python内置库--argparse

1 关于argparse

从命令行工具运行python时,argparse 可以解析命令行工具输入的各种数据,通过argparse提供的函数或者属性,我们可以获得它解析到的数据

通过argparse,我们也可以自定义命令行选项,比如pytest -s -v ,-s -v就是pytest定义的命令行选项,通过argparse,我们也可以定义自己的命令行选项

下面是一个例子
image
命令行执行 python argparse_a.py a b
image
可以看到在命令行执行python文件时输入的参数 a b,通过argparse,我们得到了这2个参数

现在执行 python argparse_a.py -o ad a b
image
然后再,在我们执行命令的目录下面,多了一个ad文件
这些都是argparse解析命令行数据的功劳

2 argparse的使用

argparse的核心功能就3步
第一步 生成一个ArgumentParser这个类的实例对象parser
image
上面使用了prog等参数字段,具体意思后面会说到,这里也可以像之前的例子不加任何参数

第二步 在parser对象上添加参数名,这些参数就是我们命令行执行时要用到的
image
总的来说,添加参数名时,有3种类型的参数,positional arguments, options that accept values, and on/off flags

第三步 从parser对象上提取具体的参数数据,这些参数数据大部分是我们在命令行输入的数据
image
如上,通过parse_args()方法返回的对象加上参数名,我们就可以得到具体的参数数据

class argparse.ArgumentParser()

执行ArgumentParser()时,括号里接受下面这些参数来创建一个对象

  • prog - The name of the program (default: os.path.basename(sys.argv[0]))

  • usage - The string describing the program usage (default: generated from arguments added to parser)

  • description - Text to display before the argument help (by default, no text)

  • epilog - Text to display after the argument help (by default, no text)

  • parents - A list of ArgumentParser objects whose arguments should also be included

  • formatter_class - A class for customizing the help output

  • prefix_chars - The set of characters that prefix optional arguments (default: ‘-‘)

  • fromfile_prefix_chars - The set of characters that prefix files from which additional arguments should be read (default: None)

  • argument_default - The global default value for arguments (default: None)

  • conflict_handler - The strategy for resolving conflicting optionals (usually unnecessary)

  • add_help - Add a -h/--help option to the parser (default: True)

  • allow_abbrev - Allows long options to be abbreviated if the abbreviation is unambiguous. (default: True)

  • exit_on_error - Determines whether or not ArgumentParser exits with error info when an error occurs. (default: True)

prog

这个字段会影响到program name的值,默认情况下,它是通过sys.argv[0]来取值的,即在命令行python后面紧邻的那一段文本中最后一部分,比如py文件的文件名
默认情况下是像这样
image

现在加上pro参数
image

image

usage

默认情况下 显示自定义的参数字段
image

加上usage后
image

image

description

添加该参数
image
image
如上,可看出默认情况下并没有相关数据的显示

还有很多其他参数,可具体查看官网

add_argument()

该方法也可以在括号中添加多个参数,如下

  • 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 and if it is absent from the namespace object.

  • type - The type to which the command-line argument should be converted.

  • choices - A sequence 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()

action

action参数值表示,我们在命令行中的参数数据应该被怎样处理,该参数默认值是store
action='store. 这是默认的处理方式,可以不用故意写出来,默认就是这样

action='store_const'
image

如上,未设置ab ac的值,在第一个日志输出记录中,ab ac值被自动设定为const的值,这就是store_const的作用,它使得参数值来自于const,而不是来自于命令行定义的数据。而且此时是不能在命令行为这些有'store_const'的参数字段定义值 如下
image

在前面有输出日志数据的图中,第一行日志中有值,而第2行ab ac是None,这和解析时使用parse_args()是否带参数有关系,是否带参数决定了他们的数据来源。 要在解析时不带参数的情况下输出参数对应的const值而非None, 可在命令行写出参数名即可,如下
image

不过对于ad这样的positional arguments,解析时使用parse_args()是否带参数并没有什么不同,这一点暂时还没搞明白

对于store_const,官方说它是经常用于像ab ac这样的optional arguments,个人也觉得定义参数的时候最好定义为ab ac这样的optional arguments,这种是可选参数,通过参数名比较容易使用,而对于ad这样的positional arguments,是必须要定义参数值的(除非有default或者const等),更麻烦的是很容易把位置搞混导致参数对不上

'store_true' and 'store_false'
和action='store_const'类似
image

image

append
image

append_const
image
如上,append_const常常和dest参数合用,dest可指定一个变量名用于parse_args()解析
合用时,参数值会被append到dest这个list中,当多个参数字段值被放到一个list中,常常合用append_const和dest

append_cons和append的的区别是,前者是把多个参数字段的值存到一个list,后者是把一个参数字段的多个值存到一个list

有dest后,就不能通过parse_args()返回的对象加上参数名来获取参数值了,参数值全部在dest这个list中

上面在parse_args()加上参数名可以解析到dest这个list
不加参数的话解析出dest的值是None
原因前面说过,加参数与否,解析的数据来源是不同的。不加参数的情况如何解析出dest即append_const后的值 如下,,命令行写出参数字段即可,不要指定字段的值
image

注意,存在append_const时,该参数字段的值只能来源于const这个参数,如果在命令行指定该参数字段的值是会报错的,这点和store_const类似。如下
image

'count'
image
没有看懂到底有啥作用,好像就是统计参数字段出现的次数

posted @   工作手记  阅读(261)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
点击右上角即可分享
微信分享提示