argparseParser for command-line options, arguments and sub-commands用于命令行选项、参数和子命令的解析器

New in version 3.2.版本3.2中新增。

Source code: Lib/argparse.py


The argparse module makes it easy to write user-friendly command-line interfaces. argparse模块使编写用户友好的命令行界面变得容易。The program defines what arguments it requires, and argparse will figure out how to parse those out of sys.argv. 程序定义了它需要的参数,argparse将找出如何从sys.argv中解析这些参数。The argparse module also automatically generates help and usage messages and issues errors when users give the program invalid arguments.argparse模块还自动生成帮助和用法消息,并在用户给程序提供无效参数时发出错误。

Example示例

The following code is a Python program that takes a list of integers and produces either the sum or the max:下面的代码是一个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的文件中,它可以在命令行上运行,并提供有用的帮助消息:

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

positional arguments:
N an integer for the accumulator

options:
-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.以下部分将引导您完成此示例。

Creating a parser创建解析器

The first step in using the argparse is creating an ArgumentParser object:使用argparse的第一步是创建ArgumentParser对象:

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

The ArgumentParser object will hold all the information necessary to parse the command line into Python data types.ArgumentParser对象将保存将命令行解析为Python数据类型所需的所有信息。

Adding arguments添加参数

Filling an ArgumentParser with information about program arguments is done by making calls to the add_argument() method. 通过调用add_argument()方法,向ArgumentParser填充有关程序参数的信息。Generally, these calls tell the ArgumentParser how to take the strings on the command line and turn them into objects. 通常,这些调用告诉ArgumentParser如何在命令行上获取字符串并将其转换为对象。This information is stored and used when parse_args() is called. 此信息在调用parse_args()时存储和使用。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)')

Later, calling parse_args() will return an object with two attributes, integers and accumulate. 稍后,调用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.integers属性将是一个或多个整数的列表,如果在命令行中指定了--sum,则accumulate属性将是sum()函数,如果不是,则是max()函数。

Parsing arguments解析参数

ArgumentParser parses arguments through the parse_args() method. 通过parse_args()方法解析参数。This will inspect the command line, convert each argument to the appropriate type and then invoke the appropriate action. 这将检查命令行,将每个参数转换为适当的类型,然后调用适当的操作。In most cases, this means a simple Namespace object will be built up from attributes parsed out of the command line:在大多数情况下,这意味着将从命令行解析的属性构建一个简单的Namespace对象:

>>> 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.在脚本中,parse_args()通常不带参数调用,ArgumentParser将自动从sys.argv确定命令行参数。

ArgumentParser objects对象

classargparse.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, exit_on_error=True)

Create a new ArgumentParser object. 创建新的ArgumentParser对象。All parameters should be passed as keyword arguments. 所有参数都应作为关键字参数传递。Each parameter has its own more detailed description below, but in short they are:以下每个参数都有其更详细的描述,但简而言之,它们是:

  • prog - The name of the program (default: os.path.basename(sys.argv[0]))程序的名称(默认值:os.path.basename(sys.argv[0])

  • usage - The string describing the program usage (default: generated from arguments added to parser)描述程序用法的字符串(默认值:从添加到解析器的参数生成)

  • description - Text to display before the argument help (default: none)要在参数帮助之前显示的文本(默认值:None

  • epilog - Text to display after the argument help (default: none)参数帮助后显示的文本(默认值:None

  • parents - A list of ArgumentParser objects whose arguments should also be included还应包括其参数的ArgumentParser对象列表

  • formatter_class - A class for customizing the help output用于自定义帮助输出的类

  • prefix_chars - The set of characters that prefix optional arguments (default: ‘-‘)作为可选参数前缀的字符集(默认值:'-'

  • fromfile_prefix_chars - The set of characters that prefix files from which additional arguments should be read (default: None)作为文件前缀的字符集,应从中读取其他参数(默认值:None

  • argument_default - The global default value for arguments (default: None)参数的全局默认值(默认值:None

  • conflict_handler - The strategy for resolving conflicting optionals (usually unnecessary)解决冲突选项的策略(通常不必要)

  • add_help - Add a -h/--help option to the parser (default: True)向解析器添加-h/--help选项(默认值:True

  • allow_abbrev - Allows long options to be abbreviated if the abbreviation is unambiguous. 如果缩写不明确,则允许缩写长选项。(default: True)(默认值:True

  • exit_on_error - Determines whether or not ArgumentParser exits with error info when an error occurs. (default: True)确定发生错误时ArgumentParser是否带错误信息退出。(默认值:True

Changed in version 3.5:版本3.5中更改: allow_abbrev parameter was added.添加了allow_abbrev参数。

Changed in version 3.8:版本3.8中更改: In previous versions, allow_abbrev also disabled grouping of short flags such as -vv to mean -v -v.在以前的版本中,allow_abbrev还禁用了短标志的分组,例如-vv表示-v -v

Changed in version 3.9:版本3.9中更改: exit_on_error parameter was added.添加了exit_on_error参数。

The following sections describe how each of these are used.以下各节描述了如何使用这些方法。

prog

By default, ArgumentParser objects use sys.argv[0] to determine how to display the name of the program in help messages. 默认情况下,ArgumentParser对象使用sys.argv[0]来确定如何在帮助消息中显示程序名称。This default is almost always desirable because it will make the help messages match how the program was invoked on the command line. 此默认值几乎总是可取的,因为它将使帮助消息与在命令行上调用程序的方式相匹配。For example, consider a file named myprogram.py with the following code:例如,考虑一个名为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):此程序的帮助将显示myprogram.py作为程序名(无论从何处调用该程序):

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

options:
-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:要更改此默认行为,可以使用prog=参数向ArgumentParser提供另一个值:

>>> parser = argparse.ArgumentParser(prog='myprogram')
>>> parser.print_help()
usage: myprogram [-h]
options:
-h, --help show this help message and exit

Note that the program name, whether determined from sys.argv[0] or from the prog= argument, is available to help messages using the %(prog)s format specifier.请注意,无论是从sys.argv[0]还是从prog=参数确定的程序名,都可用于使用%(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]
options:
-h, --help show this help message and exit
--foo FOO foo of the myprogram program

usage用法

By default, ArgumentParser calculates the usage message from the arguments it contains:默认情况下,ArgumentParser根据其包含的参数计算用法消息:

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

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

The default message can be overridden with the usage= keyword argument:可以使用usage=关键字参数覆盖默认消息:

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

options:
-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.%(prog)s格式说明符可用于在使用消息中填写程序名。

description描述

Most calls to the ArgumentParser constructor will use the description= keyword argument. ArgumentParser构造函数的大多数调用将使用description=关键字参数。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

options:
-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.要更改此行为,请参阅formatter_class参数。

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:可以使用ArgumentParserepilog=参数指定此类文本:

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

options:
-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.description参数一样,epilog=文本在默认情况下是换行的,但可以使用ArgumentParserformatter_class参数调整此行为。

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的单个解析器。The parents= argument takes a list of ArgumentParser objects, collects all the positional and optional actions from them, and adds these actions to the ArgumentParser object being constructed: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)

Note that most parent parsers will specify add_help=False. 请注意,大多数父解析器将指定add_help=FalseOtherwise, the ArgumentParser will see two -h/--help options (one in the parent and one in the child) and raise an error.否则,ArgumentParser将看到两个-h/--help选项(一个在父级,一个在子级),并引发错误。

Note

You must fully initialize the parsers before passing them via parents=. 在通过parents=,传递解析器之前,必须完全初始化解析器。If you change the parent parsers after the child parser, those changes will not be reflected in the child.如果在子解析器之后更改父解析器,这些更改将不会反映在子解析器中。

formatter_class

ArgumentParser objects allow the help formatting to be customized by specifying an alternate formatting class. 对象允许通过指定替代格式类来自定义帮助格式。Currently, there are four such classes:目前,有四个此类课程:

classargparse.RawDescriptionHelpFormatter
classargparse.RawTextHelpFormatter
classargparse.ArgumentDefaultsHelpFormatter
classargparse.MetavarTypeHelpFormatter

RawDescriptionHelpFormatter and RawTextHelpFormatter give more control over how textual descriptions are displayed. 对文本描述的显示方式提供更多控制。By default, ArgumentParser objects line-wrap the description and epilog texts in command-line help messages:默认情况下,ArgumentParser对象将命令行帮助消息中的描述结束语文本换行:

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

options:
-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:RawDescriptionHelpFormatter作为formatter_class=传递表示描述结束语已正确格式化,不应换行:

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

options:
-h, --help show this help message and exit

RawTextHelpFormatter maintains whitespace for all sorts of help text, including argument descriptions. 为各种帮助文本(包括参数描述)保留空白。However, multiple new lines are replaced with one. 但是,多个新行将被一个替换。If you wish to preserve multiple blank lines, add spaces between the newlines.如果要保留多个空行,请在换行之间添加空格。

ArgumentDefaultsHelpFormatter automatically adds information about default values to each of the argument help messages:自动将有关默认值的信息添加到每个参数帮助消息中:

>>> 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 ...]
positional arguments:
bar BAR! (default: [1, 2, 3])

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

MetavarTypeHelpFormatter uses the name of the type argument for each argument as the display name for its values (rather than using the dest as the regular formatter does):使用每个参数的类型参数的名称作为其值的显示名称(而不是像常规格式化程序那样使用dest):

>>> parser = argparse.ArgumentParser(
... prog='PROG',
... formatter_class=argparse.MetavarTypeHelpFormatter)
>>> parser.add_argument('--foo', type=int)
>>> parser.add_argument('bar', type=float)
>>> parser.print_help()
usage: PROG [-h] [--foo int] float
positional arguments:
float

options:
-h, --help show this help message and exit
--foo int

prefix_chars

Most command-line options will use - as the prefix, e.g. -f/--foo. 大多数命令行选项将使用-作为前缀,例如-f/--fooParsers 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:需要支持不同或附加前缀字符的解析器,例如对于+f/foo等选项,可以使用ArgumentParser构造函数的prefix_chars=参数指定它们:

>>> 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 '-'. prefix_chars=参数默认为'-'Supplying a set of characters that does not include - will cause -f/--foo options to be disallowed.提供不包含-的字符集将导致不允许使用-f/--foo选项。

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. 如果将fromfile_prefix_chars=参数提供给ArgumentParser构造函数,则以任何指定字符开头的参数将被视为文件,并将被它们包含的参数替换。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. 默认情况下,从文件读取的参数必须是每行一个(但请参见convert_arg_line_to_args()),并将其视为与命令行上的原始文件引用参数位于同一位置。So in the example above, the expression ['-f', 'foo', '@args.txt'] is considered equivalent to the expression ['-f', 'foo', '-f', 'bar'].因此,在上面的示例中,表达式['-f', 'foo', '@args.txt']被认为等同于表达式['-f', 'foo', '-f', 'bar']

The fromfile_prefix_chars= argument defaults to None, meaning that arguments will never be treated as file references.fromfile_prefix_chars=参数默认为None,这意味着参数永远不会被视为文件引用。

argument_default

Generally, argument defaults are specified either by passing a default to add_argument() or by calling the set_defaults() methods with a specific set of name-value pairs. 通常,参数默认值是通过将默认值传递给add_argument()或通过使用一组特定的名称-值对调用set_defaults()方法来指定的。Sometimes however, it may be useful to specify a single parser-wide default for arguments. 然而,有时,为参数指定单个解析器范围的默认值可能很有用。This can be accomplished by passing the argument_default= keyword argument to ArgumentParser. 这可以通过将argument_default=关键字参数传递给ArgumentParser来实现。For example, to globally suppress attribute creation on parse_args() calls, we supply argument_default=SUPPRESS:例如,为了全局抑制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()

allow_abbrev

Normally, when you pass an argument list to the parse_args() method of an ArgumentParser, it recognizes abbreviations of long options.通常,当您将参数列表传递给ArgumentParserparse_args()方法时,它会识别长选项的缩写

This feature can be disabled by setting allow_abbrev to False:通过将allow_abbrev设置为False,可以禁用此功能:

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

New in version 3.5.版本3.5中新增。

conflict_handler

ArgumentParser objects do not allow two actions with the same option string. 对象不允许具有相同选项字符串的两个操作。By default, ArgumentParser objects raise an exception if an attempt is made to create an argument with an option string that is already in use:默认情况下,如果尝试使用已使用的选项字符串创建参数,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

Sometimes (e.g. when using parents) it may be useful to simply override any older arguments with the same option string. 有时(例如,当使用父项时),简单地用相同的选项字符串覆盖任何旧参数可能很有用。To get this behavior, the value 'resolve' can be supplied to the conflict_handler= argument of ArgumentParser:要获得此行为,可以将值'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]
options:
-h, --help show this help message and exit
-f FOO old foo help
--foo FOO new foo help

Note that ArgumentParser objects only remove an action if all of its option strings are overridden. 请注意,ArgumentParser对象仅在其所有选项字符串被重写时才会删除操作。So, in the example above, the old -f/--foo action is retained as the -f action, because only the --foo option string was overridden.因此,在上面的示例中,旧的-f/--foo操作保留为-f操作,因为只有--foo选项字符串被重写。

add_help

By default, ArgumentParser objects add an option which simply displays the parser’s help message. 默认情况下,ArgumentParser对象添加一个选项,该选项仅显示解析器的帮助消息。For example, consider a file named myprogram.py containing the following code:例如,考虑一个名为myprogram.py的文件,其中包含以下代码:

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

If -h or --help is supplied at the command line, the ArgumentParser help will be printed:如果在命令行中提供了-h--help,则将打印ArgumentParser帮助:

$ python myprogram.py --help
usage: myprogram.py [-h] [--foo FOO]
options:
-h, --help show this help message and exit
--foo FOO foo help

Occasionally, it may be useful to disable the addition of this help option. 有时,禁用添加此帮助选项可能很有用。This can be achieved by passing False as the add_help= argument to ArgumentParser:这可以通过将False作为add_help=参数传递给ArgumentParser来实现:

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

The help option is typically -h/--help. 帮助选项通常是-h/--helpThe exception to this is if the prefix_chars= is specified and does not include -, in which case -h and --help are not valid options. 例外情况是,如果指定了prefix_chars=并且不包括-,则-h-help不是有效选项。In this case, the first character in prefix_chars is used to prefix the help options:在这种情况下,prefix_chars中的第一个字符用于作为帮助选项的前缀:

>>> parser = argparse.ArgumentParser(prog='PROG', prefix_chars='+/')
>>> parser.print_help()
usage: PROG [+h]
options:
+h, ++help show this help message and exit

exit_on_error

Normally, when you pass an invalid argument list to the parse_args() method of an ArgumentParser, it will exit with error info.通常,当您将无效参数列表传递给ArgumentParserparse_args()方法时,它将以错误信息退出。

If the user would like to catch errors manually, the feature can be enabled by setting exit_on_error to False:如果用户希望手动捕获错误,可以通过将exit_on_error设置为False来启用该功能:

>>> parser = argparse.ArgumentParser(exit_on_error=False)
>>> parser.add_argument('--integers', type=int)
_StoreAction(option_strings=['--integers'], dest='integers', nargs=None, const=None, default=None, type=<class 'int'>, choices=None, help=None, metavar=None)
>>> try:
... parser.parse_args('--integers a'.split())
... except argparse.ArgumentError:
... print('Catching an argumentError')
...
Catching an argumentError

New in version 3.9.版本3.9中新增。

The add_argument() methodadd_argument()方法

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

Define how a single command-line argument should be parsed. 定义应如何解析单个命令行参数。Each parameter has its own more detailed description below, but in short they are:以下每个参数都有其更详细的描述,但简而言之,它们是:

  • name or flags - Either a name or a list of option strings, e.g. foo or -f, --foo.名称或选项字符串列表,例如foo-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.某些操作nargs选区所需的恒定值。

  • default - The value produced if the argument is absent from the command line and if it is absent from the namespace object.如果命令行中不存在参数,且命名空间对象中不存在该参数,则生成的值。

  • 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().parse_args()返回的要添加到对象的属性的名称。

The following sections describe how each of these are used.以下各节描述了如何使用这些方法。

name or flags

The add_argument() method must know whether an optional argument, like -f or --foo, or a positional argument, like a list of filenames, is expected. add_argument()方法必须知道是否需要可选参数(如-f--foo)或位置参数(如文件名列表)。The first arguments passed to add_argument() must therefore be either a series of flags, or a simple argument name. 因此,传递给add_argument()的第一个参数必须是一系列标志或简单的参数名。For example, an optional argument could be created like:例如,可以创建如下可选参数:

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

while a positional argument could be created like:而位置参数可以创建为:

>>> parser.add_argument('bar')

When parse_args() is called, optional arguments will be identified by the - prefix, and the remaining arguments will be assumed to be positional:调用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: the following arguments are required: bar

action

ArgumentParser objects associate command-line arguments with actions. 对象将命令行参数与操作相关联。These actions can do just about anything with the command-line arguments associated with them, though most actions simply add an attribute to the object returned by parse_args(). 这些操作几乎可以使用与它们关联的命令行参数执行任何操作,尽管大多数操作只是向parse_args()返回的对象添加一个属性。The action keyword argument specifies how the command-line arguments should be handled. action关键字参数指定应如何处理命令行参数。The supplied actions are:提供的操作包括:

  • 'store' - This just stores the argument’s value. 这只是存储参数的值。This is the default action. 这是默认操作。For example:例如:

    >>> parser = argparse.ArgumentParser()
    >>> parser.add_argument('--foo')
    >>> parser.parse_args('--foo 1'.split())
    Namespace(foo='1')
  • 'store_const' - This stores the value specified by the const keyword argument. 它存储由const关键字参数指定的值。The 'store_const' action is most commonly used with optional arguments that specify some sort of flag. 'store_const'操作最常用于指定某种标志的可选参数。For example:例如:

    >>> parser = argparse.ArgumentParser()
    >>> parser.add_argument('--foo', action='store_const', const=42)
    >>> parser.parse_args(['--foo'])
    Namespace(foo=42)
  • 'store_true' and 'store_false' - These are special cases of 'store_const' used for storing the values True and False respectively. I这些是分别用于存储值TrueFalse'store_const'的特殊情况。In addition, they create default values of False and True respectively. 此外,它们分别创建默认值FalseTrueFor example:例如:

    >>> 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(foo=True, bar=False, baz=True)
  • 'append' - This stores a list, and appends each argument value to the list. 这将存储一个列表,并将每个参数值附加到列表中。This is useful to allow an option to be specified multiple times. 这对于允许多次指定选项非常有用。Example usage:示例用法:

    >>> parser = argparse.ArgumentParser()
    >>> parser.add_argument('--foo', action='append')
    >>> parser.parse_args('--foo 1 --foo 2'.split())
    Namespace(foo=['1', '2'])
  • 'append_const' - This stores a list, and appends the value specified by the const keyword argument to the list. (Note that the const keyword argument defaults to None.) 这将存储一个列表,并将const关键字参数指定的值附加到列表中。(请注意,const关键字参数默认为None。)The 'append_const' action is typically useful when multiple arguments need to store constants to the same list. 当多个参数需要将常量存储到同一列表中时,'append_const'操作通常很有用。For example:例如:

    >>> 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=[<class 'str'>, <class 'int'>])
  • 'count' - This counts the number of times a keyword argument occurs. 这统计关键字参数出现的次数。For example, this is useful for increasing verbosity levels:例如,这有助于提高详细程度:

    >>> parser = argparse.ArgumentParser()
    >>> parser.add_argument('--verbose', '-v', action='count', default=0)
    >>> parser.parse_args(['-vvv'])
    Namespace(verbose=3)

    Note, the default will be None unless explicitly set to 0.注意,除非显式设置为0,否则default将为None

  • 'help' - This prints a complete help message for all the options in the current parser and then exits. 这将打印当前解析器中所有选项的完整帮助消息,然后退出。By default a help action is automatically added to the parser. 默认情况下,帮助操作会自动添加到解析器中。See ArgumentParser for details of how the output is created.有关如何创建输出的详细信息,请参阅ArgumentParser

  • 'version' - This expects a version= keyword argument in the add_argument() call, and prints version information and exits when invoked:这在add_argument()调用中需要一个version=关键字参数,并打印版本信息并在调用时退出:

    >>> 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
  • 'extend' - This stores a list, and extends each argument value to the list. 这将存储一个列表,并将每个参数值扩展到该列表。Example usage:示例用法:

    >>> parser = argparse.ArgumentParser()
    >>> parser.add_argument("--foo", action="extend", nargs="+", type=str)
    >>> parser.parse_args(["--foo", "f1", "--foo", "f2", "f3", "f4"])
    Namespace(foo=['f1', 'f2', 'f3', 'f4'])

    New in version 3.8.版本3.8中新增。

You may also specify an arbitrary action by passing an Action subclass or other object that implements the same interface. 您还可以通过传递实现相同接口的动作子类或其他对象来指定任意动作。The BooleanOptionalAction is available in argparse and adds support for boolean actions such as --foo and --no-foo:BooleanOptionalActionargparse中可用,并添加了对布尔操作的支持,如--foo--no-foo

>>> import argparse
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo', action=argparse.BooleanOptionalAction)
>>> parser.parse_args(['--no-foo'])
Namespace(foo=False)

New in version 3.9.版本3.9中新增。

The recommended way to create a custom action is to extend Action, overriding the __call__ method and optionally the __init__ and format_usage methods.创建自定义操作的推荐方法是扩展Action,重写__call__方法,并可选地重写__init__format_usage方法。

An example of a custom action:自定义操作的示例:

>>> class FooAction(argparse.Action):
... def __init__(self, option_strings, dest, nargs=None, **kwargs):
... if nargs is not None:
... raise ValueError("nargs not allowed")
... super().__init__(option_strings, dest, **kwargs)
... 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')

For more details, see Action.有关详细信息,请参阅Action

nargs

ArgumentParser objects usually associate a single command-line argument with a single action to be taken. ArgumentParser对象通常将单个命令行参数与要执行的单个操作相关联。The nargs keyword argument associates a different number of command-line arguments with a single action. nargs关键字参数将不同数量的命令行参数与单个操作相关联。The supported values are:支持的值为:

  • N (an integer). (整数)。N arguments from the command line will be gathered together into a list. 命令行中的参数将被收集到一个列表中。For example:例如:

    >>> 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'])

    Note that nargs=1 produces a list of one item. 注意,nargs=1生成一个项目列表。This is different from the default, in which the item is produced by itself.这与默认情况不同,在默认情况下,项目由其自身生成。

  • '?'. One argument will be consumed from the command line if possible, and produced as a single item. 。如果可能,将从命令行使用一个参数,并将其作为单个项生成。If no command-line argument is present, the value from default will be produced. 如果不存在命令行参数,将生成默认值Note that for optional arguments, there is an additional case - the option string is present but not followed by a command-line argument. 请注意,对于可选参数,还有一种情况-选项字符串存在,但后面没有命令行参数。In this case the value from const will be produced. 在这种情况下,将生成const的值。Some examples to illustrate this:举例说明:

    >>> 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'])
    Namespace(bar='XX', foo='YY')
    >>> parser.parse_args(['XX', '--foo'])
    Namespace(bar='XX', foo='c')
    >>> parser.parse_args([])
    Namespace(bar='d', foo='d')

    One of the more common uses of nargs='?' is to allow optional input and output files:nargs更常见的用法之一是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=<_io.TextIOWrapper name='input.txt' encoding='UTF-8'>,
    outfile=<_io.TextIOWrapper name='output.txt' encoding='UTF-8'>)
    >>> parser.parse_args([])
    Namespace(infile=<_io.TextIOWrapper name='<stdin>' encoding='UTF-8'>,
    outfile=<_io.TextIOWrapper name='<stdout>' encoding='UTF-8'>)
  • '*'. All command-line arguments present are gathered into a list. 。所有存在的命令行参数都收集到一个列表中。Note that it generally doesn’t make much sense to have more than one positional argument with nargs='*', but multiple optional arguments with nargs='*' is possible. 请注意,通常使用多个nargs='*'的位置参数没有多大意义,但可以使用多个可选参数nargs='*'For example:或示例:

    >>> 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'])
  • '+'. Just like '*', all command-line args present are gathered into a list. 。与'*'一样,所有存在的命令行参数都被收集到一个列表中。Additionally, an error message will be generated if there wasn’t at least one command-line argument present. 此外,如果不存在至少一个命令行参数,将生成错误消息。For example:例如:

    >>> parser = argparse.ArgumentParser(prog='PROG')
    >>> parser.add_argument('foo', nargs='+')
    >>> parser.parse_args(['a', 'b'])
    Namespace(foo=['a', 'b'])
    >>> parser.parse_args([])
    usage: PROG [-h] foo [foo ...]
    PROG: error: the following arguments are required: foo

If the nargs keyword argument is not provided, the number of arguments consumed is determined by the action. 如果未提供nargs关键字参数,则使用的参数数量由操作确定。Generally this means a single command-line argument will be consumed and a single item (not a list) will be produced.通常,这意味着将使用单个命令行参数,并生成单个项(而不是列表)。

const

The const argument of add_argument() is used to hold constant values that are not read from the command line but are required for the various ArgumentParser actions. The two most common uses of it are:add_argument()const参数用于保存常量值,这些常量值不是从命令行读取的,而是各种ArgumentParser操作所必需的。它的两个最常见的用途是:

  • When add_argument() is called with action='store_const' or action='append_const'. 当使用action='store_const'action='append_const'调用add_argument()时。These actions add the const value to one of the attributes of the object returned by parse_args(). 这些操作将const值添加到parse_args()返回的对象的一个属性中。See the action description for examples.有关示例,请参阅操作说明。

  • When add_argument() is called with option strings (like -f or --foo) and nargs='?'. 当使用选项字符串(如-f--foo)和nargs='?'调用add_argument()时。This creates an optional argument that can be followed by zero or one command-line arguments. 这将创建一个可选参数,后面可以跟零个或一个命令行参数。When parsing the command line, if the option string is encountered with no command-line argument following it, the value of const will be assumed instead. 在分析命令行时,如果遇到选项字符串后面没有命令行参数,则将假定const的值。See the nargs description for examples.有关示例,请参阅nargs说明。

With the 'store_const' and 'append_const' actions, the const keyword argument must be given. 对于'store_const''append_const'操作,必须给出const关键字参数。For other actions, it defaults to None.对于其他操作,默认为None

default

All optional arguments and some positional arguments may be omitted at the command line. 命令行中可以省略所有可选参数和一些位置参数。The default keyword argument of add_argument(), whose value defaults to None, specifies what value should be used if the command-line argument is not present. add_argument()的默认关键字参数(其值默认为None)指定如果不存在命令行参数,应使用什么值。For optional arguments, the default value is used when the option string was not present at the command line:对于可选参数,当命令行中不存在选项字符串时,使用default

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

If the target namespace already has an attribute set, the action default will not over write it:如果目标命名空间已经设置了属性,则操作default不会覆盖它:

>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo', default=42)
>>> parser.parse_args([], namespace=argparse.Namespace(foo=101))
Namespace(foo=101)

If the default value is a string, the parser parses the value as if it were a command-line argument. 如果default是字符串,解析器将解析该值,就像解析命令行参数一样。In particular, the parser applies any type conversion argument, if provided, before setting the attribute on the Namespace return value. 特别是,解析器在设置Namespace返回值的属性之前应用任何类型转换参数(如果提供)。Otherwise, the parser uses the value as is:否则,解析器按原样使用值:

>>> 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)

For positional arguments with nargs equal to ? or *, the default value is used when no command-line argument was present:对于nargs等于的位置参数?*,当不存在命令行参数时使用default

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

Providing default=argparse.SUPPRESS causes no attribute to be added if the command-line argument was not present:如果不存在命令行参数,则提供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')

type

By default, the parser reads command-line arguments in as simple strings. 默认情况下,解析器以简单字符串的形式读取命令行参数。However, quite often the command-line string should instead be interpreted as another type, such as a float or int. 然而,命令行字符串通常应该被解释为另一种类型,例如floatintThe type keyword for add_argument() allows any necessary type-checking and type conversions to be performed.add_argument()type关键字允许执行任何必要的类型检查和类型转换。

If the type keyword is used with the default keyword, the type converter is only applied if the default is a string.如果type关键字与default关键字一起使用,则类型转换器仅在默认值为字符串时应用。

The argument to type can be any callable that accepts a single string. type的参数可以是任何接受单个字符串的可调用参数。If the function raises ArgumentTypeError, TypeError, or ValueError, the exception is caught and a nicely formatted error message is displayed. 如果函数引发ArgumentTypeErrorTypeErrorValueError,则捕获异常并显示格式良好的错误消息。No other exception types are handled.不处理其他异常类型。

Common built-in types and functions can be used as type converters:常见的内置类型和函数可用作类型转换器:

import argparse
import pathlib
parser = argparse.ArgumentParser()
parser.add_argument('count', type=int)
parser.add_argument('distance', type=float)
parser.add_argument('street', type=ascii)
parser.add_argument('code_point', type=ord)
parser.add_argument('source_file', type=open)
parser.add_argument('dest_file', type=argparse.FileType('w', encoding='latin-1'))
parser.add_argument('datapath', type=pathlib.Path)

User defined functions can be used as well:也可以使用用户定义的函数:

>>> def hyphenated(string):
... return '-'.join([word[:4] for word in string.casefold().split()])
...
>>> parser = argparse.ArgumentParser()
>>> _ = parser.add_argument('short_title', type=hyphenated)
>>> parser.parse_args(['"The Tale of Two Cities"'])
Namespace(short_title='"the-tale-of-two-citi')

The bool() function is not recommended as a type converter. 不建议将bool()函数用作类型转换器。All it does is convert empty strings to False and non-empty strings to True. 它所做的只是将空字符串转换为False,将非空字符串转换成TrueThis is usually not what is desired.这通常不是所期望的。

In general, the type keyword is a convenience that should only be used for simple conversions that can only raise one of the three supported exceptions. 一般来说,type关键字是一种方便,只能用于只能引发三种支持的异常之一的简单转换。Anything with more interesting error-handling or resource management should be done downstream after the arguments are parsed.任何更有趣的错误处理或资源管理都应该在解析参数后在下游完成。

For example, JSON or YAML conversions have complex error cases that require better reporting than can be given by the type keyword. 例如,JSON或YAML转换具有复杂的错误情况,需要比type关键字更好的报告。A JSONDecodeError would not be well formatted and a FileNotFound exception would not be handled at all.JSONDecodeError格式不正确,并且根本不会处理FileNotFound异常。

Even FileType has its limitations for use with the type keyword. 即使FileType也有其与type关键字一起使用的限制。If one argument uses FileType and then a subsequent argument fails, an error is reported but the file is not automatically closed. 如果一个参数使用FileType,随后的一个参数失败,则会报告错误,但文件不会自动关闭。In this case, it would be better to wait until after the parser has run and then use the with-statement to manage the files.在这种情况下,最好等到解析器运行后再使用with语句来管理文件。

For type checkers that simply check against a fixed set of values, consider using the choices keyword instead.对于只检查固定值集的类型检查器,请考虑改用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 keyword argument to add_argument(). 可以通过将容器对象作为choices关键字参数传递给add_argument()来处理这些问题。When the command line is parsed, argument values will be checked, and an error message will be displayed if the argument was not one of the acceptable values:分析命令行时,将检查参数值,如果参数不是可接受的值之一,将显示错误消息:

>>> 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')

Note that inclusion in the choices container is checked after any type conversions have been performed, so the type of the objects in the choices container should match the type specified:请注意,在执行任何类型转换后,将检查choices容器中的包含,因此choices中对象的类型应与指定的类型匹配:

>>> 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)

Any container can be passed as the choices value, so list objects, set objects, and custom containers are all supported.任何容器都可以作为choices值传递,因此都支持list对象、set对象和自定义容器。

Use of enum.Enum is not recommended because it is difficult to control its appearance in usage, help, and error messages.不建议使用enum.Enum,因为很难控制其在使用、帮助和错误消息中的外观。

Formatted choices overrides the default metavar which is normally derived from dest. 格式化的选项覆盖默认的metavar,该metavar通常从dest派生。This is usually what you want because the user never sees the dest parameter. 这通常是您想要的,因为用户从未看到dest参数。If this display isn’t desirable (perhaps because there are many choices), just specify an explicit metavar.如果不需要这种显示(可能是因为有很多选择),只需指定显式metavar即可。

required

In general, the argparse module assumes that flags like -f and --bar indicate optional arguments, which can always be omitted at the command line. 一般来说,argparse模块假设像-f--bar这样的标志表示可选参数,这些参数在命令行中总是可以省略。To make an option required, True can be specified for the required= keyword argument to add_argument():要使选项成为必需选项,可以为add_argument()required=关键字参数指定True

>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo', required=True)
>>> parser.parse_args(['--foo', 'BAR'])
Namespace(foo='BAR')
>>> parser.parse_args([])
usage: [-h] --foo FOO
: error: the following arguments are required: --foo

As the example shows, if an option is marked as required, parse_args() will report an error if that option is not present at the command line.如示例所示,如果某个选项被标记为required(必需),则如果命令行中不存在该选项,parse_args()将报告错误。

Note

Required options are generally considered bad form because users expect options to be optional, and thus they should be avoided when possible.所需选项通常被认为是不好的形式,因为用户希望options可选的,因此在可能的情况下应避免使用。

help

The help value is a string containing a brief description of the argument. help值是一个字符串,包含参数的简要描述。When a user requests help (usually by using -h or --help at the command line), these help descriptions will be displayed with each argument:当用户请求帮助时(通常在命令行中使用-h--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'])
usage: frobble [-h] [--foo] bar [bar ...]
positional arguments:
bar one of the bars to be frobbled

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

The help strings can include various format specifiers to avoid repetition of things like the program name or the argument default. help字符串可以包括各种格式说明符,以避免重复程序名或参数默认值等内容。The available specifiers include the program name, %(prog)s and most keyword arguments to add_argument(), e.g. %(default)s, %(type)s, etc.:可用的说明符包括程序名、%(prog)sadd_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)

options:
-h, --help show this help message and exit

As the help string supports %-formatting, if you want a literal % to appear in the help string, you must escape it as %%.由于帮助字符串支持%-格式,如果希望文本%出现在帮助字符串中,则必须将其转义为%%

argparse supports silencing the help entry for certain options, by setting the help value to argparse.SUPPRESS:通过将help值设置为argparse.SUPPRESS,支持对某些选项的帮助条目进行静音:

>>> parser = argparse.ArgumentParser(prog='frobble')
>>> parser.add_argument('--foo', help=argparse.SUPPRESS)
>>> parser.print_help()
usage: frobble [-h]
options:
-h, --help show this help message and exit

metavar

When ArgumentParser generates help messages, it needs some way to refer to each expected argument. ArgumentParser生成帮助消息时,它需要某种方式来引用每个预期参数。By default, ArgumentParser objects use the dest value as the “name” of each object. 默认情况下,ArgumentParser对象使用dest值作为每个对象的“名称”。By default, for positional argument actions, the dest value is used directly, and for optional argument actions, the dest value is uppercased. 默认情况下,对于位置参数操作,直接使用dest值,对于可选参数操作,dest值为大写。So, a single positional argument with dest='bar' will be referred to as bar. 因此,带有dest='bar'的单个位置参数将被称为barA single optional argument --foo that should be followed by a single command-line argument will be referred to as FOO. 一个单独的可选参数--foo,后跟一个命令行参数,将被称为FOOAn 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

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

An alternative name can be specified with metavar:可以使用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

options:
-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.请注意,metavar仅更改显示的名称,parse_args()对象上属性的名称仍由dest值确定。

Different values of nargs may cause the metavar to be used multiple times. NARG的不同值可能会导致metavar被多次使用。Providing a tuple to metavar specifies a different display for each of the arguments:metavar提供一个元组为每个参数指定不同的显示:

>>> 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]
options:
-h, --help show this help message and exit
-x X X
--foo bar baz

dest

Most ArgumentParser actions add some value as an attribute of the object returned by parse_args(). 大多数ArgumentParser操作都会添加一些值作为parse_args()返回的对象的属性。The name of this attribute is determined by the dest keyword argument of add_argument(). 此属性的名称由add_argument()dest关键字参数确定。For positional argument actions, dest is normally supplied as the first argument to add_argument():对于位置参数操作,dest通常作为add_argument()的第一个参数提供:

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

For optional argument actions, the value of dest is normally inferred from the option strings. 对于可选参数操作,dest的值通常从选项字符串中推断。ArgumentParser generates the value of dest by taking the first long option string and stripping away the initial -- string. 通过获取第一个长选项字符串并去掉初始的--字符串,生成dest的值。If no long option strings were supplied, dest will be derived from the first short option string by stripping the initial - character. 如果没有提供长选项字符串,dest将通过去掉初始-字符从第一个短选项字符串派生。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')

Action classes动作类

Action classes implement the Action API, a callable which returns a callable which processes arguments from the command-line. Action类实现了Action API,它是一个可调用函数,返回一个处理命令行参数的可调用函数。Any object which follows this API may be passed as the action parameter to add_argument().遵循此API的任何对象都可以作为action参数传递给add_argument()

classargparse.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 information needed to parse a single argument from one or more strings from the command line. ArgumentParser使用动作对象来表示从命令行的一个或多个字符串中解析单个参数所需的信息。The Action class must accept the two positional arguments plus any keyword arguments passed to ArgumentParser.add_argument() except for the action itself.Action类必须接受两个位置参数加上传递给ArgumentParser.add_argument()的任何关键字参数,但action本身除外。

Instances of Action (or return value of any callable to the action parameter) should have attributes “dest”, “option_strings”, “default”, “type”, “required”, “help”, etc. defined. 动作实例(或任何可调用action参数的返回值)应定义属性“dest”、“option_strings”、“default”、“type”、“required”、“help”等。The easiest way to ensure these attributes are defined is to call Action.__init__.确保定义这些属性的最简单方法是调用Action.__init__

Action instances should be callable, so subclasses must override the __call__ method, which should accept four parameters:动作实例应该是可调用的,因此子类必须重写__call__方法,该方法应接受四个参数:

  • parser - The ArgumentParser object which contains this action.包含此操作的ArgumentParser对象。

  • namespace - The Namespace object that will be returned by parse_args(). parse_args()将返回的Namespace对象。Most actions add an attribute to this object using setattr().大多数操作使用setattr()将属性添加到此对象。

  • values - The associated command-line arguments, with any type conversions applied. 关联的命令行参数,以及应用的任何类型转换。Type conversions are specified with the type keyword argument to add_argument().类型转换是使用type关键字参数指定的,以添加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.option_string参数是可选的,如果操作与位置参数关联,则该参数将不存在。

The __call__ method may perform arbitrary actions, but will typically set attributes on the namespace based on dest and values.__call__方法可以执行任意操作,但通常会基于destvaluesnamespace上设置属性。

Action subclasses can define a format_usage method that takes no argument and return a string which will be used when printing the usage of the program. Action子类可以定义一个format_usage方法,该方法不带参数,并返回一个字符串,该字符串将在打印程序的用法时使用。If such method is not provided, a sensible default will be used.如果未提供此类方法,将使用合理的默认值。

The parse_args() methodparse_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. 以前对add_argument()的调用确定了创建的对象以及如何分配这些对象。See the documentation for add_argument() for details.有关详细信息,请参阅add_argument()的文档。

  • args - List of strings to parse. 要分析的字符串列表。The default is taken from sys.argv.默认值取自sys.argv

  • namespace - An object to take the attributes. 获取属性的对象。The default is a new empty Namespace object.默认值是新的Namespace对象。

Option value syntax选项值语法

The parse_args() method supports several ways of specifying the value of an option (if it takes one). parse_args()方法支持多种指定选项值的方法(如果需要)。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'])
Namespace(foo=None, x='X')
>>> parser.parse_args(['--foo', 'FOO'])
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'])
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'])
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:只要最后一个选项(或没有)需要一个值,就可以使用单个-前缀将多个短选项连接在一起:

>>> 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'])
Namespace(x=True, y=True, z='Z')

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. 在分析命令行时,parse_args()会检查各种错误,包括不明确的选项、无效类型、无效选项、错误的位置参数数量等。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

Arguments containing 参数包含-

The parse_args() method attempts to give errors whenever the user has clearly made a mistake, but some situations are inherently ambiguous. parse_args()方法尝试在用户显然犯了错误时给出错误,但某些情况本质上是不明确的。For example, the command-line argument -1 could either be an attempt to specify an option or an attempt to provide a positional argument. 例如,命令行参数-1可以是指定选项的尝试,也可以是提供位置参数的尝试。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:parse_args()方法在这里很谨慎:位置参数只能以-开头,如果它们看起来像负数,并且解析器中没有看起来像负号的选项:

>>> 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:如果位置参数必须以-开头,并且看起来不像负数,则可以插入伪参数'--',它告诉parse_args(),后面的所有内容都是位置参数:

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

Argument abbreviations (prefix matching)参数缩写(前缀匹配)

The parse_args() method by default allows long options to be abbreviated to a prefix, if the abbreviation is unambiguous (the prefix matches a unique option):默认情况下parse_args()方法允许长选项缩写为前缀,如果缩写是明确的(前缀匹配唯一选项):

>>> 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. 对于可能生成多个选项的参数,将生成错误。This feature can be disabled by setting allow_abbrev to False.通过将allow_abbrev设置为False,可以禁用此功能。

Beyond 超越sys.argv

Sometimes it may be useful to have an ArgumentParser parse arguments other than those of sys.argv. 有时,让ArgumentParser解析sys.argv以外的参数可能很有用。This can be accomplished by passing a list of strings to parse_args(). 这可以通过将字符串列表传递给parse_args()来实现。This is useful for testing at the interactive prompt:这对于在交互式提示下进行测试非常有用:

>>> parser = argparse.ArgumentParser()
>>> parser.add_argument(
... 'integers', metavar='int', type=int, choices=range(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'])
Namespace(accumulate=<built-in function sum>, integers=[1, 2, 3, 4])

The Namespace object命名空间对象

classargparse.Namespace

Simple class used by default by parse_args() to create an object holding attributes and return it.parse_args()默认使用的简单类,用于创建包含属性的对象并返回它。

This class is deliberately simple, just an object subclass with a readable string representation. 这个类非常简单,只是一个具有可读字符串表示的object子类。If you prefer to have dict-like view of the attributes, you can use the standard Python idiom, vars():如果您喜欢使用类似于dict的属性视图,可以使用标准的Python习惯用法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. ArgumentParser将属性分配给一个已经存在的对象,而不是一个新的Namespace对象也可能很有用。This can be achieved by specifying the namespace= keyword argument:这可以通过指定namespace=关键字参数来实现:

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

Other utilities其他公用事业

Sub-commands子命令

ArgumentParser.add_subparsers([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 svn checkout, svn update, and svn commit. 许多程序将其功能拆分为多个子命令,例如,svn程序可以调用子命令,如svn checkoutsvn updatesvn commitSplitting 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. 支持使用add_subparsers()方法创建此类子命令。The add_subparsers() method is normally called with no arguments and returns a special action object. add_subparsers()方法通常在没有参数的情况下调用,并返回一个特殊操作对象。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.这个对象有一个方法add_parser(),它接受命令名和任何ArgumentParser构造函数参数,并返回一个可以像往常一样修改的ArgumentParser对象。

Description of parameters:参数说明:

  • title - title for the sub-parser group in help output; by default “subcommands” if description is provided, otherwise uses title for positional arguments帮助输出中子解析器组的标题;如果提供了描述,则默认为“子命令”,否则使用标题作为位置参数

  • description - description for the sub-parser group in help output, by default None帮助输出中的子解析器组的描述,默认为None

  • prog - usage information that will be displayed with sub-command help, by default the name of the program and any positional arguments before the subparser argument将与子命令帮助一起显示的使用信息,默认情况下,程序名称和子Parser参数之前的任何位置参数

  • parser_class - class which will be used to create sub-parser instances, by default the class of the current parser (e.g. ArgumentParser)类,该类将用于创建子解析器实例,默认情况下是当前解析器的类(例如ArgumentParser)

  • action - the basic type of action to be taken when this argument is encountered at the command line在命令行遇到此参数时要采取的基本操作类型

  • dest - name of the attribute under which sub-command name will be stored; by default None and no value is stored存储子命令名的属性的名称;默认情况下为None,不存储任何值

  • required - Whether or not a subcommand must be provided, by default False (added in 3.7)是否必须提供子命令,默认为False(在3.7中添加)

  • help - help for sub-parser group in help output, by default None帮助输出中子解析器组的帮助,默认为None

  • metavar - string presenting available sub-commands in help; by default it is None and presents sub-commands in form {cmd1, cmd2, ..}在帮助中显示可用子命令的字符串;默认情况下,它为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). 请注意,parse_args()返回的对象将仅包含命令行选择的主解析器和子解析器的属性(而不是任何其他子解析器)。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.因此,在上面的示例中,当指定a命令时,仅存在foobar属性,而当指定b命令时,只存在foo属性和baz属性。

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.)(但是,每个子解析器命令的帮助消息可以通过向add_parser()提供help=参数来给出,如上所述。)

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

options:
-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

options:
-h, --help show this help message and exit

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

options:
-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. add_subparsers()方法还支持titledescription关键字参数。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} ...
options:
-h, --help show this help message and exit

subcommands:
valid subcommands

{foo,bar} additional help

Furthermore, add_parser supports an additional aliases argument, which allows multiple strings to refer to the same subparser. 此外,add_parser还支持一个附加的aliases参数,该参数允许多个字符串引用同一个子解析器。This example, like svn, aliases co as a shorthand for checkout:本例与svn一样,将co别名为checkout的缩写:

>>> parser = argparse.ArgumentParser()
>>> subparsers = parser.add_subparsers()
>>> checkout = subparsers.add_parser('checkout', aliases=['co'])
>>> checkout.add_argument('foo')
>>> parser.parse_args(['co', 'bar'])
Namespace(foo='bar')

One particularly effective way of handling sub-commands is to combine the use of the add_subparsers() method with calls to set_defaults() so that each subparser knows which Python function it should execute. 处理子命令的一种特别有效的方法是将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. 这样,可以让parse_args()在参数解析完成后调用适当的函数。Associating functions with actions like this is typically the easiest way to handle the different actions for each of your subparsers. 将函数与这样的操作关联通常是处理每个子parser的不同操作的最简单方法。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:但是,如果需要检查调用的子解析器的名称,add_subparsers()调用的dest关键字参数将起作用:

>>> 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')

Changed in version 3.7:版本3.7中更改: New required keyword argument.新增的required关键字参数。

FileType objects对象

classargparse.FileType(mode='r', bufsize=- 1, encoding=None, errors=None)

The FileType factory creates objects that can be passed to the type argument of ArgumentParser.add_argument(). FileType工厂创建可以传递给ArgumentParser.add_argument()的类型参数的对象。Arguments that have FileType objects as their type will open command-line arguments as files with the requested modes, buffer sizes, encodings and error handling (see the open() function for more details):FileType对象作为其类型的参数将打开命令行参数作为具有请求模式、缓冲区大小、编码和错误处理的文件(有关详细信息,请参阅open()函数):

>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--raw', type=argparse.FileType('wb', 0))
>>> parser.add_argument('out', type=argparse.FileType('w', encoding='UTF-8'))
>>> parser.parse_args(['--raw', 'raw.dat', 'file.txt'])
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 automatically convert this into sys.stdin for readable FileType objects and sys.stdout for writable FileType objects:FileType对象理解伪参数'-',并自动将其转换为sys.stdin(对于可读FileType类型对象)和sys.stdout(对于可写FileType对象):

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

New in version 3.4.版本3.4中新增。The encodings and errors keyword arguments.encodingserrors关键字参数。

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. 默认情况下,ArgumentParser在显示帮助消息时将命令行参数分组为“位置参数”和“可选参数”。When there is a better conceptual grouping of arguments than this default one, appropriate groups can be created using the add_argument_group() method:如果参数的概念分组优于此默认分组,则可以使用add_argument_group()方法创建适当的组:

>>> 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. add_argument_group()方法返回一个参数组对象,该对象有一个add_argument()方法,就像普通的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:add_argument_group()方法接受titledescription参数,可用于自定义此显示:

>>> 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.请注意,不在用户定义组中的任何参数都将返回到通常的“位置参数”和“可选参数”部分。

Mutual exclusion互斥

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:add_mutually_exclusive_group()方法还接受一个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().请注意,当前互斥的参数组不支持add_argument_group()titledescription参数。

Parser defaults解析器默认值

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. 大多数情况下,parse_args()返回的对象的属性将通过检查命令行参数和参数操作来完全确定。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.有关此类型的示例,请参阅add_subparsers()方法。

ArgumentParser.get_default(dest)

Get the default value for a namespace attribute, as set by either add_argument() or by set_defaults():获取命名空间属性的默认值,由add_argument()set_defaults()设置:

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

Printing help打印帮助

In most typical applications, parse_args() will take care of formatting and printing any usage or error messages. 在大多数典型的应用程序中,parse_args()将负责格式化和打印任何用法或错误消息。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. 打印应如何在命令行上调用ArgumentParser的简要说明。If file is None, sys.stdout is assumed.如果fileNone,则假定为sys.stdout

ArgumentParser.print_help(file=None)

Print a help message, including the program usage and information about the arguments registered with the ArgumentParser. 打印一条帮助消息,包括程序用法和有关在ArgumentParser中注册的参数的信息。If file is None, sys.stdout is assumed.如果fileNone,则假定为sys.stdout

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的简要描述。

ArgumentParser.format_help()

Return a string containing a help message, including the program usage and information about the arguments registered with the ArgumentParser.返回包含帮助消息的字符串,包括程序用法和有关在ArgumentParser中注册的参数的信息。

Partial parsing部分解析

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. 在这些情况下,parse_known_args()方法可能很有用。It works much like parse_args() except that it does not produce an error when extra arguments are present. 它的工作原理与parse_args()非常相似,只是在存在额外参数时不会产生错误。Instead, it returns a two item tuple containing the populated namespace and the list of remaining argument strings.相反,它返回一个包含填充名称空间和剩余参数字符串列表的两项元组。

>>> 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 rules apply to parse_known_args(). 前缀匹配规则适用于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.解析器可能会使用一个选项,即使它只是其已知选项之一的前缀,而不是将其保留在剩余参数列表中。

Customizing file parsing自定义文件解析

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. 从文件读取的参数(请参阅ArgumentParser构造函数的fromfile_prefix_chars参数)每行读取一个参数。convert_arg_line_to_args() can be overridden for fancier reading.可以被重写以进行更有趣的阅读。

This method takes a single argument arg_line which is a string read from the argument file. 此方法采用单个参数arg_line,它是从参数文件读取的字符串。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. 此方法的一个有用重写是将每个空格分隔的单词视为参数。The following example demonstrates how to do this:下面的示例演示了如何执行此操作:

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

Exiting methods退出方法

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. 此方法终止程序,以指定的status退出,如果给定,则在此之前打印一条消息。The user can override this method to handle these steps differently:用户可以重写此方法以不同方式处理这些步骤:

class ErrorCatchingArgumentParser(argparse.ArgumentParser):
def exit(self, status=0, message=None):
if status:
raise Exception(f'Exiting because of an error: {message}')
exit(status)
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.该方法打印一条包含标准错误消息的使用消息,并以状态代码2终止程序。

Intermixed parsing混合解析

ArgumentParser.parse_intermixed_args(args=None, namespace=None)
ArgumentParser.parse_known_intermixed_args(args=None, namespace=None)

A number of Unix commands allow the user to intermix optional arguments with positional arguments. 许多Unix命令允许用户将可选参数与位置参数混合使用。The parse_intermixed_args() and parse_known_intermixed_args() methods support this parsing style.parse_intermixed_args()parse_mixed_args()parse_known_intermixed_args()方法支持这种解析风格。

These parsers do not support all the argparse features, and will raise exceptions if unsupported features are used. 这些解析器不支持所有argparse功能,如果使用不支持的功能,将引发异常。In particular, subparsers, argparse.REMAINDER, and mutually exclusive groups that include both optionals and positionals are not supported.特别是,不支持同时包含选项和位置的子解析器argparse.REMAINDER和互斥组。

The following example shows the difference between parse_known_args() and parse_intermixed_args(): the former returns ['2', '3'] as unparsed arguments, while the latter collects all the positionals into rest.下面的示例显示了parse_known_args()parse_intermixed_args()之间的差异:前者返回['2', '3']作为未分析的参数,而后者将所有位置收集到rest中。

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

parse_known_intermixed_args() returns a two item tuple containing the populated namespace and the list of remaining argument strings. 返回包含已填充命名空间和剩余参数字符串列表的两项元组。parse_intermixed_args() raises an error if there are any remaining unparsed argument strings.如果存在任何剩余的未分析参数字符串,则引发错误。

New in version 3.7.版本3.7中新增。

Upgrading optparse code升级optparse代码

Originally, the argparse module had attempted to maintain compatibility with optparse. 最初,argparse模块试图保持与optparse的兼容性。However, optparse was difficult to extend transparently, particularly with the changes required to support the new nargs= specifiers and better usage messages. 然而,optparse很难透明地扩展,特别是在支持新的nargs=说明符和更好的使用消息所需的更改中。When most everything in optparse had either been copy-pasted over or monkey-patched, it no longer seemed practical to try to maintain the backwards compatibility.optparse中的大部分内容要么是复制粘贴的,要么是猴子修补的,试图保持向后兼容性似乎不再实用。

The argparse module improves on the standard library optparse module in a number of ways including:argparse模块以多种方式改进了标准库optparse模块,包括:

  • Handling positional arguments.处理位置参数。

  • Supporting sub-commands.支持子命令。

  • 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.为自定义typeaction提供了简单得多的接口。

A partial upgrade path from optparse to argparse:optparseargparse的部分升级路径:

  • Replace all optparse.OptionParser.add_option() calls with ArgumentParser.add_argument() calls.ArgumentParser.add_argument()调用替换所有optparse.OptionParser.add_option()调用。

  • Replace (options, args) = parser.parse_args() with args = parser.parse_args() and add additional ArgumentParser.add_argument() calls for the positional arguments. (options, args) = parser.parse_args()替换为args = parser.parse_args(),并为位置参数添加其他参数ArgumentParser.add_argument()调用。Keep in mind that what was previously called options, now in the argparse context is called args.请记住,以前称为options,现在在argparse上下文中称为args

  • Replace optparse.OptionParser.disable_interspersed_args() by using parse_intermixed_args() instead of parse_args().通过使用parse_intermixed_args()而不是parse_args()来替换optparse.OptionParser.disable_interspersed_args()

  • Replace callback actions and the callback_* keyword arguments with type or action arguments.typeaction参数替换回调操作和callback_*关键字参数。

  • Replace string names for type keyword arguments with the corresponding type objects (e.g. int, float, complex, etc).用相应的类型对象(例如intfloatcomplex等)替换type关键字参数的字符串名称。

  • Replace optparse.Values with Namespace and optparse.OptionError and optparse.OptionValueError with ArgumentError.optparse.Values替换为Namespace,将optparse.OptionErroroptparse.OptionValueError替换为ArgumentError

  • Replace strings with implicit arguments such as %default or %prog with the standard Python syntax to use dictionaries to format strings, that is, %(default)s and %(prog)s.使用标准Python语法将字符串替换为隐式参数,如%default%prog,以使用字典格式化字符串,即%(default)s%(prog)s

  • Replace the OptionParser constructor version argument with a call to parser.add_argument('--version', action='version', version='<the version>').OptionParser构造函数版本参数替换为调用parser.add_argument('--version', action='version', version='<the version>')