Skip to main content

参数解析

简介

argparse是Python用于解析命令行参数和选项的标准模块,用于代替已经过时的optparse模块。argparse模块的作用是用于解析命令行参数,

例如:python parseTest.py input.txt output.txt --user=name --port=8080

优点

  • 默认自带空参数时帮助提示
  • 自带帮助信息 -h

基础使用

import argparse
# 首先创建一个ArgumentParser对象
parser = argparse.ArgumentParser(description='Process some integers.')

# 添加参数
parser.add_argument('integers',
metavar='N',
type=int,
nargs='+',
help='an integer for the accumulator')

# 添加--sum则返回所有数之和,否则返回列表中的最大值
parser.add_argument('--sum',
dest='accumulate',
action='store_const',
const=sum,
default=max,
help='sum the integers (default: find the max)')

args = parser.parse_args()
print args.accumulate(args.integers)
  • 如果不给入任何参数,则显示帮助信息
 if len(sys.argv) == 1:
parser.print_help()
sys.exit(1)

参数的处理

  • 默认处理
args = parser.parse_args()

# 判断单个参数
if args.xxx:
  • 对象化
args = vars(parser.parse_args())

# 判断单个参数
if xxx in args:

对象参数

argparse.ArgumentParser 的参数:

  • prog: 即运行程序的名称,默认取sys.argv[0]的值,可以修改为指定的名称
  • usage:指定usage信息的内容及格式,默认是根据你添加的信息自动生成的,可以自定义修改为指定的内容
  • description:这个程序的功能概述
  • epilog:在整个帮助信息最后添加的附加信息
  • parents:用于定义一些公共的信息供子类调用
  • formatter_class:整个信息的类定义,主要包含三个类,每个类的功能如下:
    • class argparse.RawDescriptionHelpFormatter 如何显示文本描述
    • class argparse.RawTextHelpFormatter 如何显示文本描述
    • class argparse.ArgumentDefaultsHelpFormatter 自定添加参数信息
  • prefix_chars:自定义参数个前缀类型
  • fromfile_prefix_chars:指定文件替代命令行输入参数的方式
  • argument_default
  • conflict_handler:检测是否存在相同的参数选项,不加该参数直接报错,添加该参数可以兼容(conflict_handler='resolve')
  • add_help:设置是否显示帮助信息那表之类(默认显示)
  • allow_abbrev

实例方法

方法/类作用
argparse.ArgumentParser()创建解释器 ArgumentParser 对象
argparse.Action(op,dest)返回的可调用对象可处理来自命令行的参数
argparse.RawDescriptionHelpFormatter格式化description和epilog
argparse.RawTextHelpFormatter格式化帮助文档,可保留文字直接的空格
argparse.ArgumentDefaultsHelpFormatter自动添加默认的值的信息到每一个帮助信息的参数中
argparse.MetavarTypeHelpFormatter每个参数的值都显示其type类型
argparse.Namespace()创建一个存放属性的对象并将其返回
argparse.FileType(mode,buffsiz)FileType对象用于解释器的type参数传入对象
argparse.parse_intermixed_args混合解析,把所有参数都放在列表里
argparse.parse_known_intermixed_args混合解析,返回由两个条目组成的元组

13个参数解析

add_argument() 参数 共有13个

  • name or flags - Either a name or a list of option strings, e.g. foo or -f, --foo. # 参数选项列表
  • action - The basic type of action to be taken when this argument is encountered at the command line.
  • nargs - The number of command-line arguments that should be consumed.
  • const - A constant value required by some action and nargs selections.
  • default - The value produced if the argument is absent from the command line.
  • type - The type to which the command-line argument should be converted.
  • choices - A container of the allowable values for the argument.
  • required - Whether or not the command-line option may be omitted (optionals only).
  • help - A brief description of what the argument does.
  • metavar - A name for the argument in usage messages.
  • dest - The name of the attribute to be added to the object returned by parse_args().
参数说明
name:str参数的命令行 '-f', '--foo'
action:callback|str调用该参数执行的动作
nargs
const
default参数的默认值
type指定参数的类型 int|str|
choices:list枚举参数 [a,b] a或者b
required是否必须的参数
help帮助信息
metavar
dest

参考