cli
command line interface,argparse
模块可以轻松编写用户友好的命令行界面。应用程序定义它需要什么参数,然后 argparse
将找出如何从 sys.argv
中解析这些参数,argparse
模块还会自动生成帮助和使用信息。当用户给程序提供无效参数时,该模块也会发出错误。
命令行参数类型
- positional arguments 位置参数,基于位置信息的参数
- optional arguments 选项参数
argparse
如何区分可选参数和位置参数?When parse_args() is called, optional arguments will be identified by the - prefix, and the remaining arguments will be assumed to be positional: controled by prefix_chars param in ArgumentParser。其实有个参数可以控制这个行为。
parent argparse
parents 的 add_help
参数一般都为 False,要先初始化 parent parser 再传参,如果在子 parser 后修改 parent parser ,则对子不可见。
nargs
If the nargs keyword argument is not provided, the number of arguments consumed is determined by the action. Generally this means a single command-line argument will be consumed and a single item (not a list) will be produced.
ArgumentParser objects usually associate a single command-line argument with a single action to be taken. The nargs keyword argument associates a different number of command-line arguments with a single action.
默认参数和 action 是一对一的,但是 nargs 可以多对一。
dest
Most ArgumentParser actions add some value as an attribute of the object returned by parse_args(). The name of this attribute is determined by the dest keyword argument of add_argument(). For positional argument actions, dest is normally supplied as the first argument to add_argument()。
For optional argument actions, the value of dest is normally inferred from the option strings. ArgumentParser generates the value of dest by taking the first long option string and stripping away the initial --
string. If no long option strings were supplied, dest will be derived from the first short option string by stripping the initial -
character. Any internal -
characters will be converted to _
characters to make sure the string is a valid attribute name.
对于选项参数,变量名优先使用长选项,在使用短选项,如果长选项中有连字符,则使用下划线替换。
模糊的参数
有时传参会导致解析不明确,可以使用 --
,在 --
之后的参数都是位置参数。
subparser
一个 sub parser 就相当于一个子命令,一般使用 set_defaults 绑定一个函数使用。参考 airflow
。
使用抽象可以让调用方和参数互换,parser.add_arguments,arg.add_to_parser(parser).
group
可以把相似的命令放到同一个 group 下。
互斥参数
1 | group = parser.add_mutually_exclusive_group() |