官方文档
argparse --- 命令行选项、参数和子命令解析器 — Python 3.10.2 文档
别人的笔记
Argparse 教程 — Python 3.10.2 文档https://docs.python.org/zh-cn/3/howto/argparse.html#id1完整的argparse的API
argparse --- 命令行选项、参数和子命令解析器 — Python 3.8.12 文档https://docs.python.org/zh-cn/3.8/library/argparse.html
一个简单的例子
import argparseparser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('integers', metavar='N', type=int, nargs='+',help='an integer for the accumulator')
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))
parser = argparse.ArgumentParser(description='Process some integers.')
Process some integers是标题
parser是实例化的一个对象
add_argument()可以添加参数,接受参数是一个字典类型,主要方式是name=value。里面包含string类型的数据
如果没有提供位置参数,或者只提供了一个,并且看起来不像选项字符串,则分析位置参数
参数列表
-
prog - The name of the program (default:
os.path.basename(sys.argv[0])
) -
usage - 描述程序用途的字符串(默认值:从添加到解析器的参数生成),比如+,-,*,\
-
description - 在参数帮助文档之前显示的文本(默认值:无)
-
epilog - 在参数帮助文档之后显示的文本(默认值:无)
-
parents - 一个 ArgumentParser 对象的列表,它们的参数也应包含在内
-
formatter_class - 用于自定义帮助文档输出格式的类
-
prefix_chars - 可选参数的前缀字符集合(默认值: '-')
-
fromfile_prefix_chars - 当需要从文件中读取其他参数时,用于标识文件名的前缀字符集合(默认值:
None
) -
argument_default - 参数的全局默认值(默认值:
None
) -
conflict_handler - 解决冲突选项的策略(通常是不必要的)
-
add_help - 为解析器添加一个
-h/--help
选项(默认值:True
) -
allow_abbrev - 如果缩写是无歧义的,则允许缩写长选项 (默认值:
True
) -
exit_on_error - 决定当错误发生时是否让 ArgumentParser 附带错误信息退出。 (默认值:
True
)
在 3.5 版更改: 增加了 allow_abbrev 参数。
在 3.8 版更改: 在之前的版本中,allow_abbrev 还会禁用短旗标分组,例如 -vv
表示为 -v -v
。
在 3.9 版更改: 添加了 exit_on_error 形参。
1prog
parser = argparse.ArgumentParser(prog='myprogram')
2.nargs
parser.add_argument('bar', nargs='+', help='bar help')
3.description
parser = argparse.ArgumentParser(description='A foo that bars')
4.epilog
parser = argparse.ArgumentParser(description='A foo that bars',epilog="And that's how you'd foo a bar")
5.parents
6.formatter_class
ArgumentParser 对象允许通过指定备用格式化类来自定义帮助格式。目前,有四种这样的类
7.prefix_chars
许多命令行会使用 -
当作前缀,比如 -f/--foo
。如果解析器需要支持不同的或者额外的字符,比如像 +f
或者 /foo
的选项,可以在参数解析构建器中使用 prefix_chars=
参数。
8.fromfile_prefix_chars
9.argument_default
10.allow_abbrev
判断是否是定义过的参数