python的argparse 模块测试

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/tiantao2012/article/details/87381362
argparse是python 内置的用于命令行选项与参数解析的模块
使用一般分为三步,
创建ArgumentParser()对象,调用add_argument() 方法添加参数,调用parse_args()解析添加的参数
其中参数有分为可以参数和必选参数
下面的例子包含了可选参数和必选参数,下面的--sum 属于可选参数

import argparse
parser=argparse.ArgumentParser()
parser.add_argument('integer',type=int,metavar='N',nargs='+',help="display a number")
parser.add_argument('--sum',dest='accumulate',action='store_const',const=sum,default=max,help="sum the  number")
args=parser.parse_args()
print args.accumulate(args.integer)




[root@localhost kernel]# python test.py
usage: test.py [-h] integer
test.py: error: too few arguments
[root@localhost kernel]# python test.py 123
123
[root@localhost kernel]# python test.py asdf
usage: test.py [-h] integer
test.py: error: argument integer: invalid int value: 'asdf'
[root@localhost kernel]# python test.py -h
usage: test.py [-h] integer

positional arguments:
  integer     display a number

optional arguments:
  -h, --help  show this help message and exit
[root@localhost kernel]# python test.py 1 2 --sum
3
[root@localhost kernel]# python test.py 1 2
2
[root@localhost kernel]#

猜你喜欢

转载自blog.csdn.net/tiantao2012/article/details/87381362