python argparse模块粗略了解

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=Noneusage=Nonedescription=Noneepilog=Noneparents=[]formatter_class=argparse.HelpFormatterprefix_chars='-'fromfile_prefix_chars=Noneargument_default=Noneconflict_handler='error'add_help=True)

  • prog - The name of the program (default: sys.argv[0])

  • usage - The string describing the program usage (default: generated from arguments added to parser)

  • description - Text to display before the argument help (default: none)

  • epilog - Text to display after the argument help (default: none)

  • parents - A list of ArgumentParser objects whose arguments should also be included

  • formatter_class - A class for customizing the help output

  • prefix_chars - The set of characters that prefix optional arguments (default: ‘-‘)

  • fromfile_prefix_chars - The set of characters that prefix files from which additional arguments should be read (default: None)

  • argument_default - The global default value for arguments (default: None)

  • conflict_handler - The strategy for resolving conflicting optionals (usually unnecessary)

  • add_help - Add a -h/--help option to the parser (default: 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=Noneusage=Nonedescription=Noneepilog=Noneparents=[]formatter_class=argparse.HelpFormatterprefix_chars='-'fromfile_prefix_chars=Noneargument_default=Noneconflict_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:

  • prog - The name of the program (default: sys.argv[0])

  • usage - The string describing the program usage (default: generated from arguments added to parser)

  • description - Text to display before the argument help (default: none)

  • epilog - Text to display after the argument help (default: none)

  • parents - A list of ArgumentParser objects whose arguments should also be included

  • formatter_class - A class for customizing the help output

  • prefix_chars - The set of characters that prefix optional arguments (default: ‘-‘)

  • fromfile_prefix_chars - The set of characters that prefix files from which additional arguments should be read (default: None)

  • argument_default - The global default value for arguments (default: None)

  • conflict_handler - The strategy for resolving conflicting optionals (usually unnecessary)

  • add_help - Add a -h/--help option to the parser (default: True)

第三步:将参数转化为指定命名空间的属性

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

猜你喜欢

转载自blog.51cto.com/quietguoguo/2304829
今日推荐