15.4. argparse — 命令行选项、参数和子命令的解析器

New in version 2.7.

Source code: Lib/argparse.py


The argparse module makes it easy to write user-friendly command-line interfaces. 程序只需定义好它要求的参数,然后argparse将负责如何从sys.argv中解析出这些参数。The argparse module also automatically generates help and usage messages and issues errors when users give the program invalid arguments.

15.4.1. 示例

下面的Python程序代码接收一个整数序列并输出它们的和或者最大值:

import argparse

parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('integers', metavar='N', type=int, nargs='+',
                   help='an integer for the accumulator')
parser.add_argument('--sum', dest='accumulate', action='store_const',
                   const=sum, default=max,
                   help='sum the integers (default: find the max)')

args = parser.parse_args()
print args.accumulate(args.integers)

Assuming the Python code above is saved into a file called prog.py, it can be run at the command line and provides useful help messages:

$ python prog.py -h
usage: prog.py [-h] [--sum] N [N ...]

Process some integers.

positional arguments:
 N           an integer for the accumulator

optional arguments:
 -h, --help  show this help message and exit
 --sum       sum the integers (default: find the max)

When run with the appropriate arguments, it prints either the sum or the max of the command-line integers:

$ python prog.py 1 2 3 4
4

$ python prog.py 1 2 3 4 --sum
10

If invalid arguments are passed in, it will issue an error:

$ python prog.py a b c
usage: prog.py [-h] [--sum] N [N ...]
prog.py: error: argument N: invalid int value: 'a'

The following sections walk you through this example.

15.4.1.1. 创建一个解析器

The first step in using the argparse is creating an ArgumentParser object:

>>> parser = argparse.ArgumentParser(description='Process some integers.')

ArgumentParser对象会保存把命令行解析成Python数据类型所需要的所有信息。

15.4.1.2. 添加参数

Filling an ArgumentParser with information about program arguments is done by making calls to the add_argument() method. Generally, these calls tell the ArgumentParser how to take the strings on the command line and turn them into objects. This information is stored and used when parse_args() is called. For example:

>>> parser.add_argument('integers', metavar='N', type=int, nargs='+',
...                     help='an integer for the accumulator')
>>> parser.add_argument('--sum', dest='accumulate', action='store_const',
...                     const=sum, default=max,
...                     help='sum the integers (default: find the max)')

接下来,调用parse_args()返回的对象将带有两个属性,integersaccumulateThe integers attribute will be a list of one or more ints, and the accumulate attribute will be either the sum() function, if --sum was specified at the command line, or the max() function if it was not.

15.4.1.3. 解析参数

ArgumentParser parses arguments through the parse_args() method. 它将检查命令行,把每个参数转换成恰当的类型并采取恰当的动作。In most cases, this means a simple Namespace object will be built up from attributes parsed out of the command line:

>>> parser.parse_args(['--sum', '7', '-1', '42'])
Namespace(accumulate=<built-in function sum>, integers=[7, -1, 42])

In a script, parse_args() will typically be called with no arguments, and the ArgumentParser will automatically determine the command-line arguments from sys.argv.

15.4.2. ArgumentParser 对象

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:

  • prog - 程序的名字(默认:sys.argv[0]
  • usage - 描述程序用法的字符串(默认:从解析器的参数生成)
  • description - 参数帮助信息之前的文本(默认:空)
  • epilog - 参数帮助信息之后的文本(默认:空)
  • parents - ArgumentParser 对象的一个列表,这些对象的参数应该包括进去
  • formatter_class - 定制化帮助信息的类
  • prefix_chars - 可选参数的前缀字符集(默认:‘-‘)
  • fromfile_prefix_chars - 额外的参数应该读取的文件的前缀字符集(默认:None
  • argument_default - 参数的全局默认值(默认:None
  • conflict_handler - 解决冲突的可选参数的策略(通常没有必要)
  • add_help - 给解析器添加-h/–help 选项(默认:True

The following sections describe how each of these are used.

15.4.2.1. prog 参数

By default, ArgumentParser objects uses sys.argv[0] to determine how to display the name of the program in help messages. 这个默认值几乎总能满足需求,因为帮助信息(中的程序名称)会自动匹配命令行中调用的程序名称。例如,参考下面这段myprogram.py文件中的代码:

import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--foo', help='foo help')
args = parser.parse_args()

The help for this program will display myprogram.py as the program name (regardless of where the program was invoked from):

$ python myprogram.py --help
usage: myprogram.py [-h] [--foo FOO]

optional arguments:
 -h, --help  show this help message and exit
 --foo FOO   foo help
$ cd ..
$ python subdir\myprogram.py --help
usage: myprogram.py [-h] [--foo FOO]

optional arguments:
 -h, --help  show this help message and exit
 --foo FOO   foo help

To change this default behavior, another value can be supplied using the prog= argument to ArgumentParser:

>>> parser = argparse.ArgumentParser(prog='myprogram')
>>> parser.print_help()
usage: myprogram [-h]

optional arguments:
 -h, --help  show this help message and exit

注意,无论是来自sys.argv[0]还是来自prog=argument,在帮助信息中都可以使用%(prog)s格式符得到程序的名字。

>>> parser = argparse.ArgumentParser(prog='myprogram')
>>> parser.add_argument('--foo', help='foo of the %(prog)s program')
>>> parser.print_help()
usage: myprogram [-h] [--foo FOO]

optional arguments:
 -h, --help  show this help message and exit
 --foo FOO   foo of the myprogram program

15.4.2.2. usage 参数

By default, ArgumentParser calculates the usage message from the arguments it contains:

>>> parser = argparse.ArgumentParser(prog='PROG')
>>> parser.add_argument('--foo', nargs='?', help='foo help')
>>> parser.add_argument('bar', nargs='+', help='bar help')
>>> parser.print_help()
usage: PROG [-h] [--foo [FOO]] bar [bar ...]

positional arguments:
 bar          bar help

optional arguments:
 -h, --help   show this help message and exit
 --foo [FOO]  foo help

The default message can be overridden with the usage= keyword argument:

>>> parser = argparse.ArgumentParser(prog='PROG', usage='%(prog)s [options]')
>>> parser.add_argument('--foo', nargs='?', help='foo help')
>>> parser.add_argument('bar', nargs='+', help='bar help')
>>> parser.print_help()
usage: PROG [options]

positional arguments:
 bar          bar help

optional arguments:
 -h, --help   show this help message and exit
 --foo [FOO]  foo help

The %(prog)s format specifier is available to fill in the program name in your usage messages.

15.4.2.3. description 参数

Most calls to the ArgumentParser constructor will use the description= keyword argument. This argument gives a brief description of what the program does and how it works. In help messages, the description is displayed between the command-line usage string and the help messages for the various arguments:

>>> parser = argparse.ArgumentParser(description='A foo that bars')
>>> parser.print_help()
usage: argparse.py [-h]

A foo that bars

optional arguments:
 -h, --help  show this help message and exit

By default, the description will be line-wrapped so that it fits within the given space. To change this behavior, see the formatter_class argument.

15.4.2.4. epilog 参数

Some programs like to display additional description of the program after the description of the arguments. Such text can be specified using the epilog= argument to ArgumentParser:

>>> parser = argparse.ArgumentParser(
...     description='A foo that bars',
...     epilog="And that's how you'd foo a bar")
>>> parser.print_help()
usage: argparse.py [-h]

A foo that bars

optional arguments:
 -h, --help  show this help message and exit

And that's how you'd foo a bar

As with the description argument, the epilog= text is by default line-wrapped, but this behavior can be adjusted with the formatter_class argument to ArgumentParser.

15.4.2.5. parents 参数

Sometimes, several parsers share a common set of arguments. Rather than repeating the definitions of these arguments, a single parser with all the shared arguments and passed to parents= argument to ArgumentParser can be used. parents=参数接受一个ArgumentParser对象的列表,然后收集它们当中所有的位置参数和可选参数,并将这些参数添加到正在构建的ArgumentParser对象:

>>> parent_parser = argparse.ArgumentParser(add_help=False)
>>> parent_parser.add_argument('--parent', type=int)

>>> foo_parser = argparse.ArgumentParser(parents=[parent_parser])
>>> foo_parser.add_argument('foo')
>>> foo_parser.parse_args(['--parent', '2', 'XXX'])
Namespace(foo='XXX', parent=2)

>>> bar_parser = argparse.ArgumentParser(parents=[parent_parser])
>>> bar_parser.add_argument('--bar')
>>> bar_parser.parse_args(['--bar', 'YYY'])
Namespace(bar='YYY', parent=None)

注意大部分父解析器将指定add_help=False否则,ArgumentParser将看到两个-h/--help 选项(一个在父解析器中,一个在子解析器中)并引发一个错误。

注意

在通过parents=传递父解析器之前,你必须完全初始化它们。If you change the parent parsers after the child parser, those changes will not be reflected in the child.

15.4.2.6. formatter_class 参数

ArgumentParser objects allow the help formatting to be customized by specifying an alternate formatting class. 当前,有三个这样的类:

class argparse.RawDescriptionHelpFormatter
class argparse.RawTextHelpFormatter
class argparse.ArgumentDefaultsHelpFormatter

The first two allow more control over how textual descriptions are displayed, while the last automatically adds information about argument default values.

By default, ArgumentParser objects line-wrap the description and epilog texts in command-line help messages:

>>> parser = argparse.ArgumentParser(
...     prog='PROG',
...     description='''this description
...         was indented weird
...             but that is okay''',
...     epilog='''
...             likewise for this epilog whose whitespace will
...         be cleaned up and whose words will be wrapped
...         across a couple lines''')
>>> parser.print_help()
usage: PROG [-h]

this description was indented weird but that is okay

optional arguments:
 -h, --help  show this help message and exit

likewise for this epilog whose whitespace will be cleaned up and whose words
will be wrapped across a couple lines

Passing RawDescriptionHelpFormatter as formatter_class= indicates that description and epilog are already correctly formatted and should not be line-wrapped:

>>> parser = argparse.ArgumentParser(
...     prog='PROG',
...     formatter_class=argparse.RawDescriptionHelpFormatter,
...     description=textwrap.dedent('''\
...         Please do not mess up this text!
...         --------------------------------
...             I have indented it
...             exactly the way
...             I want it
...         '''))
>>> parser.print_help()
usage: PROG [-h]

Please do not mess up this text!
--------------------------------
   I have indented it
   exactly the way
   I want it

optional arguments:
 -h, --help  show this help message and exit

RawTextHelpFormatter maintains whitespace for all sorts of help text, including argument descriptions.

The other formatter class available, ArgumentDefaultsHelpFormatter, will add information about the default value of each of the arguments:

>>> parser = argparse.ArgumentParser(
...     prog='PROG',
...     formatter_class=argparse.ArgumentDefaultsHelpFormatter)
>>> parser.add_argument('--foo', type=int, default=42, help='FOO!')
>>> parser.add_argument('bar', nargs='*', default=[1, 2, 3], help='BAR!')
>>> parser.print_help()
usage: PROG [-h] [--foo FOO] [bar [bar ...]]

positional arguments:
 bar         BAR! (default: [1, 2, 3])

optional arguments:
 -h, --help  show this help message and exit
 --foo FOO   FOO! (default: 42)

15.4.2.7. prefix_chars 参数

Most command-line options will use - as the prefix, e.g. -f/--foo. Parsers that need to support different or additional prefix characters, e.g. for options like +f or /foo, may specify them using the prefix_chars= argument to the ArgumentParser constructor:

>>> parser = argparse.ArgumentParser(prog='PROG', prefix_chars='-+')
>>> parser.add_argument('+f')
>>> parser.add_argument('++bar')
>>> parser.parse_args('+f X ++bar Y'.split())
Namespace(bar='Y', f='X')

The prefix_chars= argument defaults to '-'. Supplying a set of characters that does not include - will cause -f/--foo options to be disallowed.

15.4.2.8. fromfile_prefix_chars 参数

Sometimes, for example when dealing with a particularly long argument lists, it may make sense to keep the list of arguments in a file rather than typing it out at the command line. If the fromfile_prefix_chars= argument is given to the ArgumentParser constructor, then arguments that start with any of the specified characters will be treated as files, and will be replaced by the arguments they contain. For example:

>>> with open('args.txt', 'w') as fp:
...    fp.write('-f\nbar')
>>> parser = argparse.ArgumentParser(fromfile_prefix_chars='@')
>>> parser.add_argument('-f')
>>> parser.parse_args(['-f', 'foo', '@args.txt'])
Namespace(f='bar')

Arguments read from a file must by default be one per line (but see also convert_arg_line_to_args()) and are treated as if they were in the same place as the original file referencing argument on the command line. So in the example above, the expression ['-f', 'foo', '@args.txt'] is considered equivalent to the expression ['-f', 'foo', '-f', 'bar'].

The fromfile_prefix_chars= argument defaults to None, meaning that arguments will never be treated as file references.

15.4.2.9. argument_default 参数

通常情况下,参数默认值的指定通过传递一个默认值给add_argument()或者以一个指键-值对的集合调用set_defaults()方法。然而有时候,指定一个解析器范围的参数默认值会比较有用。这可以通过传递argument_default=关键字参数给ArgumentParser完成。例如,为了全局地阻止parse_args() 调用时不必要的属性创建,我们可以提供argument_default=SUPPRESS

>>> parser = argparse.ArgumentParser(argument_default=argparse.SUPPRESS)
>>> parser.add_argument('--foo')
>>> parser.add_argument('bar', nargs='?')
>>> parser.parse_args(['--foo', '1', 'BAR'])
Namespace(bar='BAR', foo='1')
>>> parser.parse_args([])
Namespace()

15.4.2.10. conflict_handler 参数

ArgumentParser对象不允许同一个选项具有两个动作。默认情况下,如果试图创建一个已经使用的选项,ArgumentParser对象将抛出异常。

>>> parser = argparse.ArgumentParser(prog='PROG')
>>> parser.add_argument('-f', '--foo', help='old foo help')
>>> parser.add_argument('--foo', help='new foo help')
Traceback (most recent call last):
 ..
ArgumentError: argument --foo: conflicting option string(s): --foo

有时候(例如使用parents的时候)简单地用相同的选项覆盖旧的参数是有用的。为了得到这样的行为,可以提供'resolve'值给ArgumentParserconflict_handler=参数:

>>> parser = argparse.ArgumentParser(prog='PROG', conflict_handler='resolve')
>>> parser.add_argument('-f', '--foo', help='old foo help')
>>> parser.add_argument('--foo', help='new foo help')
>>> parser.print_help()
usage: PROG [-h] [-f FOO] [--foo FOO]

optional arguments:
 -h, --help  show this help message and exit
 -f FOO      old foo help
 --foo FOO   new foo help

注意ArgumentParser 对象只有在所有的选项字符串被覆盖时才删除某个动作。所以,在上面的例子中,旧的-f/--foo动作依然保留为-f的动作,因为只有--foo选项字符串被覆盖。

15.4.2.11. add_help 参数

默认情况下,ArgumentParser对象会添加一个选项简单地显示解析器的帮助信息。例如,考虑一个包含如下代码的名为myprogram.py的文件:

import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--foo', help='foo help')
args = parser.parse_args()

如果在命令行中提供-h或者--help,ArgumentParser的帮助信息将打印出来:

$ python myprogram.py --help
usage: myprogram.py [-h] [--foo FOO]

optional arguments:
 -h, --help  show this help message and exit
 --foo FOO   foo help

偶尔,禁止这个帮助选项也可能是有用的。这可以通过传递FalseArgumentParseradd_help=参数实现:

>>> parser = argparse.ArgumentParser(prog='PROG', add_help=False)
>>> parser.add_argument('--foo', help='foo help')
>>> parser.print_help()
usage: PROG [--foo FOO]

optional arguments:
 --foo FOO  foo help

该帮助选项通常是-h/--help例外情况是指定了prefix_chars=而且不包括-,在这种情况下-h--help不是合法的选项。在这种情况下,prefix_chars中的第一个字符将用于该帮助选项的前缀:

>>> parser = argparse.ArgumentParser(prog='PROG', prefix_chars='+/')
>>> parser.print_help()
usage: PROG [+h]

optional arguments:
  +h, ++help  show this help message and exit

15.4.3. add_argument() 方法

ArgumentParser.add_argument(name or flags...[, action][, nargs][, const][, default][, type][, choices][, required][, help][, metavar][, dest])

定义应该如何解析一个命令行参数。下面每个参数有它们自己详细的描述,简单地讲它们是:

  • name or flags - Either a name or a list of option strings, e.g. foo or -f, --foo.
  • action - The basic type of action to be taken when this argument is encountered at the command line.
  • nargs - The number of command-line arguments that should be consumed.
  • const - A constant value required by some action and nargs selections.
  • default - The value produced if the argument is absent from the command line.
  • type - The type to which the command-line argument should be converted.
  • choices - A container of the allowable values for the argument.
  • required - Whether or not the command-line option may be omitted (optionals only).
  • help - A brief description of what the argument does.
  • metavar - A name for the argument in usage messages.
  • dest - The name of the attribute to be added to the object returned by parse_args().

下面的小节描述这些参数如何使用。

15.4.3.1. name 或 flags 参数

add_argument() 方法必须知道期望的是可选参数,比如-f 或者--foo,还是位置参数,比如一个文件列表。传递给add_argument() 的第一个参数因此必须是一个标记序列或者一个简单的参数名字。例如,一个可选的参数可以像这样创建:

>>> parser.add_argument('-f', '--foo')

而一个位置参数可以像这样创建:

>>> parser.add_argument('bar')

当调用parse_args()时,可选的参数将以- 前缀标识,剩余的参数将被假定为位置参数:

>>> parser = argparse.ArgumentParser(prog='PROG')
>>> parser.add_argument('-f', '--foo')
>>> parser.add_argument('bar')
>>> parser.parse_args(['BAR'])
Namespace(bar='BAR', foo=None)
>>> parser.parse_args(['BAR', '--foo', 'FOO'])
Namespace(bar='BAR', foo='FOO')
>>> parser.parse_args(['--foo', 'FOO'])
usage: PROG [-h] [-f FOO] bar
PROG: error: too few arguments

15.4.3.2. action 参数

ArgumentParser 对象将命令行参数和动作关联起来。这些动作可以完成与命令行参数关联的任何事情,尽管大部分动作只是简单地给parse_args()返回的对象添加一个属性。action 关键字参数指出应该如何处理命令行参数。支持的动作有:

  • 'store' - 只是保存参数的值。这是默认的动作。例如:

    >>> parser = argparse.ArgumentParser()
    >>> parser.add_argument('--foo')
    >>> parser.parse_args('--foo 1'.split())
    Namespace(foo='1')
    
  • 'store_const' - 保存由const关键字参数指出的值。(注意const关键字参数默认是几乎没有帮助的None。)'store_const'动作最常用于指定某种标记的可选参数。例如:

    >>> parser = argparse.ArgumentParser()
    >>> parser.add_argument('--foo', action='store_const', const=42)
    >>> parser.parse_args('--foo'.split())
    Namespace(foo=42)
    
  • 'store_true''store_false' - 它们是'store_const' 的特殊情形,分别用于保存值TrueFalse另外,它们分别会创建默认值FalseTrue例如:

    >>> parser = argparse.ArgumentParser()
    >>> parser.add_argument('--foo', action='store_true')
    >>> parser.add_argument('--bar', action='store_false')
    >>> parser.add_argument('--baz', action='store_false')
    >>> parser.parse_args('--foo --bar'.split())
    Namespace(bar=False, baz=True, foo=True)
    
  • 'append' - 保存一个列表,并将每个参数值附加在列表的后面。这对于允许指定多次的选项很有帮助。示例用法:

    >>> parser = argparse.ArgumentParser()
    >>> parser.add_argument('--foo', action='append')
    >>> parser.parse_args('--foo 1 --foo 2'.split())
    Namespace(foo=['1', '2'])
    
  • 'append_const' - 保存一个列表,并将const关键字参数指出的值附加在列表的后面。(注意const关键字参数默认是None。)'append_const' 动作在多个参数需要保存常量到相同的列表时特别有用。例如:

    >>> parser = argparse.ArgumentParser()
    >>> parser.add_argument('--str', dest='types', action='append_const', const=str)
    >>> parser.add_argument('--int', dest='types', action='append_const', const=int)
    >>> parser.parse_args('--str --int'.split())
    Namespace(types=[<type 'str'>, <type 'int'>])
    
  • 'count' - 计算关键字参数出现的次数。例如,这可用于增加详细的级别:

    >>> parser = argparse.ArgumentParser()
    >>> parser.add_argument('--verbose', '-v', action='count')
    >>> parser.parse_args('-vvv'.split())
    Namespace(verbose=3)
    
  • 'help' - 打印当前解析器中所有选项的完整的帮助信息然后退出。默认情况下,help动作会自动添加到解析器中。参见ArgumentParser以得到如何生成输出信息。

  • 'version' - 它期待version=参数出现在add_argument()调用中,在调用时打印出版本信息并退出:

    >>> import argparse
    >>> parser = argparse.ArgumentParser(prog='PROG')
    >>> parser.add_argument('--version', action='version', version='%(prog)s 2.0')
    >>> parser.parse_args(['--version'])
    PROG 2.0
    

你还可以通过传递一个实现了Action API的对象指定任意一个动作。实现该功能的最简单方法是扩展argparse.Action,并提供一个合适的__call__方法。__call__方法应该接受四个参数:

  • parser - The ArgumentParser object which contains this action.
  • namespace - The Namespace object that will be returned by parse_args(). Most actions add an attribute to this object.
  • values - The associated command-line arguments, with any type conversions applied. (Type conversions are specified with the type keyword argument to add_argument().)
  • option_string - The option string that was used to invoke this action. The option_string argument is optional, and will be absent if the action is associated with a positional argument.

自定义动作的例子:

>>> class FooAction(argparse.Action):
...     def __call__(self, parser, namespace, values, option_string=None):
...         print '%r %r %r' % (namespace, values, option_string)
...         setattr(namespace, self.dest, values)
...
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo', action=FooAction)
>>> parser.add_argument('bar', action=FooAction)
>>> args = parser.parse_args('1 --foo 2'.split())
Namespace(bar=None, foo=None) '1' None
Namespace(bar='1', foo=None) '2' '--foo'
>>> args
Namespace(bar='1', foo='2')

15.4.3.3. nargs 参数

ArgumentParser对象通常将一个动作与一个命令行参数关联。nargs关键字参数将一个动作与不同数目的命令行参数关联在一起。它支持的值有:

  • N(一个整数)。命令行中的N个参数将被一起收集在一个列表中。例如:

    >>> parser = argparse.ArgumentParser()
    >>> parser.add_argument('--foo', nargs=2)
    >>> parser.add_argument('bar', nargs=1)
    >>> parser.parse_args('c --foo a b'.split())
    Namespace(bar=['c'], foo=['a', 'b'])
    

    注意nargs=1生成一个只有一个元素的列表。这和默认的行为是不一样的,默认情况下生成的是元素自己。

  • '?'如果有的话就从命令行读取一个参数并生成一个元素。如果没有对应的命令行参数,则产生一个来自default的值。注意,对于可选参数,有另外一种情况 - 有选项字符串但是后面没有跟随命令行参数。在这种情况下,将生成一个来自const的值。用一些例子加以解释:

    >>> parser = argparse.ArgumentParser()
    >>> parser.add_argument('--foo', nargs='?', const='c', default='d')
    >>> parser.add_argument('bar', nargs='?', default='d')
    >>> parser.parse_args('XX --foo YY'.split())
    Namespace(bar='XX', foo='YY')
    >>> parser.parse_args('XX --foo'.split())
    Namespace(bar='XX', foo='c')
    >>> parser.parse_args(''.split())
    Namespace(bar='d', foo='d')
    

    nargs='?'的一种更常见的用法是允许可选的输入和输出文件:

    >>> parser = argparse.ArgumentParser()
    >>> parser.add_argument('infile', nargs='?', type=argparse.FileType('r'),
    ...                     default=sys.stdin)
    >>> parser.add_argument('outfile', nargs='?', type=argparse.FileType('w'),
    ...                     default=sys.stdout)
    >>> parser.parse_args(['input.txt', 'output.txt'])
    Namespace(infile=<open file 'input.txt', mode 'r' at 0x...>,
              outfile=<open file 'output.txt', mode 'w' at 0x...>)
    >>> parser.parse_args([])
    Namespace(infile=<open file '<stdin>', mode 'r' at 0x...>,
              outfile=<open file '<stdout>', mode 'w' at 0x...>)
    
  • '*'出现的所有命令行参数都被收集到一个列表中。注意,一般情况下具有多个带有nargs='*'的位置参数是不合理的,但是多个带有nargs='*'的可选参数是可能的。例如:

    >>> parser = argparse.ArgumentParser()
    >>> parser.add_argument('--foo', nargs='*')
    >>> parser.add_argument('--bar', nargs='*')
    >>> parser.add_argument('baz', nargs='*')
    >>> parser.parse_args('a b --foo x y --bar 1 2'.split())
    Namespace(bar=['1', '2'], baz=['a', 'b'], foo=['x', 'y'])
    
  • '+''*'一样,出现的所有命令行参数都被收集到一个列表中。除此之外,如果没有至少出现一个命令行参数将会产生一个错误信息。例如:

    >>> parser = argparse.ArgumentParser(prog='PROG')
    >>> parser.add_argument('foo', nargs='+')
    >>> parser.parse_args('a b'.split())
    Namespace(foo=['a', 'b'])
    >>> parser.parse_args(''.split())
    usage: PROG [-h] foo [foo ...]
    PROG: error: too few arguments
    
  • argparse.REMAINDER.所有剩余的命令行参数都被收集到一个列表中。这通常用于命令行工具分发命令到其它命令行工具:

    >>> parser = argparse.ArgumentParser(prog='PROG')
    >>> parser.add_argument('--foo')
    >>> parser.add_argument('command')
    >>> parser.add_argument('args', nargs=argparse.REMAINDER)
    >>> print parser.parse_args('--foo B cmd --arg1 XX ZZ'.split())
    Namespace(args=['--arg1', 'XX', 'ZZ'], command='cmd', foo='B')
    

如果没有提供nargs关键字参数,读取的参数个数取决于action通常这意味着将读取一个命令行参数并产生一个元素(不是一个列表)。

15.4.3.4. const 参数

add_argument()const 参数用于保存常量值,它们不是从命令行读入但是是ArgumentParser 的动作所要求的。它的两个最常见的用法是:

  • 当以action='store_const'或者action='append_const'调用add_argument()时。这些动作向parse_args()返回对象的一个属性添加const值。参见action的描述。
  • 当以选项字符串(例如-f或者--foonargs='?')调用add_argument()时。它创建一个后面可以跟随零个或者一个命令行字符串的可选参数。当解析命令行参数时,如果选项字符串后面没有跟随命令行参数,则假定其为const的值。参见nargs的描述。

const 关键字的默认值是None

15.4.3.5. default 参数

所有可选的参数以及某些位置参数可以在命令行中省略。add_argument()default关键字参数,其默认值为None,指出如果命令行参数没有出现时它们应该是什么值。对于可选参数,default的值用于选项字符串没有出现在命令行中的时候:

>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo', default=42)
>>> parser.parse_args('--foo 2'.split())
Namespace(foo='2')
>>> parser.parse_args(''.split())
Namespace(foo=42)

如果default的值是一个字符串,解析器将像命令行参数一样解析这个值。特别地,在设置Namespace返回值的属性之前,解析器会调用type的转换参数。否则,解析器就使用其原始值:

>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--length', default='10', type=int)
>>> parser.add_argument('--width', default=10.5, type=int)
>>> parser.parse_args()
Namespace(length=10, width=10.5)

对于nargs等于?或者*的位置参数,default在没有其命令行参数时使用:

>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('foo', nargs='?', default=42)
>>> parser.parse_args('a'.split())
Namespace(foo='a')
>>> parser.parse_args(''.split())
Namespace(foo=42)

default=argparse.SUPPRESS将导致如果没有命令行参数时不会添加属性:

>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo', default=argparse.SUPPRESS)
>>> parser.parse_args([])
Namespace()
>>> parser.parse_args(['--foo', '1'])
Namespace(foo='1')

15.4.3.6. type 参数

默认情况下,ArgumentParser对象以简单字符串方式读入命令行参数。然而,很多时候命令行字符串应该被解释成另外一种类型,例如浮点数或者整数add_argument()type关键字参数允许任意必要的类型检查并作类型转换。常见的内建类型和函数可以直接用作type参数的值:

>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('foo', type=int)
>>> parser.add_argument('bar', type=file)
>>> parser.parse_args('2 temp.txt'.split())
Namespace(bar=<open file 'temp.txt', mode 'r' at 0x...>, foo=2)

参见default关键字参数一节关于何时type参数应用与默认参数的信息。

为了简化各种文件类型的使用,argparse提供了工厂类型FileType,它以file对象的mode=bufsize=为参数。例如,FileType('w')可以用于创建一个可写的文件:

>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('bar', type=argparse.FileType('w'))
>>> parser.parse_args(['out.txt'])
Namespace(bar=<open file 'out.txt', mode 'w' at 0x...>)

type=可以接受任何可调用类型,只要该类型以一个字符串为参数并且返回转换后的类型:

>>> def perfect_square(string):
...     value = int(string)
...     sqrt = math.sqrt(value)
...     if sqrt != int(sqrt):
...         msg = "%r is not a perfect square" % string
...         raise argparse.ArgumentTypeError(msg)
...     return value
...
>>> parser = argparse.ArgumentParser(prog='PROG')
>>> parser.add_argument('foo', type=perfect_square)
>>> parser.parse_args('9'.split())
Namespace(foo=9)
>>> parser.parse_args('7'.split())
usage: PROG [-h] foo
PROG: error: argument foo: '7' is not a perfect square

choices关键字参数对于简单的某个范围内的类型检查可能更方便:

>>> parser = argparse.ArgumentParser(prog='PROG')
>>> parser.add_argument('foo', type=int, choices=xrange(5, 10))
>>> parser.parse_args('7'.split())
Namespace(foo=7)
>>> parser.parse_args('11'.split())
usage: PROG [-h] {5,6,7,8,9}
PROG: error: argument foo: invalid choice: 11 (choose from 5, 6, 7, 8, 9)

更多细节请参阅choices一节。

15.4.3.7. choices 参数

某些命令行参数应该从一个受限的集合中选择。这种情况的处理可以通过传递一个容器对象作为choices关键字参数给add_argument()当解析命令行时,将检查参数的值,如果参数不是一个可接受的值则显示一个错误信息:

>>> parser = argparse.ArgumentParser(prog='game.py')
>>> parser.add_argument('move', choices=['rock', 'paper', 'scissors'])
>>> parser.parse_args(['rock'])
Namespace(move='rock')
>>> parser.parse_args(['fire'])
usage: game.py [-h] {rock,paper,scissors}
game.py: error: argument move: invalid choice: 'fire' (choose from 'rock',
'paper', 'scissors')

注意choices 容器包含的对象在type转换之后检查,所以choices容器中对象的类型应该与type指出的类型相匹配:

>>> parser = argparse.ArgumentParser(prog='doors.py')
>>> parser.add_argument('door', type=int, choices=range(1, 4))
>>> print(parser.parse_args(['3']))
Namespace(door=3)
>>> parser.parse_args(['4'])
usage: doors.py [-h] {1,2,3}
doors.py: error: argument door: invalid choice: 4 (choose from 1, 2, 3)

支持in操作符的任何对象都可以传递给choices作为它的值,所以dict对象、set对象以及自定义的容器等等都支持。

15.4.3.8. required 参数

一般情况下,argparse模块假定-f--bar标记表示可选参数,它们在命令行中可以省略。如果要使得选项是必需的,可以指定True作为required=关键字参数的值给add_argument()

>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo', required=True)
>>> parser.parse_args(['--foo', 'BAR'])
Namespace(foo='BAR')
>>> parser.parse_args([])
usage: argparse.py [-h] [--foo FOO]
argparse.py: error: option --foo is required

正如例子所演示的,如果一个命令被标记为required,那么如果命令行中没有出现该参数parse_args() 将报告一个错误。

注意

Required 选项一般情况下认为是不好的形式因为用户期望选项可选 的,因此应该尽可能避免这种形式。

15.4.3.9. help 参数

help的值是一个包含参数简短描述的字符串。当用户要求帮助时(通常通过使用-h或者--help at the command line),这些help的描述将随每个参数一起显示出来:

>>> parser = argparse.ArgumentParser(prog='frobble')
>>> parser.add_argument('--foo', action='store_true',
...         help='foo the bars before frobbling')
>>> parser.add_argument('bar', nargs='+',
...         help='one of the bars to be frobbled')
>>> parser.parse_args('-h'.split())
usage: frobble [-h] [--foo] bar [bar ...]

positional arguments:
 bar     one of the bars to be frobbled

optional arguments:
 -h, --help  show this help message and exit
 --foo   foo the bars before frobbling

help字符串可以包含各种格式指示符以避免如程序名字和参数default的重复。可用的指示符包括程序的名称%(prog)s以及大部分add_argument()的关键字参数,例如%(default)s%(type)s等:

>>> parser = argparse.ArgumentParser(prog='frobble')
>>> parser.add_argument('bar', nargs='?', type=int, default=42,
...         help='the bar to %(prog)s (default: %(default)s)')
>>> parser.print_help()
usage: frobble [-h] [bar]

positional arguments:
 bar     the bar to frobble (default: 42)

optional arguments:
 -h, --help  show this help message and exit

通过设置help值为argparse.SUPPRESSargparse支持隐藏特定选项的帮助:

>>> parser = argparse.ArgumentParser(prog='frobble')
>>> parser.add_argument('--foo', help=argparse.SUPPRESS)
>>> parser.print_help()
usage: frobble [-h]

optional arguments:
  -h, --help  show this help message and exit

15.4.3.10. metavar 参数

ArgumentParser生成帮助信息时,它需要以某种方式引用每一个参数。 默认情况下,ArgumentParser对象使用dest的值作为每个对象的“名字”。默认情况下,对于位置参数直接使用dest的值,对于可选参数则将dest的值变为大写。所以,位置参数dest='bar'将引用成barA single optional argument --foo that should be followed by a single command-line argument will be referred to as FOO. An example:

>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo')
>>> parser.add_argument('bar')
>>> parser.parse_args('X --foo Y'.split())
Namespace(bar='X', foo='Y')
>>> parser.print_help()
usage:  [-h] [--foo FOO] bar

positional arguments:
 bar

optional arguments:
 -h, --help  show this help message and exit
 --foo FOO

An alternative name can be specified with metavar:

>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo', metavar='YYY')
>>> parser.add_argument('bar', metavar='XXX')
>>> parser.parse_args('X --foo Y'.split())
Namespace(bar='X', foo='Y')
>>> parser.print_help()
usage:  [-h] [--foo YYY] XXX

positional arguments:
 XXX

optional arguments:
 -h, --help  show this help message and exit
 --foo YYY

Note that metavar only changes the displayed name - the name of the attribute on the parse_args() object is still determined by the dest value.

Different values of nargs may cause the metavar to be used multiple times. Providing a tuple to metavar specifies a different display for each of the arguments:

>>> parser = argparse.ArgumentParser(prog='PROG')
>>> parser.add_argument('-x', nargs=2)
>>> parser.add_argument('--foo', nargs=2, metavar=('bar', 'baz'))
>>> parser.print_help()
usage: PROG [-h] [-x X X] [--foo bar baz]

optional arguments:
 -h, --help     show this help message and exit
 -x X X
 --foo bar baz

15.4.3.11. dest 参数

Most ArgumentParser actions add some value as an attribute of the object returned by parse_args(). The name of this attribute is determined by the dest keyword argument of add_argument(). For positional argument actions, dest is normally supplied as the first argument to add_argument():

>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('bar')
>>> parser.parse_args('XXX'.split())
Namespace(bar='XXX')

For optional argument actions, the value of dest is normally inferred from the option strings. ArgumentParser生成的dest的值是将第一长的选项字符串前面的--字符串去掉。If no long option strings were supplied, dest will be derived from the first short option string by stripping the initial - character. Any internal - characters will be converted to _ characters to make sure the string is a valid attribute name. The examples below illustrate this behavior:

>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('-f', '--foo-bar', '--foo')
>>> parser.add_argument('-x', '-y')
>>> parser.parse_args('-f 1 -x 2'.split())
Namespace(foo_bar='1', x='2')
>>> parser.parse_args('--foo 1 -y 2'.split())
Namespace(foo_bar='1', x='2')

dest allows a custom attribute name to be provided:

>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo', dest='bar')
>>> parser.parse_args('--foo XXX'.split())
Namespace(bar='XXX')

15.4.4. parse_args() 方法

ArgumentParser.parse_args(args=None, namespace=None)

Convert argument strings to objects and assign them as attributes of the namespace. Return the populated namespace.

Previous calls to add_argument() determine exactly what objects are created and how they are assigned. See the documentation for add_argument() for details.

By default, the argument strings are taken from sys.argv, and a new empty Namespace object is created for the attributes.

15.4.4.1. Option value syntax

The parse_args() method supports several ways of specifying the value of an option (if it takes one). In the simplest case, the option and its value are passed as two separate arguments:

>>> parser = argparse.ArgumentParser(prog='PROG')
>>> parser.add_argument('-x')
>>> parser.add_argument('--foo')
>>> parser.parse_args('-x X'.split())
Namespace(foo=None, x='X')
>>> parser.parse_args('--foo FOO'.split())
Namespace(foo='FOO', x=None)

For long options (options with names longer than a single character), the option and value can also be passed as a single command-line argument, using = to separate them:

>>> parser.parse_args('--foo=FOO'.split())
Namespace(foo='FOO', x=None)

For short options (options only one character long), the option and its value can be concatenated:

>>> parser.parse_args('-xX'.split())
Namespace(foo=None, x='X')

几个短选项可以连在一起仅使用一个-前缀,只要只有最后一个选项要求有值或者都不要有值:

>>> parser = argparse.ArgumentParser(prog='PROG')
>>> parser.add_argument('-x', action='store_true')
>>> parser.add_argument('-y', action='store_true')
>>> parser.add_argument('-z')
>>> parser.parse_args('-xyzZ'.split())
Namespace(x=True, y=True, z='Z')

15.4.4.2. Invalid arguments

While parsing the command line, parse_args() checks for a variety of errors, including ambiguous options, invalid types, invalid options, wrong number of positional arguments, etc. When it encounters such an error, it exits and prints the error along with a usage message:

>>> parser = argparse.ArgumentParser(prog='PROG')
>>> parser.add_argument('--foo', type=int)
>>> parser.add_argument('bar', nargs='?')

>>> # invalid type
>>> parser.parse_args(['--foo', 'spam'])
usage: PROG [-h] [--foo FOO] [bar]
PROG: error: argument --foo: invalid int value: 'spam'

>>> # invalid option
>>> parser.parse_args(['--bar'])
usage: PROG [-h] [--foo FOO] [bar]
PROG: error: no such option: --bar

>>> # wrong number of arguments
>>> parser.parse_args(['spam', 'badger'])
usage: PROG [-h] [--foo FOO] [bar]
PROG: error: extra arguments found: badger

15.4.4.3. Arguments containing -

The parse_args() method attempts to give errors whenever the user has clearly made a mistake, but some situations are inherently ambiguous. For example, the command-line argument -1 could either be an attempt to specify an option or an attempt to provide a positional argument. The parse_args() method is cautious here: positional arguments may only begin with - if they look like negative numbers and there are no options in the parser that look like negative numbers:

>>> parser = argparse.ArgumentParser(prog='PROG')
>>> parser.add_argument('-x')
>>> parser.add_argument('foo', nargs='?')

>>> # no negative number options, so -1 is a positional argument
>>> parser.parse_args(['-x', '-1'])
Namespace(foo=None, x='-1')

>>> # no negative number options, so -1 and -5 are positional arguments
>>> parser.parse_args(['-x', '-1', '-5'])
Namespace(foo='-5', x='-1')

>>> parser = argparse.ArgumentParser(prog='PROG')
>>> parser.add_argument('-1', dest='one')
>>> parser.add_argument('foo', nargs='?')

>>> # negative number options present, so -1 is an option
>>> parser.parse_args(['-1', 'X'])
Namespace(foo=None, one='X')

>>> # negative number options present, so -2 is an option
>>> parser.parse_args(['-2'])
usage: PROG [-h] [-1 ONE] [foo]
PROG: error: no such option: -2

>>> # negative number options present, so both -1s are options
>>> parser.parse_args(['-1', '-1'])
usage: PROG [-h] [-1 ONE] [foo]
PROG: error: argument -1: expected one argument

If you have positional arguments that must begin with - and don’t look like negative numbers, you can insert the pseudo-argument '--' which tells parse_args() that everything after that is a positional argument:

>>> parser.parse_args(['--', '-f'])
Namespace(foo='-f', one=None)

15.4.4.4. Argument abbreviations (prefix matching)

The parse_args() method allows long options to be abbreviated to a prefix, if the abbreviation is unambiguous (the prefix matches a unique option):

>>> parser = argparse.ArgumentParser(prog='PROG')
>>> parser.add_argument('-bacon')
>>> parser.add_argument('-badger')
>>> parser.parse_args('-bac MMM'.split())
Namespace(bacon='MMM', badger=None)
>>> parser.parse_args('-bad WOOD'.split())
Namespace(bacon=None, badger='WOOD')
>>> parser.parse_args('-ba BA'.split())
usage: PROG [-h] [-bacon BACON] [-badger BADGER]
PROG: error: ambiguous option: -ba could match -badger, -bacon

An error is produced for arguments that could produce more than one options.

15.4.4.5. Beyond sys.argv

Sometimes it may be useful to have an ArgumentParser parse arguments other than those of sys.argv. This can be accomplished by passing a list of strings to parse_args(). This is useful for testing at the interactive prompt:

>>> parser = argparse.ArgumentParser()
>>> parser.add_argument(
...     'integers', metavar='int', type=int, choices=xrange(10),
...  nargs='+', help='an integer in the range 0..9')
>>> parser.add_argument(
...     '--sum', dest='accumulate', action='store_const', const=sum,
...   default=max, help='sum the integers (default: find the max)')
>>> parser.parse_args(['1', '2', '3', '4'])
Namespace(accumulate=<built-in function max>, integers=[1, 2, 3, 4])
>>> parser.parse_args('1 2 3 4 --sum'.split())
Namespace(accumulate=<built-in function sum>, integers=[1, 2, 3, 4])

15.4.4.6. Namespace 对象

class argparse.Namespace

Simple class used by default by parse_args() to create an object holding attributes and return it.

This class is deliberately simple, just an object subclass with a readable string representation. If you prefer to have dict-like view of the attributes, you can use the standard Python idiom, vars():

>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo')
>>> args = parser.parse_args(['--foo', 'BAR'])
>>> vars(args)
{'foo': 'BAR'}

It may also be useful to have an ArgumentParser assign attributes to an already existing object, rather than a new Namespace object. This can be achieved by specifying the namespace= keyword argument:

>>> class C(object):
...     pass
...
>>> c = C()
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo')
>>> parser.parse_args(args=['--foo', 'BAR'], namespace=c)
>>> c.foo
'BAR'

15.4.5. 其它实用工具

15.4.5.1. 子命令

ArgumentParser.add_subparsers([title][, description][, prog][, parser_class][, action][, option_string][, dest][, help][, metavar])

Many programs split up their functionality into a number of sub-commands, for example, the svn program can invoke sub-commands like svn checkout, svn update, and svn commit. Splitting up functionality this way can be a particularly good idea when a program performs several different functions which require different kinds of command-line arguments. ArgumentParser supports the creation of such sub-commands with the add_subparsers() method. The add_subparsers() method is normally called with no arguments and returns a special action object. This object has a single method, add_parser(), which takes a command name and any ArgumentParser constructor arguments, and returns an ArgumentParser object that can be modified as usual.

Description of parameters:

  • title - 在输出的帮助中子解析器组的标题;默认情况下,如果提供description参数则为“subcommands”,否则使用位置参数的标题
  • description - 在输出的帮助中子解析器组的描述,默认为None
  • prog - 与子命令的帮助一起显示的使用帮助信息,默认为程序的名字和子解析器参数之前的所有位置参数
  • parser_class - 用于创建子解析器实例的类,默认为当前的解析器(例如ArgumentParser)
  • dest - 子命令的名字应该存储的属性名称;默认为None且不存储任何值
  • help - 在输出的帮助中子解析器中的帮助信息,默认为None
  • metavar - 在帮助中表示可用的子命令的字符串;默认为None并以{cmd1, cmd2, ..}的形式表示子命令

Some example usage:

>>> # create the top-level parser
>>> parser = argparse.ArgumentParser(prog='PROG')
>>> parser.add_argument('--foo', action='store_true', help='foo help')
>>> subparsers = parser.add_subparsers(help='sub-command help')
>>>
>>> # create the parser for the "a" command
>>> parser_a = subparsers.add_parser('a', help='a help')
>>> parser_a.add_argument('bar', type=int, help='bar help')
>>>
>>> # create the parser for the "b" command
>>> parser_b = subparsers.add_parser('b', help='b help')
>>> parser_b.add_argument('--baz', choices='XYZ', help='baz help')
>>>
>>> # parse some argument lists
>>> parser.parse_args(['a', '12'])
Namespace(bar=12, foo=False)
>>> parser.parse_args(['--foo', 'b', '--baz', 'Z'])
Namespace(baz='Z', foo=True)

Note that the object returned by parse_args() will only contain attributes for the main parser and the subparser that was selected by the command line (and not any other subparsers). So in the example above, when the a command is specified, only the foo and bar attributes are present, and when the b command is specified, only the foo and baz attributes are present.

Similarly, when a help message is requested from a subparser, only the help for that particular parser will be printed. The help message will not include parent parser or sibling parser messages. (A help message for each subparser command, however, can be given by supplying the help= argument to add_parser() as above.)

>>> parser.parse_args(['--help'])
usage: PROG [-h] [--foo] {a,b} ...

positional arguments:
  {a,b}   sub-command help
    a     a help
    b     b help

optional arguments:
  -h, --help  show this help message and exit
  --foo   foo help

>>> parser.parse_args(['a', '--help'])
usage: PROG a [-h] bar

positional arguments:
  bar     bar help

optional arguments:
  -h, --help  show this help message and exit

>>> parser.parse_args(['b', '--help'])
usage: PROG b [-h] [--baz {X,Y,Z}]

optional arguments:
  -h, --help     show this help message and exit
  --baz {X,Y,Z}  baz help

The add_subparsers() method also supports title and description keyword arguments. When either is present, the subparser’s commands will appear in their own group in the help output. For example:

>>> parser = argparse.ArgumentParser()
>>> subparsers = parser.add_subparsers(title='subcommands',
...                                    description='valid subcommands',
...                                    help='additional help')
>>> subparsers.add_parser('foo')
>>> subparsers.add_parser('bar')
>>> parser.parse_args(['-h'])
usage:  [-h] {foo,bar} ...

optional arguments:
  -h, --help  show this help message and exit

subcommands:
  valid subcommands

  {foo,bar}   additional help

处理子命令的一个特别有效的方法是将add_subparsers()方法和set_defaults() 调用绑在一起使用,这样每个子命令就可以知道它应该执行哪个Python 函数。For example:

>>> # sub-command functions
>>> def foo(args):
...     print args.x * args.y
...
>>> def bar(args):
...     print '((%s))' % args.z
...
>>> # create the top-level parser
>>> parser = argparse.ArgumentParser()
>>> subparsers = parser.add_subparsers()
>>>
>>> # create the parser for the "foo" command
>>> parser_foo = subparsers.add_parser('foo')
>>> parser_foo.add_argument('-x', type=int, default=1)
>>> parser_foo.add_argument('y', type=float)
>>> parser_foo.set_defaults(func=foo)
>>>
>>> # create the parser for the "bar" command
>>> parser_bar = subparsers.add_parser('bar')
>>> parser_bar.add_argument('z')
>>> parser_bar.set_defaults(func=bar)
>>>
>>> # parse the args and call whatever function was selected
>>> args = parser.parse_args('foo 1 -x 2'.split())
>>> args.func(args)
2.0
>>>
>>> # parse the args and call whatever function was selected
>>> args = parser.parse_args('bar XYZYX'.split())
>>> args.func(args)
((XYZYX))

This way, you can let parse_args() do the job of calling the appropriate function after argument parsing is complete. Associating functions with actions like this is typically the easiest way to handle the different actions for each of your subparsers. However, if it is necessary to check the name of the subparser that was invoked, the dest keyword argument to the add_subparsers() call will work:

>>> parser = argparse.ArgumentParser()
>>> subparsers = parser.add_subparsers(dest='subparser_name')
>>> subparser1 = subparsers.add_parser('1')
>>> subparser1.add_argument('-x')
>>> subparser2 = subparsers.add_parser('2')
>>> subparser2.add_argument('y')
>>> parser.parse_args(['2', 'frobble'])
Namespace(subparser_name='2', y='frobble')

15.4.5.2. FileType objects

class argparse.FileType(mode='r', bufsize=None)

The FileType factory creates objects that can be passed to the type argument of ArgumentParser.add_argument(). Arguments that have FileType objects as their type will open command-line arguments as files with the requested modes and buffer sizes:

>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--output', type=argparse.FileType('wb', 0))
>>> parser.parse_args(['--output', 'out'])
Namespace(output=<open file 'out', mode 'wb' at 0x...>)

FileType objects understand the pseudo-argument '-' and automatically convert this into sys.stdin for readable FileType objects and sys.stdout for writable FileType objects:

>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('infile', type=argparse.FileType('r'))
>>> parser.parse_args(['-'])
Namespace(infile=<open file '<stdin>', mode 'r' at 0x...>)

15.4.5.3. Argument groups

ArgumentParser.add_argument_group(title=None, description=None)

By default, ArgumentParser groups command-line arguments into “positional arguments” and “optional arguments” when displaying help messages. When there is a better conceptual grouping of arguments than this default one, appropriate groups can be created using the add_argument_group() method:

>>> parser = argparse.ArgumentParser(prog='PROG', add_help=False)
>>> group = parser.add_argument_group('group')
>>> group.add_argument('--foo', help='foo help')
>>> group.add_argument('bar', help='bar help')
>>> parser.print_help()
usage: PROG [--foo FOO] bar

group:
  bar    bar help
  --foo FOO  foo help

The add_argument_group() method returns an argument group object which has an add_argument() method just like a regular ArgumentParser. When an argument is added to the group, the parser treats it just like a normal argument, but displays the argument in a separate group for help messages. The add_argument_group() method accepts title and description arguments which can be used to customize this display:

>>> parser = argparse.ArgumentParser(prog='PROG', add_help=False)
>>> group1 = parser.add_argument_group('group1', 'group1 description')
>>> group1.add_argument('foo', help='foo help')
>>> group2 = parser.add_argument_group('group2', 'group2 description')
>>> group2.add_argument('--bar', help='bar help')
>>> parser.print_help()
usage: PROG [--bar BAR] foo

group1:
  group1 description

  foo    foo help

group2:
  group2 description

  --bar BAR  bar help

Note that any arguments not in your user-defined groups will end up back in the usual “positional arguments” and “optional arguments” sections.

15.4.5.4. 互斥分组

ArgumentParser.add_mutually_exclusive_group(required=False)

Create a mutually exclusive group. argparse will make sure that only one of the arguments in the mutually exclusive group was present on the command line:

>>> parser = argparse.ArgumentParser(prog='PROG')
>>> group = parser.add_mutually_exclusive_group()
>>> group.add_argument('--foo', action='store_true')
>>> group.add_argument('--bar', action='store_false')
>>> parser.parse_args(['--foo'])
Namespace(bar=True, foo=True)
>>> parser.parse_args(['--bar'])
Namespace(bar=False, foo=False)
>>> parser.parse_args(['--foo', '--bar'])
usage: PROG [-h] [--foo | --bar]
PROG: error: argument --bar: not allowed with argument --foo

The add_mutually_exclusive_group() method also accepts a required argument, to indicate that at least one of the mutually exclusive arguments is required:

>>> parser = argparse.ArgumentParser(prog='PROG')
>>> group = parser.add_mutually_exclusive_group(required=True)
>>> group.add_argument('--foo', action='store_true')
>>> group.add_argument('--bar', action='store_false')
>>> parser.parse_args([])
usage: PROG [-h] (--foo | --bar)
PROG: error: one of the arguments --foo --bar is required

Note that currently mutually exclusive argument groups do not support the title and description arguments of add_argument_group().

15.4.5.5. 解析器的默认值

ArgumentParser.set_defaults(**kwargs)

Most of the time, the attributes of the object returned by parse_args() will be fully determined by inspecting the command-line arguments and the argument actions. set_defaults() allows some additional attributes that are determined without any inspection of the command line to be added:

>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('foo', type=int)
>>> parser.set_defaults(bar=42, baz='badger')
>>> parser.parse_args(['736'])
Namespace(bar=42, baz='badger', foo=736)

Note that parser-level defaults always override argument-level defaults:

>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo', default='bar')
>>> parser.set_defaults(foo='spam')
>>> parser.parse_args([])
Namespace(foo='spam')

Parser-level defaults can be particularly useful when working with multiple parsers. See the add_subparsers() method for an example of this type.

ArgumentParser.get_default(dest)

Get the default value for a namespace attribute, as set by either add_argument() or by set_defaults():

>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo', default='badger')
>>> parser.get_default('foo')
'badger'

15.4.5.6. 打印帮助

In most typical applications, parse_args() will take care of formatting and printing any usage or error messages. However, several formatting methods are available:

ArgumentParser.print_usage(file=None)

Print a brief description of how the ArgumentParser should be invoked on the command line. If file is None, sys.stdout is assumed.

ArgumentParser.print_help(file=None)

Print a help message, including the program usage and information about the arguments registered with the ArgumentParser. If file is None, sys.stdout is assumed.

There are also variants of these methods that simply return a string instead of printing it:

ArgumentParser.format_usage()

Return a string containing a brief description of how the ArgumentParser should be invoked on the command line.

ArgumentParser.format_help()

Return a string containing a help message, including the program usage and information about the arguments registered with the ArgumentParser.

15.4.5.7. 部分解析

ArgumentParser.parse_known_args(args=None, namespace=None)

Sometimes a script may only parse a few of the command-line arguments, passing the remaining arguments on to another script or program. In these cases, the parse_known_args() method can be useful. It works much like parse_args() except that it does not produce an error when extra arguments are present. 相反,它返回一个两个元素的元组,包含构造的namespace和剩余的参数字符串的列表。

>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo', action='store_true')
>>> parser.add_argument('bar')
>>> parser.parse_known_args(['--foo', '--badger', 'BAR', 'spam'])
(Namespace(bar='BAR', foo=True), ['--badger', 'spam'])

Warning

Prefix matching规则适用于parse_known_args()The parser may consume an option even if it’s just a prefix of one of its known options, instead of leaving it in the remaining arguments list.

15.4.5.8. 定制文件的解析

ArgumentParser.convert_arg_line_to_args(arg_line)

Arguments that are read from a file (see the fromfile_prefix_chars keyword argument to the ArgumentParser constructor) are read one argument per line. convert_arg_line_to_args() can be overriden for fancier reading.

This method takes a single argument arg_line which is a string read from the argument file. It returns a list of arguments parsed from this string. The method is called once per line read from the argument file, in order.

A useful override of this method is one that treats each space-separated word as an argument:

def convert_arg_line_to_args(self, arg_line):
    for arg in arg_line.split():
        if not arg.strip():
            continue
        yield arg

15.4.5.9. 退出的方法

ArgumentParser.exit(status=0, message=None)

This method terminates the program, exiting with the specified status and, if given, it prints a message before that.

ArgumentParser.error(message)

This method prints a usage message including the message to the standard error and terminates the program with a status code of 2.

15.4.6. 升级optparse的代码

最初,argparse模块尝试保持与optparse的兼容性。然而,optparse很难透明地扩展,特别是新的变化要求支持nargs=指示符和更好的用法帮助信息。optparse中的大部分内容已经被复制粘贴或者胡乱地打上补丁时,试图维持向后兼容性似乎不太实际。

optparseargparse的部分升级路线:

  • 替换所有的optparse.OptionParser.add_option()调用为ArgumentParser.add_argument()调用。
  • 替换(options, args) = parser.parse_args()args = parser.parse_args()并为位置参数增加一个额外的ArgumentParser.add_argument()调用。 记住之前叫做options的东西,现在在argparse环境中叫做args
  • 替换回调动作和callback_*关键字参数为type或者action参数。
  • 替换type关键字参数的字符串名称为相应的类型对象(例如int、float、complex等)。
  • 替换optparse.ValuesNamespace并替换optparse.OptionErroroptparse.OptionValueErrorArgumentError
  • 替换隐式参数的字符串为Python 的标准语法以使用字典来格式化字符串,例如替换%default%prog%(default)s%(prog)s
  • 替换OptionParser构造器的version参数为调用parser.add_argument('--version', action='version', version='<the version>')