参考文献

argparse

简单用法

1
2
3
4
5
6
7
8
9
10
# 创建解析器
parser = argparse.ArgumentParser(
prog='ProgramName',
description='What the program does',
epilog='Text at the bottom of help')
# 添加参数
parser.add_argument('filename') # positional argument
parser.add_argument('-c', '--count') # option that takes a value
parser.add_argument('-v', '--verbose',
action='store_true') # on/off flag

add_argument()

Name Description Values
action 指定应如何处理参数 'store', 'store_const', 'store_true', 'append', 'append_const', 'count', 'help', 'version'
choices 将值限制为一组特定的选项 ['foo', 'bar'], range(1, 10), or Container instance
const 存储常量值
default 没有设置值情况下的默认参数 默认为 None
dest 指定 result 命名空间中使用的属性名称 argparse默认的变量名是---后面的字符串,但是也可以通过dest=xxx来设置参数的变量名,然后在代码中用args.xxx来获取参数的值
help 参数的帮助消息
metavar 参数的备用显示名称,如 help 中所示
nargs 参数可以使用的次数 N 参数的绝对个数(例如:3)
‘?’ 0或1个参数
‘*’ 0或所有参数
‘+’ 所有,并且至少一个参数
required 指示参数是必需的还是可选的 True or False
type 自动将参数转换为给定类型 intfloatargparse 的 Json 函数。FileType('w')或可调用函数