1. 程式人生 > >python argparse模組粗略瞭解

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=None

description=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