> 文档中心 > 还有人不知道ArgumentParser命令行解析器——我不允许

还有人不知道ArgumentParser命令行解析器——我不允许


👦👦一个帅气的boy,你可以叫我Love And Program
🖱 ⌨个人主页:l。Ve的个人主页
💖💖如果对你有帮助的话希望三连💨💨支持一下博主

在这里插入图片描述

一文搞懂ArgumentParser命令行解析器

  • 1 前言
  • 2 上才艺——ArgumentParser()
    • prog
    • usage
    • description
    • epilog
    • parents
    • formatter_class
    • prefix_chars
    • fromfile_prefix_chars
    • allow_abbrev
    • conflict_handler
    • add_help
    • exit_on_error

1 前言

没想到我会在这上面出差错,结果框框报错,找别的文章就甩一段翻译😂😂我还真没看明白,今天直接上实战搞懂他。

官方文档传送门


2 上才艺——ArgumentParser()

class argparse.ArgumentParser(prog=None, usage=None, description=None,  epilog=None, parents=[], formatter_class=argparse.HelpFormatter,  prefix_chars='-',fromfile_prefix_chars=None, argument_default=None, conflict_handler='error',  add_help=True, allow_abbrev=True, exit_on_error=True)

prog

  • prog:解释器名字,默认状态下为文件名,也就是说你可选择不输入。
import argparseparser = argparse.ArgumentParser(prog='Program')parser.print_help()parser = argparse.ArgumentParser()parser.print_help()

结果:

usage: Program [-h]Process Testoptional arguments:  -h, --help  show this help message and exit#——————————————————————————————————————————————————————————————————————————usage: Add_command_Function.py [-h]optional arguments:  -h, --help  show this help message and exit

usage

  • usage:描述程序用途的字符串,默认情况下他会输出[-h],如果你加上add_argument函数,他也会显示
parser = argparse.ArgumentParser(prog='Program',usage="我是usage,而且我还也可以用%(prog)s覆盖prog", description="Process Test")parser.print_help()parser = argparse.ArgumentParser(prog='Program', description="Process Test")parser.add_argument("-f",help="first thing")parser.print_help()
usage: 我是usage,而且我还也可以用Program覆盖progProcess Testoptional arguments:  -h, --help     show this help message and exit#----------------------------------------------------------------------------usage: Program [-h] [-f F]Process Testoptional arguments:  -h, --help  show this help message and exit  -f F first thing

description

  • description:当你使用命令行不加参数时就会出现它

命令行输入python Add_command_Function.py

parser = argparse.ArgumentParser( description="大家好,我是description")parser.print_help()

输出:

usage: Add_command_Function.py [-h] [-f F]大家好,我是descriptionoptional arguments:  -h, --help  show this help message and exit

epilog

  • epilog:在参数帮助文档之后显示的文本
parser = argparse.ArgumentParser( description="大家好,我是description",epilog="我是结尾哦")parser.print_help()

结果:

usage: Add_command_Function.py [-h]大家好,我是descriptionoptional arguments:  -h, --help  show this help message and exit我是结尾哦

parents

👇👇传送至add_help

  • parents:理解为单个解析器通过此值来引用其他ArgumentParser 对象列表加到自己里面
parser = argparse.ArgumentParser( description="大家好,我是description",epilog="我是结尾哦",add_help=False)parser.add_argument("-f",help="first thing",type=int)Two_parser = argparse.ArgumentParser(parents=[parser])Two_parser.add_argument("-s",help="first thing")Two_parser.parse_args(['-f', '2'])#命令行 : python Add_command_Function.py -s

结果:

usage: Add_command_Function.py [-f F]大家好,我是descriptionoptional arguments:  -f F  first thing我是结尾哦

formatter_class

  • formatter_class :理解为对解析器内的内容进行一个合适的格式化格式,有四种格式,最常用的是RawDescriptionHelpFormatterRawTextHelpFormatter类。
  1. class argparse.RawDescriptionHelpFormatter:允许使用格式,默认情况下不会有换行
parser = argparse.ArgumentParser( description='''  this description     was indented weird     but that is okay''',epilog="我是结尾哦",add_help=False,formatter_class=argparse.RawDescriptionHelpFormatter)parser.add_argument("-f",help="first thing",type=int)parser.print_help()#usage: Add_command_Function.py [-f F]#     this description#     was indented weird#     but that is okay
  1. class argparse.RawTextHelpFormatter:

这东西和上面具体啥差别呢??试了一下,这里不太严谨,因为没试出啥大区别,有人知道可以和大家分享一下,不过更推荐第二种,因为...人家描述的多😂😂🤣🤣

  1. class argparse.ArgumentDefaultsHelpFormatter:添加默认的值的信息到每一个帮助信息的参数
  2. class argparse.MetavarTypeHelpFormatter:显示加入命令行type类型(真鸡肋啊)
parser = argparse.ArgumentParser( description="大家好,我是description",epilog="我是结尾哦",add_help=False,formatter_class=argparse.MetavarTypeHelpFormatter)parser.add_argument("-f",help="first thing",type=int)parser.add_argument('bar', type=float)parser.add_argument('-cc', type=float)parser.print_help()#usage: Add_command_Function.py [-f int] [-cc float] float#大家好,我是description#positional arguments:#  float#optional arguments:#  -f int     first thing#  -cc float#我是结尾哦

prefix_chars

  • prefix_chars:通俗理解为你可以修改命令行默认参数的前缀,我们在大多程序下用的都是'-',这也是默认的情况,但是有了它你就可以修改默认值。
parser = argparse.ArgumentParser( description='''这是一个程序''',epilog="我是结尾哦",prefix_chars="+")parser.add_argument("-f",help="first thing",type=int)

命令行用python Add_command_Function.py +f可以,但是依然可以用python Add_command_Function.py -f😡😡我不李姐

fromfile_prefix_chars

  • fromfile_prefix_chars:将命令存入一个文件中从而不需要在命令行打出来(如果说这个函数真的有一个参数最有用的话那就是它)
with open('args.txt', 'w') as fp:    fp.write('-f\n1111\n-d\n1.222')parser = argparse.ArgumentParser( description='''这是一个程序''',epilog="我是结尾哦",fromfile_prefix_chars='@')parser.add_argument("-f",help="first thing",type=int)parser.add_argument("-c",help="first thing",type=float)parser.add_argument("-d",help="first thing",type=float)args =parser.parse_args(['@args.txt'])print(args.f,args.d)#结果#1111 1.222

allow_abbrev

  • allow_abbrev:如果缩写是无歧义的,则允许缩写长选项,啥意思呢?看看下面,默认开启状态下下面是不会报错的,会自动识别为–foonly,因为–foon被理解为它的缩写,False之后这种状态就不会被理解开始报错,如下代码所示:
parser = argparse.ArgumentParser(prog='PROG', allow_abbrev=False)parser.add_argument("--foobar",help="first thing",type=int)parser.add_argument("--foonley",help="second thing",type=float)args = parser.parse_args(['--foon','1'])print(args.foonley)#usage: PROG [-h] [--foobar FOOBAR] [--foonley FOONLEY] [-dsc DSC]#PROG: error: unrecognized arguments: --foon

conflict_handler

  • conflict_handler:非常好理解,有时候重写旧的有相同选项字符串的参数会更有用,重写旧的字符串时就用到此变量,意味着减少冲突(文档说通常不必要,相当鸡肋了)
parser = argparse.ArgumentParser(prog='PROG')parser.add_argument("-f","--fist",help="first thing",type=int)parser.add_argument("--fist",help="second thing",type=float)#python Add_command_Function.py#argparse.ArgumentError: argument --fist: conflicting option string: --fist
parser = argparse.ArgumentParser(prog='PROG', conflict_handler='resolve')parser.add_argument("-f","--fist",help="first thing",type=int)parser.add_argument("--fist",help="second thing",type=float)#python Add_command_Function.py#正常运行

add_help

☝☝传送至parents

  • add_help:为解析器添加一个 -h/–help 选项
    这个没啥多说的,就决定是否加一个help选项,但是需要注意的是要调用父解析器的话必须为Flase(见传送),若add_help为True则发生报错

exit_on_error

  • exit_on_error:3.9版本新增内容,可以理解为是否启用手动捕获错误,设为False启用。默认为True,直接返回报错。
parser = argparse.ArgumentParser(exit_on_error=False)parser.add_argument("-f",help="first thing",type=int)parser.add_argument("-c",help="first thing",type=float)try:    parser.parse_args('--integers',' a')except argparse.ArgumentError:    print('Catching an argumentError')

辛苦各位可以看到最后,此函数的用处还是相当多的,各种大型项目里面都可以看见,但是我搜到的都是直接翻译过来,看着有点懵,还不如看官方文档呢,在这里记录一下学习记录

妊娠纹产品大全