argparse —- 命令行选项、参数和子命令解析器

3.2 新版功能.

源代码:Lib/argparse.py


教程

此页面包含该 API 的参考信息。有关 Python 命令行解析更细致的介绍,请参阅 argparse 教程

argparse 模块可以让人轻松编写用户友好的命令行接口。程序定义它需要的参数,然后 argparse 将弄清如何从 sys.argv 解析出那些参数。 argparse 模块还会自动生成帮助和使用手册,并在用户给程序传入无效参数时报出错误信息。

示例

以下代码是一个 Python 程序,它获取一个整数列表并计算总和或者最大值:

  1. import argparse
  2.  
  3. parser = argparse.ArgumentParser(description='Process some integers.')
  4. parser.add_argument('integers', metavar='N', type=int, nargs='+',
  5. help='an integer for the accumulator')
  6. parser.add_argument('--sum', dest='accumulate', action='store_const',
  7. const=sum, default=max,
  8. help='sum the integers (default: find the max)')
  9.  
  10. args = parser.parse_args()
  11. print(args.accumulate(args.integers))

假设上面的 Python 代码保存在名为 prog.py 的文件中,它可以在命令行运行并提供有用的帮助信息:

  1. $ python prog.py -h
  2. usage: prog.py [-h] [--sum] N [N ...]
  3.  
  4. Process some integers.
  5.  
  6. positional arguments:
  7. N an integer for the accumulator
  8.  
  9. optional arguments:
  10. -h, --help show this help message and exit
  11. --sum sum the integers (default: find the max)

当使用适当的参数运行时,它会输出命令行传入整数的总和或者最大值:

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

如果传入无效参数,则会报出错误:

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

以下部分将引导你完成这个示例。

创建一个解析器

使用 argparse 的第一步是创建一个 ArgumentParser 对象:

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

ArgumentParser 对象包含将命令行解析成 Python 数据类型所需的全部信息。

添加参数

给一个 ArgumentParser 添加程序参数信息是通过调用 add_argument() 方法完成的。通常,这些调用指定 ArgumentParser 如何获取命令行字符串并将其转换为对象。这些信息在 parse_args() 调用时被存储和使用。例如:

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

然后,调用 parse_args() 将返回一个具有 integersaccumulate 两个属性的对象。integers 属性将是一个包含一个或多个整数的列表,而 accumulate 属性当命令行中指定了 —sum 参数时将是 sum() 函数,否则则是 max() 函数。

解析参数

ArgumentParser 通过 parse_args() 方法解析参数。它将检查命令行,把每个参数转换为适当的类型然后调用相应的操作。在大多数情况下,这意味着一个简单的 Namespace 对象将从命令行解析出的属性构建:

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

在脚本中,通常 parse_args() 会被不带参数调用,而 ArgumentParser 将自动从 sys.argv 中确定命令行参数。

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, allow_abbrev=True)
  • 创建一个新的 ArgumentParser 对象。所有的参数都应当作为关键字参数传入。每个参数在下面都有它更详细的描述,但简而言之,它们是:

    • 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

    • allow_abbrev - 如果缩写是无歧义的,则允许缩写长选项 (默认值:True

在 3.5 版更改: 增加了 allow_abbrev 参数。

以下部分描述这些参数如何使用。

prog

默认情况下,ArgumentParser 对象使用 sys.argv[0] 来确定如何在帮助消息中显示程序名称。这一默认值几乎总是可取的,因为它将使帮助消息与从命令行调用此程序的方式相匹配。例如,对于有如下代码的名为 myprogram.py 的文件:

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

该程序的帮助信息将显示 myprogram.py 作为程序名称(无论程序从何处被调用):

  1. $ python myprogram.py --help
  2. usage: myprogram.py [-h] [--foo FOO]
  3.  
  4. optional arguments:
  5. -h, --help show this help message and exit
  6. --foo FOO foo help
  7. $ cd ..
  8. $ python subdir/myprogram.py --help
  9. usage: myprogram.py [-h] [--foo FOO]
  10.  
  11. optional arguments:
  12. -h, --help show this help message and exit
  13. --foo FOO foo help

要更改这样的默认行为,可以使用 prog= 参数为 ArgumentParser 指定另一个值:

  1. >>> parser = argparse.ArgumentParser(prog='myprogram')
  2. >>> parser.print_help()
  3. usage: myprogram [-h]
  4.  
  5. optional arguments:
  6. -h, --help show this help message and exit

需要注意的是,无论是从 sys.argv[0] 或是从 prog= 参数确定的程序名称,都可以在帮助消息里通过 %(prog)s 格式说明符来引用。

  1. >>> parser = argparse.ArgumentParser(prog='myprogram')
  2. >>> parser.add_argument('--foo', help='foo of the %(prog)s program')
  3. >>> parser.print_help()
  4. usage: myprogram [-h] [--foo FOO]
  5.  
  6. optional arguments:
  7. -h, --help show this help message and exit
  8. --foo FOO foo of the myprogram program

usage

默认情况下,ArgumentParser 根据它包含的参数来构建用法消息:

  1. >>> parser = argparse.ArgumentParser(prog='PROG')
  2. >>> parser.add_argument('--foo', nargs='?', help='foo help')
  3. >>> parser.add_argument('bar', nargs='+', help='bar help')
  4. >>> parser.print_help()
  5. usage: PROG [-h] [--foo [FOO]] bar [bar ...]
  6.  
  7. positional arguments:
  8. bar bar help
  9.  
  10. optional arguments:
  11. -h, --help show this help message and exit
  12. --foo [FOO] foo help

可以通过 usage= 关键字参数覆盖这一默认消息:

  1. >>> parser = argparse.ArgumentParser(prog='PROG', usage='%(prog)s [options]')
  2. >>> parser.add_argument('--foo', nargs='?', help='foo help')
  3. >>> parser.add_argument('bar', nargs='+', help='bar help')
  4. >>> parser.print_help()
  5. usage: PROG [options]
  6.  
  7. positional arguments:
  8. bar bar help
  9.  
  10. optional arguments:
  11. -h, --help show this help message and exit
  12. --foo [FOO] foo help

在用法消息中可以使用 %(prog)s 格式说明符来填入程序名称。

描述

大多数对 ArgumentParser 构造方法的调用都会使用 description= 关键字参数。这个参数简要描述这个程度做什么以及怎么做。在帮助消息中,这个描述会显示在命令行用法字符串和各种参数的帮助消息之间:

  1. >>> parser = argparse.ArgumentParser(description='A foo that bars')
  2. >>> parser.print_help()
  3. usage: argparse.py [-h]
  4.  
  5. A foo that bars
  6.  
  7. optional arguments:
  8. -h, --help show this help message and exit

在默认情况下,description 将被换行以便适应给定的空间。如果想改变这种行为,见 formatter_class 参数。

epilog

一些程序喜欢在 description 参数后显示额外的对程序的描述。这种文字能够通过给 ArgumentParser:: 提供 epilog= 参数而被指定。

  1. >>> parser = argparse.ArgumentParser(
  2. ... description='A foo that bars',
  3. ... epilog="And that's how you'd foo a bar")
  4. >>> parser.print_help()
  5. usage: argparse.py [-h]
  6.  
  7. A foo that bars
  8.  
  9. optional arguments:
  10. -h, --help show this help message and exit
  11.  
  12. And that's how you'd foo a bar

description 参数一样,epilog= text 在默认情况下会换行,但是这种行为能够被调整通过提供 formatter_class 参数给 ArgumentParse.

parents

有些时候,少数解析器会使用同一系列参数。 单个解析器能够通过提供 parents= 参数给 ArgumentParser 而使用相同的参数而不是重复这些参数的定义。parents= 参数使用 ArgumentParser 对象的列表,从它们那里收集所有的位置和可选的行为,然后将这写行为加到正在构建的 ArgumentParser 对象。

  1. >>> parent_parser = argparse.ArgumentParser(add_help=False)
  2. >>> parent_parser.add_argument('--parent', type=int)
  3.  
  4. >>> foo_parser = argparse.ArgumentParser(parents=[parent_parser])
  5. >>> foo_parser.add_argument('foo')
  6. >>> foo_parser.parse_args(['--parent', '2', 'XXX'])
  7. Namespace(foo='XXX', parent=2)
  8.  
  9. >>> bar_parser = argparse.ArgumentParser(parents=[parent_parser])
  10. >>> bar_parser.add_argument('--bar')
  11. >>> bar_parser.parse_args(['--bar', 'YYY'])
  12. Namespace(bar='YYY', parent=None)

请注意大多数父解析器会指定 add_help=False . 否则, ArgumentParse 将会看到两个 -h/—help 选项(一个在父参数中一个在子参数中)并且产生一个错误。

注解

你在传parents=给那些解析器时必须完全初始化它们。如果你在子解析器之后改变父解析器是,这些改变不会反映在子解析器上。

formatter_class

ArgumentParser 对象允许通过指定备用格式化类来自定义帮助格式。目前,有四种这样的类。

  • class argparse.RawDescriptionHelpFormatter
  • class argparse.RawTextHelpFormatter
  • class argparse.ArgumentDefaultsHelpFormatter
  • class argparse.MetavarTypeHelpFormatter

RawDescriptionHelpFormatterRawTextHelpFormatter 在正文的描述和展示上给与了更多的控制。ArgumentParser 对象会将 descriptionepilog 的文字在命令行中自动换行。

  1. >>> parser = argparse.ArgumentParser(
  2. ... prog='PROG',
  3. ... description='''this description
  4. ... was indented weird
  5. ... but that is okay''',
  6. ... epilog='''
  7. ... likewise for this epilog whose whitespace will
  8. ... be cleaned up and whose words will be wrapped
  9. ... across a couple lines''')
  10. >>> parser.print_help()
  11. usage: PROG [-h]
  12.  
  13. this description was indented weird but that is okay
  14.  
  15. optional arguments:
  16. -h, --help show this help message and exit
  17.  
  18. likewise for this epilog whose whitespace will be cleaned up and whose words
  19. will be wrapped across a couple lines

RawDescriptionHelpFormatterformatter_class= 表示 descriptionepilog 已经被正确的格式化了,不能在命令行中被自动换行:

  1. >>> parser = argparse.ArgumentParser(
  2. ... prog='PROG',
  3. ... formatter_class=argparse.RawDescriptionHelpFormatter,
  4. ... description=textwrap.dedent('''\
  5. ... Please do not mess up this text!
  6. ... --------------------------------
  7. ... I have indented it
  8. ... exactly the way
  9. ... I want it
  10. ... '''))
  11. >>> parser.print_help()
  12. usage: PROG [-h]
  13.  
  14. Please do not mess up this text!
  15. --------------------------------
  16. I have indented it
  17. exactly the way
  18. I want it
  19.  
  20. optional arguments:
  21. -h, --help show this help message and exit

RawTextHelpFormatter 保留所有种类文字的空格,包括参数的描述。然而,多重的新行会被替换成一行。如果你想保留多重的空白行,可以在新行之间加空格。

ArgumentDefaultsHelpFormatter 自动添加默认的值的信息到每一个帮助信息的参数中:

  1. >>> parser = argparse.ArgumentParser(
  2. ... prog='PROG',
  3. ... formatter_class=argparse.ArgumentDefaultsHelpFormatter)
  4. >>> parser.add_argument('--foo', type=int, default=42, help='FOO!')
  5. >>> parser.add_argument('bar', nargs='*', default=[1, 2, 3], help='BAR!')
  6. >>> parser.print_help()
  7. usage: PROG [-h] [--foo FOO] [bar [bar ...]]
  8.  
  9. positional arguments:
  10. bar BAR! (default: [1, 2, 3])
  11.  
  12. optional arguments:
  13. -h, --help show this help message and exit
  14. --foo FOO FOO! (default: 42)

MetavarTypeHelpFormatter 为它的值在每一个参数中使用 type 的参数名当作它的显示名(而不是使用通常的格式 dest ):

  1. >>> parser = argparse.ArgumentParser(
  2. ... prog='PROG',
  3. ... formatter_class=argparse.MetavarTypeHelpFormatter)
  4. >>> parser.add_argument('--foo', type=int)
  5. >>> parser.add_argument('bar', type=float)
  6. >>> parser.print_help()
  7. usage: PROG [-h] [--foo int] float
  8.  
  9. positional arguments:
  10. float
  11.  
  12. optional arguments:
  13. -h, --help show this help message and exit
  14. --foo int

prefix_chars

许多命令行会使用 - 当作前缀,比如 -f/—foo。如果解析器需要支持不同的或者额外的字符,比如像 +f 或者 /foo 的选项,可以在参数解析构建器中使用 prefix_chars= 参数。

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

The prefix_chars= 参数默认使用 '-'. 支持一系列字符,但是不包括 - ,这样会产生不被允许的 -f/—foo 选项。

fromfile_prefix_chars

有些时候,先举个例子,当处理一个特别长的参数列表的时候,把它存入一个文件中而不是在命令行打出来会很有意义。如果 fromfile_prefix_chars= 参数提供给 ArgumentParser 构造函数,之后所有类型的字符的参数都会被当成文件处理,并且会被文件包含的参数替代。举个栗子:

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

从文件读取的参数在默认情况下必须一个一行(但是可参见 convert_arg_line_to_args())并且它们被视为与命令行上的原始文件引用参数位于同一位置。所以在以上例子中,['-f', 'foo', '@args.txt'] 的表示和 ['-f', 'foo', '-f', 'bar'] 的表示相同。

fromfile_prefix_chars= 参数默认为 None,意味着参数不会被当作文件对待。

argument_default

一般情况下,参数默认会通过设置一个默认到 add_argument() 或者调用带一组指定键值对的 ArgumentParser.set_defaults() 方法。但是有些时候,为参数指定一个普遍适用的解析器会更有用。这能够通过传输 argument_default= 关键词参数给 ArgumentParser 来完成。举个栗子,要全局禁止在 parse_args() 中创建属性,我们提供 argument_default=SUPPRESS:

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

allow_abbrev

正常情况下,当你向 ArgumentParserparse_args() 方法传入一个参数列表时,它会 recognizes abbreviations

这个特性可以设置 allow_abbrevFalse 来关闭:

  1. >>> parser = argparse.ArgumentParser(prog='PROG', allow_abbrev=False)
  2. >>> parser.add_argument('--foobar', action='store_true')
  3. >>> parser.add_argument('--foonley', action='store_false')
  4. >>> parser.parse_args(['--foon'])
  5. usage: PROG [-h] [--foobar] [--foonley]
  6. PROG: error: unrecognized arguments: --foon

3.5 新版功能.

conflict_handler

ArgumentParser 对象不允许在相同选项字符串下有两种行为。默认情况下, ArgumentParser 对象会产生一个异常如果去创建一个正在使用的选项字符串参数。

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

有些时候(例如:使用 parents),重写旧的有相同选项字符串的参数会更有用。为了产生这种行为, 'resolve' 值可以提供给 ArgumentParserconflict_handler= 参数:

  1. >>> parser = argparse.ArgumentParser(prog='PROG', conflict_handler='resolve')
  2. >>> parser.add_argument('-f', '--foo', help='old foo help')
  3. >>> parser.add_argument('--foo', help='new foo help')
  4. >>> parser.print_help()
  5. usage: PROG [-h] [-f FOO] [--foo FOO]
  6.  
  7. optional arguments:
  8. -h, --help show this help message and exit
  9. -f FOO old foo help
  10. --foo FOO new foo help

注意 ArgumentParser 对象只能移除一个行为如果它所有的选项字符串都被重写。所以,在上面的例子中,旧的 -f/—foo 行为 回合 -f 行为保持一样, 因为只有 —foo 选项字符串被重写。

add_help

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

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

如果 -h or —help 在命令行中被提供, 参数解析器帮助信息会打印:

  1. $ python myprogram.py --help
  2. usage: myprogram.py [-h] [--foo FOO]
  3.  
  4. optional arguments:
  5. -h, --help show this help message and exit
  6. --foo FOO foo help

有时候可能会需要关闭额外的帮助信息。这可以通过在 ArgumentParser 中设置 add_help= 参数为 False 来实现。

  1. >>> parser = argparse.ArgumentParser(prog='PROG', add_help=False)
  2. >>> parser.add_argument('--foo', help='foo help')
  3. >>> parser.print_help()
  4. usage: PROG [--foo FOO]
  5.  
  6. optional arguments:
  7. --foo FOO foo help

帮助选项一般为 -h/—help。如果 prefix_chars= 被指定并且没有包含 - 字符,在这种情况下, -h —help 不是有效的选项。此时, prefix_chars 的第一个字符将用作帮助选项的前缀。

  1. >>> parser = argparse.ArgumentParser(prog='PROG', prefix_chars='+/')
  2. >>> parser.print_help()
  3. usage: PROG [+h]
  4.  
  5. optional arguments:
  6. +h, ++help show this help message and exit

add_argument() 方法

  • ArgumentParser.addargument(_name or flags…[, action][, nargs][, const][, default][, type][, choices][, required][, help][, metavar][, dest])
  • 定义单个的命令行参数应当如何解析。每个形参都在下面有它自己更多的描述,长话短说有:

    • name or flags - 一个命名或者一个选项字符串的列表,例如 foo-f, —foo

    • action - 当参数在命令行中出现时使用的动作基本类型。

    • nargs - 命令行参数应当消耗的数目。

    • const - 被一些 actionnargs 选择所需求的常数。

    • default - 当参数未在命令行中出现时使用的值。

    • type - 命令行参数应当被转换成的类型。

    • choices - 可用的参数的容器。

    • required - 此命令行选项是否可省略 (仅选项可用)。

    • help - 一个此选项作用的简单描述。

    • metavar - 在使用方法消息中使用的参数值示例。

    • dest - 被添加到 parse_args() 所返回对象上的属性名。

以下部分描述这些参数如何使用。

name or flags

add_argument() 方法必须知道它是否是一个选项,例如 -f—foo,或是一个位置参数,例如一组文件名。第一个传递给 add_argument() 的参数必须是一系列 flags 或者是一个简单的参数名。例如,可以选项可以被这样创建:

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

而位置参数可以这么创建:

  1. >>> parser.add_argument('bar')

parse_args() 被调用,选项会以 - 前缀识别,剩下的参数则会被假定为位置参数:

  1. >>> parser = argparse.ArgumentParser(prog='PROG')
  2. >>> parser.add_argument('-f', '--foo')
  3. >>> parser.add_argument('bar')
  4. >>> parser.parse_args(['BAR'])
  5. Namespace(bar='BAR', foo=None)
  6. >>> parser.parse_args(['BAR', '--foo', 'FOO'])
  7. Namespace(bar='BAR', foo='FOO')
  8. >>> parser.parse_args(['--foo', 'FOO'])
  9. usage: PROG [-h] [-f FOO] bar
  10. PROG: error: the following arguments are required: bar

action

ArgumentParser 对象将命令行参数与动作相关联。这些动作可以做与它们相关联的命令行参数的任何事,尽管大多数动作只是简单的向 parse_args() 返回的对象上添加属性。action 命名参数指定了这个命令行参数应当如何处理。供应的动作有:

  • 'store' - 存储参数的值。这是默认的动作。例如:
  1. >>> parser = argparse.ArgumentParser()
  2. >>> parser.add_argument('--foo')
  3. >>> parser.parse_args('--foo 1'.split())
  4. Namespace(foo='1')
  • 'store_const' - 存储被 const 命名参数指定的值。 'store_const' 动作通常用在选项中来指定一些标志。例如:
  1. >>> parser = argparse.ArgumentParser()
  2. >>> parser.add_argument('--foo', action='store_const', const=42)
  3. >>> parser.parse_args(['--foo'])
  4. Namespace(foo=42)
  • 'store_true' and 'store_false' - 这些是 'store_const' 分别用作存储 TrueFalse 值的特殊用例。另外,它们的默认值分别为 FalseTrue。例如:
  1. >>> parser = argparse.ArgumentParser()
  2. >>> parser.add_argument('--foo', action='store_true')
  3. >>> parser.add_argument('--bar', action='store_false')
  4. >>> parser.add_argument('--baz', action='store_false')
  5. >>> parser.parse_args('--foo --bar'.split())
  6. Namespace(foo=True, bar=False, baz=True)
  • 'append' - 存储一个列表,并且将每个参数值追加到列表中。在允许多次使用选项时很有用。例如:
  1. >>> parser = argparse.ArgumentParser()
  2. >>> parser.add_argument('--foo', action='append')
  3. >>> parser.parse_args('--foo 1 --foo 2'.split())
  4. Namespace(foo=['1', '2'])
  • 'append_const' - 这存储一个列表,并将 const 命名参数指定的值追加到列表中。(注意 const 命名参数默认为 None。)&#39;append_const&#39; 动作一般在多个参数需要在同一列表中存储常数时会有用。例如:
  1. >>> parser = argparse.ArgumentParser()
  2. >>> parser.add_argument('--str', dest='types', action='append_const', const=str)
  3. >>> parser.add_argument('--int', dest='types', action='append_const', const=int)
  4. >>> parser.parse_args('--str --int'.split())
  5. Namespace(types=[<class 'str'>, <class 'int'>])
  • 'count' - 计算一个关键字参数出现的数目或次数。例如,对于一个增长的详情等级来说有用:
  1. >>> parser = argparse.ArgumentParser()
  2. >>> parser.add_argument('--verbose', '-v', action='count', default=0)
  3. >>> parser.parse_args(['-vvv'])
  4. Namespace(verbose=3)

Note, the default will be None unless explicitly set to 0.

  • 'help' - 打印所有当前解析器中的选项和参数的完整帮助信息,然后退出。默认情况下,一个 help 动作会被自动加入解析器。关于输出是如何创建的,参与 ArgumentParser

  • 'version' - 期望有一个 version= 命名参数在 add_argument() 调用中,并打印版本信息并在调用后退出:

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

您还可以通过传递 Action 子类或实现相同接口的其他对象来指定任意操作。建议的方法是扩展 Action,覆盖 call 方法和可选的 init 方法。

一个自定义动作的例子:

  1. >>> class FooAction(argparse.Action):
  2. ... def __init__(self, option_strings, dest, nargs=None, **kwargs):
  3. ... if nargs is not None:
  4. ... raise ValueError("nargs not allowed")
  5. ... super(FooAction, self).__init__(option_strings, dest, **kwargs)
  6. ... def __call__(self, parser, namespace, values, option_string=None):
  7. ... print('%r %r %r' % (namespace, values, option_string))
  8. ... setattr(namespace, self.dest, values)
  9. ...
  10. >>> parser = argparse.ArgumentParser()
  11. >>> parser.add_argument('--foo', action=FooAction)
  12. >>> parser.add_argument('bar', action=FooAction)
  13. >>> args = parser.parse_args('1 --foo 2'.split())
  14. Namespace(bar=None, foo=None) '1' None
  15. Namespace(bar='1', foo=None) '2' '--foo'
  16. >>> args
  17. Namespace(bar='1', foo='2')

更多描述,见 Action

nargs

ArgumentParser 对象通常关联一个单独的命令行参数到一个单独的被执行的动作。 nargs 命名参数关联不同数目的命令行参数到单一动作。支持的值有:

  • N (一个整数)。命令行中的 N 个参数会被聚集到一个列表中。 例如:
  1. >>> parser = argparse.ArgumentParser()
  2. >>> parser.add_argument('--foo', nargs=2)
  3. >>> parser.add_argument('bar', nargs=1)
  4. >>> parser.parse_args('c --foo a b'.split())
  5. Namespace(bar=['c'], foo=['a', 'b'])

注意 nargs=1 会产生一个单元素列表。这和默认的元素本身是不同的。

  • '?'。如果可能的话,会从命令行中消耗一个参数,并产生一个单一项。如果当前没有命令行参数,则会产生 default 值。注意,对于选项,有另外的用例 - 选项字符串出现但没有跟随命令行参数,则会产生 const 值。一些说用用例:
  1. >>> parser = argparse.ArgumentParser()
  2. >>> parser.add_argument('--foo', nargs='?', const='c', default='d')
  3. >>> parser.add_argument('bar', nargs='?', default='d')
  4. >>> parser.parse_args(['XX', '--foo', 'YY'])
  5. Namespace(bar='XX', foo='YY')
  6. >>> parser.parse_args(['XX', '--foo'])
  7. Namespace(bar='XX', foo='c')
  8. >>> parser.parse_args([])
  9. Namespace(bar='d', foo='d')

nargs='?' 的一个更普遍用法是允许可选的输入或输出文件:

  1. >>> parser = argparse.ArgumentParser()
  2. >>> parser.add_argument('infile', nargs='?', type=argparse.FileType('r'),
  3. ... default=sys.stdin)
  4. >>> parser.add_argument('outfile', nargs='?', type=argparse.FileType('w'),
  5. ... default=sys.stdout)
  6. >>> parser.parse_args(['input.txt', 'output.txt'])
  7. Namespace(infile=<_io.TextIOWrapper name='input.txt' encoding='UTF-8'>,
  8. outfile=<_io.TextIOWrapper name='output.txt' encoding='UTF-8'>)
  9. >>> parser.parse_args([])
  10. Namespace(infile=<_io.TextIOWrapper name='<stdin>' encoding='UTF-8'>,
  11. outfile=<_io.TextIOWrapper name='<stdout>' encoding='UTF-8'>)
  • ''。所有当前命令行参数被聚集到一个列表中。注意通过 nargs='' 来实现多个位置参数通常没有意义,但是多个选项是可能的。例如:
  1. >>> parser = argparse.ArgumentParser()
  2. >>> parser.add_argument('--foo', nargs='*')
  3. >>> parser.add_argument('--bar', nargs='*')
  4. >>> parser.add_argument('baz', nargs='*')
  5. >>> parser.parse_args('a b --foo x y --bar 1 2'.split())
  6. Namespace(bar=['1', '2'], baz=['a', 'b'], foo=['x', 'y'])
  • '+'。和 '*' 类似,所有当前命令行参数被聚集到一个列表中。另外,当前没有至少一个命令行参数时会产生一个错误信息。例如:
  1. >>> parser = argparse.ArgumentParser(prog='PROG')
  2. >>> parser.add_argument('foo', nargs='+')
  3. >>> parser.parse_args(['a', 'b'])
  4. Namespace(foo=['a', 'b'])
  5. >>> parser.parse_args([])
  6. usage: PROG [-h] foo [foo ...]
  7. PROG: error: the following arguments are required: foo
  • argarse.REMAINDER。所有剩余的命令行参数被聚集到一个列表中。这通常在从一个命令行功能传递参数到另一个命令行功能中时有用:
  1. >>> parser = argparse.ArgumentParser(prog='PROG')
  2. >>> parser.add_argument('--foo')
  3. >>> parser.add_argument('command')
  4. >>> parser.add_argument('args', nargs=argparse.REMAINDER)
  5. >>> print(parser.parse_args('--foo B cmd --arg1 XX ZZ'.split()))
  6. Namespace(args=['--arg1', 'XX', 'ZZ'], command='cmd', foo='B')

如果不提供 nargs 命名参数,则消耗参数的数目将被 action 决定。通常这意味着单一项目(非列表)消耗单一命令行参数。

const

add_argument()const 参数用于保存不从命令行中读取但被各种 ArgumentParser 动作需求的常数值。最常用的两例为:

  • add_argument() 通过 action='store_const'action='append_const 调用时。这些动作将 const 值添加到 parse_args() 返回的对象的属性中。在 action 的描述中查看案例。

  • add_argument() 通过选项(例如 -f—foo)调用并且 nargs='?' 时。这会创建一个可以跟随零个或一个命令行参数的选项。当解析命令行时,如果选项后没有参数,则将用 const 代替。在 nargs 描述中查看案例。

'store_const''append_const' 动作, const 命名参数必须给出。对其他动作,默认为 None

默认值

所有选项和一些位置参数可能在命令行中被忽略。add_argument() 的命名参数 default,默认值为 None,指定了在命令行参数未出现时应当使用的值。对于选项, default 值在选项未在命令行中出现时使用:

  1. >>> parser = argparse.ArgumentParser()
  2. >>> parser.add_argument('--foo', default=42)
  3. >>> parser.parse_args(['--foo', '2'])
  4. Namespace(foo='2')
  5. >>> parser.parse_args([])
  6. Namespace(foo=42)

如果 default 值是一个字符串,解析器解析此值就像一个命令行参数。特别是,在将属性设置在 Namespace 的返回值之前,解析器应用任何提供的 type 转换参数。否则解析器使用原值:

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

对于 nargs 等于 ?* 的位置参数, default 值在没有命令行参数出现时使用。

  1. >>> parser = argparse.ArgumentParser()
  2. >>> parser.add_argument('foo', nargs='?', default=42)
  3. >>> parser.parse_args(['a'])
  4. Namespace(foo='a')
  5. >>> parser.parse_args([])
  6. Namespace(foo=42)

提供 default=argparse.SUPPRESS 导致命令行参数未出现时没有属性被添加:

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

type — 类型

默认情况下,ArgumentParser 对象将命令行参数当作简单字符串读入。然而,命令行字符串经常需要被当作其它的类型,比如 float 或者 intadd_argument()type 关键词参数允许任何的类型检查和类型转换。一般的内建类型和函数可以直接被 type 参数使用。

  1. >>> parser = argparse.ArgumentParser()
  2. >>> parser.add_argument('foo', type=int)
  3. >>> parser.add_argument('bar', type=open)
  4. >>> parser.parse_args('2 temp.txt'.split())
  5. Namespace(bar=<_io.TextIOWrapper name='temp.txt' encoding='UTF-8'>, foo=2)

type 参数被应用到默认参数时,请参考 default 参数的部分。

To ease the use of various types of files, the argparse module provides thefactory FileType which takes the mode=, bufsize=, encoding= anderrors= arguments of the open() function. For example,FileType('w') can be used to create a writable file:

  1. >>> parser = argparse.ArgumentParser()
  2. >>> parser.add_argument('bar', type=argparse.FileType('w'))
  3. >>> parser.parse_args(['out.txt'])
  4. Namespace(bar=<_io.TextIOWrapper name='out.txt' encoding='UTF-8'>)

type= can take any callable that takes a single string argument and returnsthe converted value:

  1. >>> def perfect_square(string):
  2. ... value = int(string)
  3. ... sqrt = math.sqrt(value)
  4. ... if sqrt != int(sqrt):
  5. ... msg = "%r is not a perfect square" % string
  6. ... raise argparse.ArgumentTypeError(msg)
  7. ... return value
  8. ...
  9. >>> parser = argparse.ArgumentParser(prog='PROG')
  10. >>> parser.add_argument('foo', type=perfect_square)
  11. >>> parser.parse_args(['9'])
  12. Namespace(foo=9)
  13. >>> parser.parse_args(['7'])
  14. usage: PROG [-h] foo
  15. PROG: error: argument foo: '7' is not a perfect square

choices 关键词参数可能会使类型检查者更方便的检查一个范围的值。

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

详情请查阅 choices 段落。

choices

Some command-line arguments should be selected from a restricted set of values.These can be handled by passing a container object as the choices keywordargument to add_argument(). When the command line isparsed, argument values will be checked, and an error message will be displayedif the argument was not one of the acceptable values:

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

Note that inclusion in the choices container is checked after any typeconversions have been performed, so the type of the objects in the _choices_container should match the type specified:

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

Any object that supports the in operator can be passed as the _choices_value, so dict objects, set objects, custom containers,etc. are all supported.

required

In general, the argparse module assumes that flags like -f and —barindicate optional arguments, which can always be omitted at the command line.To make an option required, True can be specified for the required=keyword argument to add_argument():

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

As the example shows, if an option is marked as required,parse_args() will report an error if that option is notpresent at the command line.

注解

Required options are generally considered bad form because users expectoptions to be optional, and thus they should be avoided when possible.

help

The help value is a string containing a brief description of the argument.When a user requests help (usually by using -h or —help at thecommand line), these help descriptions will be displayed with eachargument:

  1. >>> parser = argparse.ArgumentParser(prog='frobble')
  2. >>> parser.add_argument('--foo', action='store_true',
  3. ... help='foo the bars before frobbling')
  4. >>> parser.add_argument('bar', nargs='+',
  5. ... help='one of the bars to be frobbled')
  6. >>> parser.parse_args(['-h'])
  7. usage: frobble [-h] [--foo] bar [bar ...]
  8.  
  9. positional arguments:
  10. bar one of the bars to be frobbled
  11.  
  12. optional arguments:
  13. -h, --help show this help message and exit
  14. --foo foo the bars before frobbling

The help strings can include various format specifiers to avoid repetitionof things like the program name or the argument default. The availablespecifiers include the program name, %(prog)s and most keyword arguments toadd_argument(), e.g. %(default)s, %(type)s, etc.:

  1. >>> parser = argparse.ArgumentParser(prog='frobble')
  2. >>> parser.add_argument('bar', nargs='?', type=int, default=42,
  3. ... help='the bar to %(prog)s (default: %(default)s)')
  4. >>> parser.print_help()
  5. usage: frobble [-h] [bar]
  6.  
  7. positional arguments:
  8. bar the bar to frobble (default: 42)
  9.  
  10. optional arguments:
  11. -h, --help show this help message and exit

As the help string supports %-formatting, if you want a literal % to appearin the help string, you must escape it as %%.

argparse supports silencing the help entry for certain options, bysetting the help value to argparse.SUPPRESS:

  1. >>> parser = argparse.ArgumentParser(prog='frobble')
  2. >>> parser.add_argument('--foo', help=argparse.SUPPRESS)
  3. >>> parser.print_help()
  4. usage: frobble [-h]
  5.  
  6. optional arguments:
  7. -h, --help show this help message and exit

metavar

When ArgumentParser generates help messages, it needs some way to referto each expected argument. By default, ArgumentParser objects use the destvalue as the "name" of each object. By default, for positional argumentactions, the dest value is used directly, and for optional argument actions,the dest value is uppercased. So, a single positional argument withdest='bar' will be referred to as bar. A singleoptional argument —foo that should be followed by a single command-line argumentwill be referred to as FOO. An example:

  1. >>> parser = argparse.ArgumentParser()
  2. >>> parser.add_argument('--foo')
  3. >>> parser.add_argument('bar')
  4. >>> parser.parse_args('X --foo Y'.split())
  5. Namespace(bar='X', foo='Y')
  6. >>> parser.print_help()
  7. usage: [-h] [--foo FOO] bar
  8.  
  9. positional arguments:
  10. bar
  11.  
  12. optional arguments:
  13. -h, --help show this help message and exit
  14. --foo FOO

An alternative name can be specified with metavar:

  1. >>> parser = argparse.ArgumentParser()
  2. >>> parser.add_argument('--foo', metavar='YYY')
  3. >>> parser.add_argument('bar', metavar='XXX')
  4. >>> parser.parse_args('X --foo Y'.split())
  5. Namespace(bar='X', foo='Y')
  6. >>> parser.print_help()
  7. usage: [-h] [--foo YYY] XXX
  8.  
  9. positional arguments:
  10. XXX
  11.  
  12. optional arguments:
  13. -h, --help show this help message and exit
  14. --foo YYY

Note that metavar only changes the displayed name - the name of theattribute on the parse_args() object is still determinedby 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 thearguments:

  1. >>> parser = argparse.ArgumentParser(prog='PROG')
  2. >>> parser.add_argument('-x', nargs=2)
  3. >>> parser.add_argument('--foo', nargs=2, metavar=('bar', 'baz'))
  4. >>> parser.print_help()
  5. usage: PROG [-h] [-x X X] [--foo bar baz]
  6.  
  7. optional arguments:
  8. -h, --help show this help message and exit
  9. -x X X
  10. --foo bar baz

dest

Most ArgumentParser actions add some value as an attribute of theobject returned by parse_args(). The name of thisattribute is determined by the dest keyword argument ofadd_argument(). For positional argument actions,dest is normally supplied as the first argument toadd_argument():

  1. >>> parser = argparse.ArgumentParser()
  2. >>> parser.add_argument('bar')
  3. >>> parser.parse_args(['XXX'])
  4. Namespace(bar='XXX')

For optional argument actions, the value of dest is normally inferred fromthe option strings. ArgumentParser generates the value of dest bytaking the first long option string and stripping away the initial string. If no long option strings were supplied, dest will be derived fromthe first short option string by stripping the initial - character. Anyinternal - characters will be converted to _ characters to make surethe string is a valid attribute name. The examples below illustrate thisbehavior:

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

dest allows a custom attribute name to be provided:

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

Action classes

Action classes implement the Action API, a callable which returns a callablewhich processes arguments from the command-line. Any object which followsthis API may be passed as the action parameter toadd_argument().

  • class argparse.Action(option_strings, dest, nargs=None, const=None, default=None, type=None, choices=None, required=False, help=None, metavar=None)

Action objects are used by an ArgumentParser to represent the informationneeded to parse a single argument from one or more strings from thecommand line. The Action class must accept the two positional argumentsplus any keyword arguments passed to ArgumentParser.add_argument()except for the action itself.

Instances of Action (or return value of any callable to the actionparameter) should have attributes "dest", "optionstrings", "default", "type","required", "help", etc. defined. The easiest way to ensure these attributesare defined is to call Action._init.

Action instances should be callable, so subclasses must override thecall method, which should accept four parameters:

  • parser - The ArgumentParser object which contains this action.

  • namespace - The Namespace object that will be returned byparse_args(). Most actions add an attribute to thisobject using setattr().

  • values - The associated command-line arguments, with any type conversionsapplied. Type conversions are specified with the type keyword argument toadd_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 actionis associated with a positional argument.

The call method may perform arbitrary actions, but will typically setattributes on the namespace based on dest and values.

parse_args() 方法

  • ArgumentParser.parseargs(_args=None, namespace=None)
  • Convert argument strings to objects and assign them as attributes of thenamespace. Return the populated namespace.

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

  • args - List of strings to parse. The default is taken fromsys.argv.

  • namespace - An object to take the attributes. The default is a new emptyNamespace object.

Option value syntax

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

  1. >>> parser = argparse.ArgumentParser(prog='PROG')
  2. >>> parser.add_argument('-x')
  3. >>> parser.add_argument('--foo')
  4. >>> parser.parse_args(['-x', 'X'])
  5. Namespace(foo=None, x='X')
  6. >>> parser.parse_args(['--foo', 'FOO'])
  7. Namespace(foo='FOO', x=None)

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

  1. >>> parser.parse_args(['--foo=FOO'])
  2. Namespace(foo='FOO', x=None)

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

  1. >>> parser.parse_args(['-xX'])
  2. Namespace(foo=None, x='X')

Several short options can be joined together, using only a single - prefix,as long as only the last option (or none of them) requires a value:

  1. >>> parser = argparse.ArgumentParser(prog='PROG')
  2. >>> parser.add_argument('-x', action='store_true')
  3. >>> parser.add_argument('-y', action='store_true')
  4. >>> parser.add_argument('-z')
  5. >>> parser.parse_args(['-xyzZ'])
  6. Namespace(x=True, y=True, z='Z')

无效的参数

While parsing the command line, parse_args() checks for avariety 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:

  1. >>> parser = argparse.ArgumentParser(prog='PROG')
  2. >>> parser.add_argument('--foo', type=int)
  3. >>> parser.add_argument('bar', nargs='?')
  4.  
  5. >>> # invalid type
  6. >>> parser.parse_args(['--foo', 'spam'])
  7. usage: PROG [-h] [--foo FOO] [bar]
  8. PROG: error: argument --foo: invalid int value: 'spam'
  9.  
  10. >>> # invalid option
  11. >>> parser.parse_args(['--bar'])
  12. usage: PROG [-h] [--foo FOO] [bar]
  13. PROG: error: no such option: --bar
  14.  
  15. >>> # wrong number of arguments
  16. >>> parser.parse_args(['spam', 'badger'])
  17. usage: PROG [-h] [--foo FOO] [bar]
  18. PROG: error: extra arguments found: badger

包含 - 的参数

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

  1. >>> parser = argparse.ArgumentParser(prog='PROG')
  2. >>> parser.add_argument('-x')
  3. >>> parser.add_argument('foo', nargs='?')
  4.  
  5. >>> # no negative number options, so -1 is a positional argument
  6. >>> parser.parse_args(['-x', '-1'])
  7. Namespace(foo=None, x='-1')
  8.  
  9. >>> # no negative number options, so -1 and -5 are positional arguments
  10. >>> parser.parse_args(['-x', '-1', '-5'])
  11. Namespace(foo='-5', x='-1')
  12.  
  13. >>> parser = argparse.ArgumentParser(prog='PROG')
  14. >>> parser.add_argument('-1', dest='one')
  15. >>> parser.add_argument('foo', nargs='?')
  16.  
  17. >>> # negative number options present, so -1 is an option
  18. >>> parser.parse_args(['-1', 'X'])
  19. Namespace(foo=None, one='X')
  20.  
  21. >>> # negative number options present, so -2 is an option
  22. >>> parser.parse_args(['-2'])
  23. usage: PROG [-h] [-1 ONE] [foo]
  24. PROG: error: no such option: -2
  25.  
  26. >>> # negative number options present, so both -1s are options
  27. >>> parser.parse_args(['-1', '-1'])
  28. usage: PROG [-h] [-1 ONE] [foo]
  29. PROG: error: argument -1: expected one argument

If you have positional arguments that must begin with - and don't looklike negative numbers, you can insert the pseudo-argument '—' which tellsparse_args() that everything after that is a positionalargument:

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

参数缩写(前缀匹配)

The parse_args() method by defaultallows long options to be abbreviated to a prefix, if the abbreviation isunambiguous (the prefix matches a unique option):

  1. >>> parser = argparse.ArgumentParser(prog='PROG')
  2. >>> parser.add_argument('-bacon')
  3. >>> parser.add_argument('-badger')
  4. >>> parser.parse_args('-bac MMM'.split())
  5. Namespace(bacon='MMM', badger=None)
  6. >>> parser.parse_args('-bad WOOD'.split())
  7. Namespace(bacon=None, badger='WOOD')
  8. >>> parser.parse_args('-ba BA'.split())
  9. usage: PROG [-h] [-bacon BACON] [-badger BADGER]
  10. PROG: error: ambiguous option: -ba could match -badger, -bacon

An error is produced for arguments that could produce more than one options.This feature can be disabled by setting allow_abbrev to False.

Beyond sys.argv

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

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

命名空间对象

  • class argparse.Namespace
  • Simple class used by default by parse_args() to createan object holding attributes and return it.

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

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

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

  1. >>> class C:
  2. ... pass
  3. ...
  4. >>> c = C()
  5. >>> parser = argparse.ArgumentParser()
  6. >>> parser.add_argument('--foo')
  7. >>> parser.parse_args(args=['--foo', 'BAR'], namespace=c)
  8. >>> c.foo
  9. 'BAR'

其它实用工具

子命令

  • ArgumentParser.addsubparsers([_title][, description][, prog][, parser_class][, action][, option_string][, dest][, required][, help][, metavar])
  • Many programs split up their functionality into a number of sub-commands,for example, the svn program can invoke sub-commands like svncheckout, svn update, and svn commit. Splitting up functionalitythis way can be a particularly good idea when a program performs severaldifferent functions which require different kinds of command-line arguments.ArgumentParser supports the creation of such sub-commands with theadd_subparsers() method. The add_subparsers() method is normallycalled with no arguments and returns a special action object. This objecthas a single method, add_parser(), which takes acommand name and any ArgumentParser constructor arguments, andreturns an ArgumentParser object that can be modified as usual.

形参的描述

  • title - title for the sub-parser group in help output; by default"subcommands" if description is provided, otherwise uses title forpositional arguments

  • description - description for the sub-parser group in help output, bydefault None

  • prog - usage information that will be displayed with sub-command help,by default the name of the program and any positional arguments before thesubparser argument

  • parser_class - class which will be used to create sub-parser instances, bydefault the class of the current parser (e.g. ArgumentParser)

  • action - the basic type of action to be taken when this argument isencountered at the command line

  • dest - name of the attribute under which sub-command name will bestored; by default None and no value is stored

  • required - Whether or not a subcommand must be provided, by defaultFalse (added in 3.7)

  • help - help for sub-parser group in help output, by default None

  • metavar - string presenting available sub-commands in help; by default itis None and presents sub-commands in form {cmd1, cmd2, ..}

一些使用示例:

  1. >>> # create the top-level parser
  2. >>> parser = argparse.ArgumentParser(prog='PROG')
  3. >>> parser.add_argument('--foo', action='store_true', help='foo help')
  4. >>> subparsers = parser.add_subparsers(help='sub-command help')
  5. >>>
  6. >>> # create the parser for the "a" command
  7. >>> parser_a = subparsers.add_parser('a', help='a help')
  8. >>> parser_a.add_argument('bar', type=int, help='bar help')
  9. >>>
  10. >>> # create the parser for the "b" command
  11. >>> parser_b = subparsers.add_parser('b', help='b help')
  12. >>> parser_b.add_argument('--baz', choices='XYZ', help='baz help')
  13. >>>
  14. >>> # parse some argument lists
  15. >>> parser.parse_args(['a', '12'])
  16. Namespace(bar=12, foo=False)
  17. >>> parser.parse_args(['--foo', 'b', '--baz', 'Z'])
  18. Namespace(baz='Z', foo=True)

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

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

  1. >>> parser.parse_args(['--help'])
  2. usage: PROG [-h] [--foo] {a,b} ...
  3.  
  4. positional arguments:
  5. {a,b} sub-command help
  6. a a help
  7. b b help
  8.  
  9. optional arguments:
  10. -h, --help show this help message and exit
  11. --foo foo help
  12.  
  13. >>> parser.parse_args(['a', '--help'])
  14. usage: PROG a [-h] bar
  15.  
  16. positional arguments:
  17. bar bar help
  18.  
  19. optional arguments:
  20. -h, --help show this help message and exit
  21.  
  22. >>> parser.parse_args(['b', '--help'])
  23. usage: PROG b [-h] [--baz {X,Y,Z}]
  24.  
  25. optional arguments:
  26. -h, --help show this help message and exit
  27. --baz {X,Y,Z} baz help

The add_subparsers() method also supports title and descriptionkeyword arguments. When either is present, the subparser's commands willappear in their own group in the help output. For example:

  1. >>> parser = argparse.ArgumentParser()
  2. >>> subparsers = parser.add_subparsers(title='subcommands',
  3. ... description='valid subcommands',
  4. ... help='additional help')
  5. >>> subparsers.add_parser('foo')
  6. >>> subparsers.add_parser('bar')
  7. >>> parser.parse_args(['-h'])
  8. usage: [-h] {foo,bar} ...
  9.  
  10. optional arguments:
  11. -h, --help show this help message and exit
  12.  
  13. subcommands:
  14. valid subcommands
  15.  
  16. {foo,bar} additional help

Furthermore, add_parser supports an additional aliases argument,which allows multiple strings to refer to the same subparser. This example,like svn, aliases co as a shorthand for checkout:

  1. >>> parser = argparse.ArgumentParser()
  2. >>> subparsers = parser.add_subparsers()
  3. >>> checkout = subparsers.add_parser('checkout', aliases=['co'])
  4. >>> checkout.add_argument('foo')
  5. >>> parser.parse_args(['co', 'bar'])
  6. Namespace(foo='bar')

One particularly effective way of handling sub-commands is to combine the useof the add_subparsers() method with calls to set_defaults() sothat each subparser knows which Python function it should execute. Forexample:

  1. >>> # sub-command functions
  2. >>> def foo(args):
  3. ... print(args.x * args.y)
  4. ...
  5. >>> def bar(args):
  6. ... print('((%s))' % args.z)
  7. ...
  8. >>> # create the top-level parser
  9. >>> parser = argparse.ArgumentParser()
  10. >>> subparsers = parser.add_subparsers()
  11. >>>
  12. >>> # create the parser for the "foo" command
  13. >>> parser_foo = subparsers.add_parser('foo')
  14. >>> parser_foo.add_argument('-x', type=int, default=1)
  15. >>> parser_foo.add_argument('y', type=float)
  16. >>> parser_foo.set_defaults(func=foo)
  17. >>>
  18. >>> # create the parser for the "bar" command
  19. >>> parser_bar = subparsers.add_parser('bar')
  20. >>> parser_bar.add_argument('z')
  21. >>> parser_bar.set_defaults(func=bar)
  22. >>>
  23. >>> # parse the args and call whatever function was selected
  24. >>> args = parser.parse_args('foo 1 -x 2'.split())
  25. >>> args.func(args)
  26. 2.0
  27. >>>
  28. >>> # parse the args and call whatever function was selected
  29. >>> args = parser.parse_args('bar XYZYX'.split())
  30. >>> args.func(args)
  31. ((XYZYX))

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

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

在 3.7 版更改: New required keyword argument.

FileType 对象

  • class argparse.FileType(mode='r', bufsize=-1, encoding=None, errors=None)
  • The FileType factory creates objects that can be passed to the typeargument of ArgumentParser.add_argument(). Arguments that haveFileType objects as their type will open command-line arguments asfiles with the requested modes, buffer sizes, encodings and error handling(see the open() function for more details):
  1. >>> parser = argparse.ArgumentParser()
  2. >>> parser.add_argument('--raw', type=argparse.FileType('wb', 0))
  3. >>> parser.add_argument('out', type=argparse.FileType('w', encoding='UTF-8'))
  4. >>> parser.parse_args(['--raw', 'raw.dat', 'file.txt'])
  5. Namespace(out=<_io.TextIOWrapper name='file.txt' mode='w' encoding='UTF-8'>, raw=<_io.FileIO name='raw.dat' mode='wb'>)

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

  1. >>> parser = argparse.ArgumentParser()
  2. >>> parser.add_argument('infile', type=argparse.FileType('r'))
  3. >>> parser.parse_args(['-'])
  4. Namespace(infile=<_io.TextIOWrapper name='<stdin>' encoding='UTF-8'>)

3.4 新版功能: encodingserrors 关键字参数。

参数组

  • ArgumentParser.addargument_group(_title=None, description=None)
  • By default, ArgumentParser groups command-line arguments into"positional arguments" and "optional arguments" when displaying helpmessages. When there is a better conceptual grouping of arguments than thisdefault one, appropriate groups can be created using theadd_argument_group() method:
  1. >>> parser = argparse.ArgumentParser(prog='PROG', add_help=False)
  2. >>> group = parser.add_argument_group('group')
  3. >>> group.add_argument('--foo', help='foo help')
  4. >>> group.add_argument('bar', help='bar help')
  5. >>> parser.print_help()
  6. usage: PROG [--foo FOO] bar
  7.  
  8. group:
  9. bar bar help
  10. --foo FOO foo help

The add_argument_group() method returns an argument group object whichhas an add_argument() method just like a regularArgumentParser. When an argument is added to the group, the parsertreats it just like a normal argument, but displays the argument in aseparate group for help messages. The add_argument_group() methodaccepts title and description arguments which can be used tocustomize this display:

  1. >>> parser = argparse.ArgumentParser(prog='PROG', add_help=False)
  2. >>> group1 = parser.add_argument_group('group1', 'group1 description')
  3. >>> group1.add_argument('foo', help='foo help')
  4. >>> group2 = parser.add_argument_group('group2', 'group2 description')
  5. >>> group2.add_argument('--bar', help='bar help')
  6. >>> parser.print_help()
  7. usage: PROG [--bar BAR] foo
  8.  
  9. group1:
  10. group1 description
  11.  
  12. foo foo help
  13.  
  14. group2:
  15. group2 description
  16.  
  17. --bar BAR bar help

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

Mutual exclusion

  • ArgumentParser.addmutually_exclusive_group(_required=False)
  • 创建一个互斥组。 argparse 将会确保互斥组中只有一个参数在命令行中可用:
  1. >>> parser = argparse.ArgumentParser(prog='PROG')
  2. >>> group = parser.add_mutually_exclusive_group()
  3. >>> group.add_argument('--foo', action='store_true')
  4. >>> group.add_argument('--bar', action='store_false')
  5. >>> parser.parse_args(['--foo'])
  6. Namespace(bar=True, foo=True)
  7. >>> parser.parse_args(['--bar'])
  8. Namespace(bar=False, foo=False)
  9. >>> parser.parse_args(['--foo', '--bar'])
  10. usage: PROG [-h] [--foo | --bar]
  11. PROG: error: argument --bar: not allowed with argument --foo

add_mutually_exclusive_group() 方法也接受一个 required 参数,表示在互斥组中至少有一个参数是需要的:

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

注意,目前互斥参数组不支持 add_argument_group()titledescription 参数。

Parser defaults

  • ArgumentParser.setdefaults(**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 argumentactions. set_defaults() allows some additionalattributes that are determined without any inspection of the command line tobe added:
  1. >>> parser = argparse.ArgumentParser()
  2. >>> parser.add_argument('foo', type=int)
  3. >>> parser.set_defaults(bar=42, baz='badger')
  4. >>> parser.parse_args(['736'])
  5. Namespace(bar=42, baz='badger', foo=736)

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

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

Parser-level defaults can be particularly useful when working with multipleparsers. See the add_subparsers() method for anexample of this type.

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

打印帮助

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

  • ArgumentParser.printusage(_file=None)
  • Print a brief description of how the ArgumentParser should beinvoked on the command line. If file is None, sys.stdout isassumed.
  • ArgumentParser.printhelp(_file=None)
  • Print a help message, including the program usage and information about thearguments registered with the ArgumentParser. If file isNone, sys.stdout is assumed.

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

  • ArgumentParser.format_usage()
  • Return a string containing a brief description of how theArgumentParser should be invoked on the command line.
  • ArgumentParser.format_help()
  • Return a string containing a help message, including the program usage andinformation about the arguments registered with the ArgumentParser.

Partial parsing

  • ArgumentParser.parseknown_args(_args=None, namespace=None)

Sometimes a script may only parse a few of the command-line arguments, passingthe remaining arguments on to another script or program. In these cases, theparse_known_args() method can be useful. It works much likeparse_args() except that it does not produce an error whenextra arguments are present. Instead, it returns a two item tuple containingthe populated namespace and the list of remaining argument strings.

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

警告

Prefix matching rules apply toparse_known_args(). The parser may consume an option even if it's justa prefix of one of its known options, instead of leaving it in the remainingarguments list.

自定义文件解析

  • ArgumentParser.convertarg_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 oneargument per line. convert_arg_line_to_args() can be overridden forfancier reading.

This method takes a single argument arg_line which is a string read fromthe 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 wordas an argument. The following example demonstrates how to do this:

  1. class MyArgumentParser(argparse.ArgumentParser):
  2. def convert_arg_line_to_args(self, arg_line):
  3. return arg_line.split()

退出方法

  • 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 thestandard error and terminates the program with a status code of 2.

Intermixed parsing

  • ArgumentParser.parseintermixed_args(_args=None, namespace=None)
  • ArgumentParser.parseknown_intermixed_args(_args=None, namespace=None)

A number of Unix commands allow the user to intermix optional arguments withpositional arguments. The parse_intermixed_args()and parse_known_intermixed_args() methodssupport this parsing style.

These parsers do not support all the argparse features, and will raiseexceptions if unsupported features are used. In particular, subparsers,argparse.REMAINDER, and mutually exclusive groups that include bothoptionals and positionals are not supported.

The following example shows the difference betweenparse_known_args() andparse_intermixed_args(): the former returns ['2','3'] as unparsed arguments, while the latter collects all the positionalsinto rest.

  1. >>> parser = argparse.ArgumentParser()
  2. >>> parser.add_argument('--foo')
  3. >>> parser.add_argument('cmd')
  4. >>> parser.add_argument('rest', nargs='*', type=int)
  5. >>> parser.parse_known_args('doit 1 --foo bar 2 3'.split())
  6. (Namespace(cmd='doit', foo='bar', rest=[1]), ['2', '3'])
  7. >>> parser.parse_intermixed_args('doit 1 --foo bar 2 3'.split())
  8. Namespace(cmd='doit', foo='bar', rest=[1, 2, 3])

parse_known_intermixed_args() returns a two item tuplecontaining the populated namespace and the list of remaining argument strings.parse_intermixed_args() raises an error if there are anyremaining unparsed argument strings.

3.7 新版功能.

升级 optparse 代码

Originally, the argparse module had attempted to maintain compatibilitywith optparse. However, optparse was difficult to extendtransparently, particularly with the changes required to support the newnargs= specifiers and better usage messages. When most everything inoptparse had either been copy-pasted over or monkey-patched, it nolonger seemed practical to try to maintain the backwards compatibility.

The argparse module improves on the standard library optparsemodule in a number of ways including:

  • 处理位置参数。

  • 支持子命令。

  • Allowing alternative option prefixes like + and /.

  • Handling zero-or-more and one-or-more style arguments.

  • Producing more informative usage messages.

  • Providing a much simpler interface for custom type and action.

A partial upgrade path from optparse to argparse:

  • Replace all optparse.OptionParser.add_option() calls withArgumentParser.add_argument() calls.

  • Replace (options, args) = parser.parse_args() with args =parser.parse_args() and add additional ArgumentParser.add_argument()calls for the positional arguments. Keep in mind that what was previouslycalled options, now in the argparse context is called args.

  • Replace optparse.OptionParser.disable_interspersed_args()by using parse_intermixed_args() instead ofparse_args().

  • Replace callback actions and the callback_* keyword arguments withtype or action arguments.

  • Replace string names for type keyword arguments with the correspondingtype objects (e.g. int, float, complex, etc).

  • Replace optparse.Values with Namespace andoptparse.OptionError and optparse.OptionValueError withArgumentError.

  • Replace strings with implicit arguments such as %default or %prog withthe standard Python syntax to use dictionaries to format strings, that is,%(default)s and %(prog)s.

  • Replace the OptionParser constructor version argument with a call toparser.add_argument('—version', action='version', version='<the version>').