参考https://www.cnblogs.com/lindaxin/p/7975697.html
# python3中argparse模块 # 简单用法 import argparse parser = argparse.ArgumentParser() parser.add_argument('test') # 必选参数 add_argument()指定程序可以接受的命令行选项 parser.add_argument('--test_a') # 可选参数 args = parser.parse_args() # parse_args()从指定的选项中返回一些数据 print(args) print(args.test) print(args.test_a) # cmd执行: python tests.py 1 --test 2 # 输出: Namespace(test='1', test_a='2') 1 2 混合使用 定位参数和选项参数可以混合使用,看下面一个例子,给一个整数序列,输出它们的和或最大值(默认): import argparse parser = 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) 结果: $ python argparse_usage.py usage: argparse_usage.py [-h] [--sum] N [N ...] argparse_usage.py: error: too few arguments $ python argparse_usage.py 1 2 3 4 4 $ python argparse_usage.py 1 2 3 4 --sum 10 add_argument() 方法 add_argument() 方法定义如何解析命令行参数:
parser = argparse.ArgumentParser(prog='my - program', usage='%(prog)s [options] usage',description = 'my - description',epilog = 'my - epilog')
创建一个ArgumentParser实例,ArgumentParser的参数都为关键字参数。
prog :文件名,默认为sys.argv[0],用来在help信息中描述程序的名称。
usage :描述程序用途的字符串
description :help信息前显示的信息
epilog :help信息之后显示的信息
ArgumentParser.add_argument(name or flags...[, action][, nargs][, const][, default][, type][, choices][, required][, help][, metavar][, dest]) 每个参数解释如下: name or flags - 选项字符串的名字或者列表,例如 foo 或者 -f, --foo。 action - 命令行遇到参数时的动作,默认值是 store。 store_const,表示赋值为const; append,将遇到的值存储成列表,也就是如果参数重复则会保存多个值; append_const,将参数规范中定义的一个值保存到一个列表; count,存储遇到的次数;此外,也可以继承 argparse.Action 自定义参数解析; nargs - 应该读取的命令行参数个数,可以是具体的数字,或者是?号,当不指定值时对于 Positional argument 使用 default,对于 Optional argument 使用 const;或者是 * 号,表示 0 或多个参数;或者是 + 号表示 1 或多个参数。 const - action 和 nargs 所需要的常量值。 default - 不指定参数时的默认值。 type - 命令行参数应该被转换成的类型。 choices - 参数可允许的值的一个容器。 required - 可选参数是否可以省略 (仅针对可选参数)。 help - 参数的帮助信息,当指定为 argparse.SUPPRESS 时表示不显示该参数的帮助信息. metavar - 在 usage 说明中的参数名称,对于必选参数默认就是参数名称,对于可选参数默认是全大写的参数名称. dest - 解析后的参数名称,默认情况下,对于可选参数选取最长的名称,中划线转换为下划线.
# 添加子参数: import argparse parse = argparse.ArgumentParser() parse.add_argument('a') res = parse.add_subparsers(dest='he') # res.required = True son_res = res.add_parser('m', help='son command,name must be m') # 添加描述信息等 //不要写成(add_parser('-m')) son_res.add_argument('-son', default='333') # son_res.add_argument('-son', choice=['1','2','3']) # print(parse.abc) print(parse) a = parse.parse_args() print(a) print(a.son) # // 运行:python test.py one m -son 999 # // 结果: # ArgumentParser(prog='test_a.py', usage=None, description=None, # formatter_class=<class 'argparse.HelpFormatter'>, conflict_handler='error', add_help=True) # Namespace(a='one', he='m', son='999') # 999
来源:https://www.cnblogs.com/lajiao/p/9553726.html