import argparse
parser = argparse.ArgumentParser()
parser.add_argument("square",help="display a square of a given number",type=int)
args = parser.parse_args()print(args.square**2)
将上述程序存入名为test.py的文件中,在cmd窗口调用,输入不同数据执行结果如下:
当没有输入参数时,会报错,因为选项square是位置参数,是必须输入的。
当输入数字4时,成功返回计算结果。
当输入字符串four时,程序执行出错,提示需要输入数字。
不同输入参数名,不然会被当做输入给参数的字符串去执行。
参看该程序的帮助命令,可以看到该程序有位置参数和可选参数两类。
$ python test.py
usage: test.py [-h] square
test.py: error: the following arguments are required: square
$ python test.py 4
16
$ python test.py four
usage: test.py [-h] square
test.py: error: argument square: invalid int value: 'four'
$ python test.py square 4
usage: test.py [-h] square
test.py: error: argument square: invalid int value: 'square'
$ python test.py -h
usage: test.py [-h] square
positional arguments:
square display a square of a given number
optional arguments:
-h, --help show this help message and exit
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("square",help="display a square of a given number",type=int)
parser.add_argument("--verbosity",help="increase output verbosity")
args = parser.parse_args()if args.verbosity:print("the square of "+str(args.square)+" is "+str(args.square**2))else:print(args.square**2)
输入不同参数执行如下:
给参数 verbosity 传参为1,回显详细输出内容。
不调用参数 verbosity ,回显简要输出内容。
当调用参数 verbosity 又不传参时,程序出错,应为该参数还没设置默认参数。
参看帮助,有两个可选参数分别是 help 和 verbosity 。
$ python test.py 4 --verbosity 1 # 效果等同 python test.py --verbosity 1 4
the square of 4 is 16
$ python test.py 4
16
$ python test.py 4 --verbosity
usage: test.py [-h] [--verbosity VERBOSITY] square
test.py: error: argument --verbosity: expected one argument
$ python test.py -h
usage: test.py [-h] [--verbosity VERBOSITY] square
positional arguments:
square display a square of a given number
optional arguments:
-h, --help show this help message and exit
--verbosity VERBOSITY
increase output verbosity
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("square",help="display a square of a given number",type=int)
parser.add_argument("-v","--verbose",help="increase output verbosity",action="store_true")
args = parser.parse_args()if args.verbose:print("the square of "+str(args.square)+" is "+str(args.square**2))else:print(args.square**2)
输入不同参数执行如下:调用参数 -v ,无需传参,更符合该参数对应功能的使用习惯。
$ python test.py -v 4
the square of 4 is 16
$ python test.py 4 -v
the square of 4 is 16