官方文档https://docs.python.org/zh-cn/3.7/howto/argparse.html https://docs.python.org/zh-cn/3.7/library/argparse.html#module-argparse
基础功能 --help
选项,也可缩写为 -h
,是唯一一个可以直接使用的选项
基础 import argparseparser = argparse.ArgumentParser() parser.parse_args()
位置参数 默认参数类型 import argparseparser = argparse.ArgumentParser() parser.add_argument("echo" , help="echo the string you use here" ) args = parser.parse_args() print(args.echo)
>python exer.py -h usage: exer.py [-h] echo positional arguments: echo optional arguments: -h, --help show this help message and exit
接收echo参数(字符串格式),并打印
>python exer.py helloworld helloworld
其它类型 import argparseparser = argparse.ArgumentParser() parser.add_argument("square" , help="display a square of a given number" , type=int) args = parser.parse_args() print(args.square**2 )
计算平方
可选参数 import argparseparser = argparse.ArgumentParser() parser.add_argument("--verbosity" , help="increase output verbosity" ) args = parser.parse_args() if args.verbosity: print("verbosity turned on" )
不输入参数不报错
help
>python exer.py -h usage: exer.py [-h] [--verbosity VERBOSITY] optional arguments: -h, --help show this help message and exit --verbosity VERBOSITY increase output verbosity
需要指定参数的具体值
>python exer.py --verbosity usage: exer.py [-h] [--verbosity VERBOSITY] exer.py: error: argument --verbosity: expected one argument
> python exer.py --verbosity 1 verbosity turned on
action=store_true
"store_true"
意味着,当这一选项存在时,为 args.verbose
赋值为 True
。没有指定时则隐含地赋值为 False
。
parser.add_argument("--verbose" , help="increase output verbosity" , action="store_true" )
短选项 parser.add_argument("-v" , "--verbose" , help="increase output verbosity" , action="store_true" )
>python exer.py -h usage: exer.py [-h] [-v] optional arguments: -h, --help show this help message and exit -v, --verbose increase output verbosity
此时,该项依旧为可选项。若去掉--verbose
只留下-v
,则该项为必需项
结合位置参数和可选参数 import argparseparser = argparse.ArgumentParser() parser.add_argument("square" , type=int, help="display a square of a given number" ) parser.add_argument("-v" , "--verbose" , action="store_true" , help="increase output verbosity" ) args = parser.parse_args() answer = args.square**2 if args.verbose: print("the square of {} equals {}" .format(args.square, answer)) else : print(answer)
>python exer.py -h usage: exer.py [-h] [-v] square positional arguments: square display a square of a given number optional arguments: -h, --help show this help message and exit -v, --verbose increase output verbosity
若没有参数,则报错
两个参数的顺序可以颠倒
>python exer.py 5 -v the square of 5 equals 25
>python exer.py -v 5 the square of 5 equals 25
参数取值范围限制 import argparseparser = argparse.ArgumentParser() parser.add_argument("square" , type=int, help="display a square of a given number" ) parser.add_argument("-v" , "--verbosity" , type=int, choices=[0 , 1 , 2 ], help="increase output verbosity" ) args = parser.parse_args() answer = args.square**2 if args.verbosity == 2 : print("the square of {} equals {}" .format(args.square, answer)) elif args.verbosity == 1 : print("{}^2 == {}" .format(args.square, answer)) else : print(answer)
>python exer.py -v 2 4 the square of 4 equals 16
>python exer.py -v 1 4 4^2 == 16
action=”count”
参数值为该参数出现了几次
import argparseparser = argparse.ArgumentParser() parser.add_argument("square" , type=int, help="display the square of a given number" ) parser.add_argument("-v" , "--verbosity" , action="count" , help="increase output verbosity" ) args = parser.parse_args() answer = args.square**2 if args.verbosity == 2 : print("the square of {} equals {}" .format(args.square, answer)) elif args.verbosity == 1 : print("{}^2 == {}" .format(args.square, answer)) else : print(answer)
>python exer.py -v 0 0^2 == 0
>python exer.py -v 0 -v the square of 0 equals 0
>python exer.py -vv 0 the square of 0 equals 0
关键字default
parser.add_argument("-v" , "--verbosity" , action="count" , default=0 , help="increase output verbosity" )
默认情况下如果一个可选参数没有被指定,它的值会是 None
,并且它不能和整数值相比较(所以产生了 TypeError
异常)。
改进 import argparseparser = argparse.ArgumentParser() parser.add_argument("x" , type=int, help="the base" ) parser.add_argument("y" , type=int, help="the exponent" ) parser.add_argument("-v" , "--verbosity" , action="count" , default=0 ) args = parser.parse_args() answer = args.x**args.y if args.verbosity >= 2 : print("{} to the power {} equals {}" .format(args.x, args.y, answer)) elif args.verbosity >= 1 : print("{}^{} == {}" .format(args.x, args.y, answer)) else : print(answer)
修改部分内容为
if args.verbosity >= 2 : print("Running '{}'" .format(__file__))
>python exer.py -vv 0 8 Running 'exer.py' 0^8 == 0
矛盾选项 import argparseparser = argparse.ArgumentParser(description="calculate X to the power of Y" ) group = parser.add_mutually_exclusive_group() group.add_argument("-v" , "--verbose" , action="store_true" ) group.add_argument("-q" , "--quiet" , action="store_true" ) parser.add_argument("x" , type=int, help="the base" ) parser.add_argument("y" , type=int, help="the exponent" ) args = parser.parse_args() answer = args.x**args.y if args.quiet: print(answer) elif args.verbose: print("{} to the power {} equals {}" .format(args.x, args.y, answer)) else : print("{}^{} == {}" .format(args.x, args.y, answer))
参数-v
和-q
不可以同时使用
argparse
— 命令行选项、参数和子命令解析器https://docs.python.org/zh-cn/3.7/library/argparse.html#argparse.ArgumentParser.add_argument
官方文档写的太好了,我重写一遍意义不大,大家直接去看官方文档吧
add_argument() 方法
ArgumentParser.add_argument(name or flags… [, action ][, nargs ][, const ][, default ][, type ][, choices ][, required ][, help ][, metavar ][, dest ])
action store ...: parser = argparse.ArgumentParser() ...: parser.add_argument('--foo' , action='store_true' ) ...: parser.add_argument('--bar' , action='store_false' ) ...: parser.add_argument('--baz' , action='store_false' ) ...: parser.parse_args('--foo --bar' .split()) Out[2 ]: Namespace(bar=False , baz=True , foo=True )