本文共 1038 字,大约阅读时间需要 3 分钟。
argparse是python 内置的用于命令行选项与参数解析的模块使用一般分为三步,创建ArgumentParser()对象,调用add_argument() 方法添加参数,调用parse_args()解析添加的参数其中参数有分为可以参数和必选参数下面的例子包含了可选参数和必选参数,下面的--sum 属于可选参数import argparseparser=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.pyusage: test.py [-h] integertest.py: error: too few arguments[root@localhost kernel]# python test.py 123123[root@localhost kernel]# python test.py asdfusage: test.py [-h] integertest.py: error: argument integer: invalid int value: 'asdf'[root@localhost kernel]# python test.py -husage: test.py [-h] integerpositional arguments: integer display a numberoptional arguments: -h, --help show this help message and exit[root@localhost kernel]# python test.py 1 2 --sum3[root@localhost kernel]# python test.py 1 22[root@localhost kernel]#
转载地址:http://cvnmi.baihongyu.com/