https://docs.python.org/2.7/library/argparse.html#module-argparse
看了一下python对于参数的处理,了解了argparse这个模块
import argparse
parser = 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)
第一步:定义一个argparse对象
使用argparse.ArgumentParser()来定义argparse对象
具体参数详见https://docs.python.org/2.7/library/argparse.html#argumentparser-objects
class argparse.ArgumentParser(prog=None, usage=None, description=None, epilog=None, parents=[], formatter_class=argparse.HelpFormatter, prefix_chars='-', fromfile_prefix_chars=None, argument_default=None, conflict_handler='error', add_help=True)¶
第二步:添加参数arguments
使用add_argument()来添加参数
参数分为Positional Argument 和 Optional Argument
区分Positional Argument 和 Optional Argument 通过上文中argparse.ArgumentParser()的prefix_chars来定义,默认为“-”
具体参数详见https://docs.python.org/2.7/library/argparse.html#argumentparser-objects
class argparse.ArgumentParser(prog=None, usage=None, description=None, epilog=None, parents=[], formatter_class=argparse.HelpFormatter, prefix_chars='-', fromfile_prefix_chars=None, argument_default=None, conflict_handler='error', add_help=True)
Create a new ArgumentParser object. All parameters should be passed as keyword arguments. Each parameter has its own more detailed description below, but in short they are:
第三步:将参数转化为指定命名空间的属性
parser.parse_args()来实现这一功能
具体参数详见https://docs.python.org/2.7/library/argparse.html#the-parse-args-method
在示例代码中-v -q 为同组的互斥参数add_mutually_exclusive_group(),两个参数只可以出现一个,但不是必须出现。https://docs.python.org/2.7/library/argparse.html#mutual-exclusion
示例代码演示
1、
python ex1.py -h
usage: ex1.py [-h] [-v | -q] x y
calculate X to the power of Y
positional arguments:
x the base
y the exponent
optional arguments:
-h, --help show this help message and exit
-v, --verbose
-q, --quiet
2、
python ex1.py 2 3
2^3 == 8
3、
python ex1.py 2 3 -v
2 to the power 3 equals 8
4、
python ex1.py 2 3 -q
8
5、
python ex1.py
usage: ex1.py [-h] [-v | -q] x y
ex1.py: error: too few arguments
6、
python ex1.py 2 3 -v -q
usage: ex1.py [-h] [-v | -q] x y
ex1.py: error: argument -q/--quiet: not allowed with argument -v/--verbose