[记录]Python2.7使用argparse模块

# -*- coding: utf8 -*-

import argparse

#ArgumentParser.add_argument(name or flags…[, action][, nargs][, const][, default][, type][, choices][, required][, help][, metavar][, dest])
#action:默认是store:保存值到参数名中;store_const:值存放在const中;store_true和store_false:值存为True或False;append:存为列表;append_const:存为列表,会根据const关键参数进行添加;count:统计参数出现的次数
#nargs: 指定参数值得个数,值可以为整数N(N个),*(任意多个),+(一个或更多),值为?时,首先从命令行获得参数,若没有则从const获得,然后从default获得
#const:保存一个常量
#type:这个参数用来指定参数的类型
#choices: 这个参数用来检查输入参数的范围
#required: 当某个选项指定需要在命令中出现的时候用这个参数
#help: 使用这个参数描述选项作用
#dest: 这个参数相当于把位置或者选项关联到一个特定的名字
#metavar: 这个参数用于help信息输出中 parser = argparse.ArgumentParser(description="say something about this application !!")
parser.add_argument("-a", "--age", type=str, dest='aaa', metavar=('123'), nargs="*", help="I can tell you how to set a name argument.")
parser.add_argument("-b", "--bool", dest='bbb', help="I can tell you how to set a name argument.", action="store_true")
parser.add_argument("-c", "--count", dest='ccc', help="this is an optional argument", type=int, choices=[0, 1, 2])
parser.add_argument("-v", "--verbose", dest='ddd', action="count", default=0, help="increase output verbosity")
result = parser.parse_args()
answer = result.ccc**2 if result.ddd >= 2:
print "the square of {} equals {}".format(result.ccc, answer)
elif result.ddd >= 1:
print "{}^2 == {}".format(result.ccc, answer)
else:
print answer print result.aaa
print result.bbb
print result.ddd '''
使用示例:
#python args.py -b --count 2 -a 123 456 789 -vvvvv
the square of 2 equals 4
['123', '456', '789']
True
5
'''

  

上一篇:nginx upload module的使用


下一篇:数组去重(ES5、ES6)