argparse - Parser for command-line options, arguments and sub-commands - 3

argparse - Parser for command-line options, arguments and sub-commands - 3

argparse - Parser for command-line options, arguments and sub-commands
https://docs.python.org/3/library/argparse.html

argparse - 命令行选项、参数和子命令解析器
https://docs.python.org/zh-cn/3/library/argparse.html

3. The add_argument() method - add_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.
name or flags - 一个命名或者一个选项字符串的列表,e.g. foo or -f, --foo。

action - The basic type of action to be taken when this argument is encountered at the command line.
action - 当参数在命令行中出现时使用的动作基本类型。

nargs - The number of command-line arguments that should be consumed.
nargs - 命令行参数应当消耗的数目。

const - A constant value required by some action and nargs selections.
const - 被一些 action 和 nargs 选择所需求的常数。

default - The value produced if the argument is absent from the command line.
default - 当参数未在命令行中出现时使用的值。

type - The type to which the command-line argument should be converted.
type - 命令行参数应当被转换成的类型。

choices - A container of the allowable values for the argument.
choices - 可用的参数的容器。

required - Whether or not the command-line option may be omitted (optionals only).
required - 此命令行选项是否可省略 (仅选项可用)。

help - A brief description of what the argument does.
help - 一个此选项作用的简单描述。

metavar - A name for the argument in usage messages.
metavar - 在使用方法消息中使用的参数值示例。

dest - The name of the attribute to be added to the object returned by parse_args().
dest - 被添加到 parse_args() 所返回对象上的属性名。

The following sections describe how each of these are used.
以下部分描述这些参数如何使用。

3.1 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. The first arguments passed to add_argument() must therefore be either a series of flags, or a simple argument name. For example, an optional argument could be created like:
add_argument() 方法必须知道它是否是 optional argument,例如 -f 或 --foo,或是一个位置参数,例如一组文件名。第一个传递给 add_argument() 的参数必须是一系列 flags 或者是一个简单的参数名。例如,optional argument 可以被这样创建:

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() 被调用,optional arguments 会以 - 前缀识别,剩下的参数则会被假定为位置参数:

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

3.2 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(). The action keyword argument specifies how the command-line arguments should be handled. The supplied actions are:
ArgumentParser 对象将命令行参数与动作相关联。这些动作可以做与它们相关联的命令行参数的任何事,尽管大多数动作只是简单的向 parse_args() 返回的对象上添加属性。action 命名参数指定了这个命令行参数应当如何处理。供应的动作有:

  • ‘store’ - This just stores the argument’s value. This is the default action. For example:
    ‘store’ - 存储参数的值。这是默认的动作。
>>> 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. The ‘store_const’ action is most commonly used with optional arguments that specify some sort of flag. For example:
    ‘store_const’ - 存储被 const 命名参数指定的值。‘store_const’ 动作通常用在选项中来指定一些标志。
>>> 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. In addition, they create default values of False and True respectively. For example:
    ‘store_true’ and ‘store_false’ - 这些是 ‘store_const’ 分别用作存储 True 和 False 值的特殊用例。另外,它们的默认值分别为 False 和 True。
>>> 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:
    ‘append’ - 存储一个列表,并且将每个参数值追加到列表中。在允许多次使用选项时很有用。
>>> 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.) The ‘append_const’ action is typically useful when multiple arguments need to store constants to the same list. For example:
‘append_const’ - 这存储一个列表,并将 const 命名参数指定的值追加到列表中。(注意 const 命名参数默认为 None。)‘append_const’ 动作一般在多个参数需要在同一列表中存储常数时会有用。

>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--str', dest='types', action='append_const', const=str)
>>> parser.add_argument('--int', dest='types', action='append_const', const=int)
>>> parser.parse_args('--str --int'.split())
Namespace(types=[, ])
  • ‘count’ - This counts the number of times a keyword argument occurs. For example, this is useful for increasing verbosity levels:
    ‘count’ - 计算一个关键字参数出现的数目或次数。例如,对于一个增长的详情等级来说有用
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--verbose', '-v', action='count')
>>> parser.parse_args(['-vvv'])
Namespace(verbose=3)
  • ‘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.
    ‘help’ - 打印所有当前解析器中的选项和参数的完整帮助信息,然后退出。默认情况下,一个 help 动作会被自动加入解析器。关于输出是如何创建的,参与 ArgumentParser。

  • ‘version’ - This expects a version= keyword argument in the add_argument() call, and prints version information and exits when invoked:
    ‘version’ - 期望有一个 version= 命名参数在 add_argument() 调用中,并打印版本信息并在调用后退出:

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

You may also specify an arbitrary action by passing an Action subclass or other object that implements the same interface. The recommended way to do this is to extend Action, overriding the call method and optionally the init method.
您还可以通过传递 Action 子类或实现相同接口的其他对象来指定任意操作。建议的方法是扩展 Action,覆盖 call 方法和可选的 init 方法。

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(FooAction, self).__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')

3.3 nargs

ArgumentParser objects usually associate a single command-line argument with a single action to be taken. The nargs keyword argument associates a different number of command-line arguments with a single action. The supported values are:
ArgumentParser 对象通常关联一个单独的命令行参数到一个单独的被执行的动作。nargs 命名参数关联不同数目的命令行参数到单一动作。支持的值有:

  • N (an integer). N arguments from the command line will be gathered together into a list. For example:
    N (一个整数)。命令行中的 N 个参数会被聚集到一个列表中。
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo', nargs=2)
>>> parser.add_argument('bar', nargs=1)
>>> parser.parse_args('c --foo a b'.split())
Namespace(bar=['c'], foo=['a', 'b'])

Note that nargs=1 produces a list of one item. This is different from the default, in which the item is produced by itself.
注意 nargs=1 会产生一个单元素列表。这和默认的元素本身是不同的。

  • ‘?’. 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. Some examples to illustrate this:
    ‘?’。如果可能的话,会从命令行中消耗一个参数,并产生一个单一项。如果当前没有命令行参数,则会产生 default 值。注意,对于选项,有另外的用例 - 选项字符串出现但没有跟随命令行参数,则会产生 const 值。
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo', nargs='?', const='c', default='d')
>>> parser.add_argument('bar', nargs='?', default='d')
>>> parser.parse_args(['XX', '--foo', 'YY'])
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=’?’ 的一个更普遍用法是允许可选的输入或输出文件:

>>> 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='' encoding='UTF-8'>,
          outfile=<_io.TextIOWrapper name='' 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. For example:
    '
    ’。所有当前命令行参数被聚集到一个列表中。注意通过 nargs=’*’ 来实现多个位置参数通常没有意义,但是多个选项是可能的。
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo', nargs='*')
>>> parser.add_argument('--bar', nargs='*')
>>> parser.add_argument('baz', nargs='*')
>>> parser.parse_args('a b --foo x y --bar 1 2'.split())
Namespace(bar=['1', '2'], baz=['a', 'b'], foo=['x', 'y'])
  • ‘+’. 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

argparse.REMAINDER. All the remaining command-line arguments are gathered into a list. This is commonly useful for command line utilities that dispatch to other command line utilities:
argarse.REMAINDER。所有剩余的命令行参数被聚集到一个列表中。这通常在从一个命令行功能传递参数到另一个命令行功能中时有用:

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

If the nargs keyword argument is not provided, the number of arguments consumed is determined by the action. Generally this means a single command-line argument will be consumed and a single item (not a list) will be produced.
如果不提供 nargs 命名参数,则消耗参数的数目将被 action 决定。通常这意味着单一项目 (非列表) 消耗单一命令行参数。

3.4 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’. These actions add the const value to one of the attributes of the object returned by parse_args(). See the action description for examples.
当 add_argument() 通过 action=‘store_const’ 或 action='append_const 调用时。这些动作将 const 值添加到 parse_args() 返回的对象的属性中。在 action 的描述中查看案例。

When add_argument() is called with option strings (like -f or --foo) and nargs=’?’. 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. See the nargs description for examples.
当 add_argument() 通过选项 (例如 -f 或 --foo) 调用并且 nargs=’?’ 时。这会创建一个可以跟随零个或一个命令行参数的选项。当解析命令行时,如果选项后没有参数,则将用 const 代替。在 nargs 描述中查看案例。

With the ‘store_const’ and ‘append_const’ actions, the const keyword argument must be given. For other actions, it defaults to None.
对 ‘store_const’ 和 ‘append_const’ 动作, const 命名参数必须给出。对其他动作,默认为 None。

3.5 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. For optional arguments, the default value is used when the option string was not present at the command line:
所有 optional arguments and some positional arguments 可能在命令行中被忽略。add_argument() 的命名参数 default,默认值为 None,指定了在命令行参数未出现时应当使用的值。对于 optional arguments,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 default value is a string, the parser parses the value as if it were a command-line argument. In particular, the parser applies any type conversion argument, if provided, before setting the attribute on the Namespace return value. Otherwise, the parser uses the value as is:
如果 default 值是一个字符串,解析器解析此值就像一个命令行参数。特别是,在将属性设置在 Namespace 的返回值之前,解析器应用任何提供的 type 转换参数。否则解析器使用原值:

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

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

3.6 type

By default, ArgumentParser objects read command-line arguments in as simple strings. However, quite often the command-line string should instead be interpreted as another type, like a float or int. The type keyword argument of add_argument() allows any necessary type-checking and type conversions to be performed. Common built-in types and functions can be used directly as the value of the type argument:
默认情况下,ArgumentParser 对象将命令行参数当作简单字符串读入。然而,命令行字符串经常需要被当作其它的类型,比如 float 或者 int。add_argument() 的 type 关键词参数允许任何的类型检查和类型转换。一般的内建类型和函数可以直接被 type 参数使用。

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

See the section on the default keyword argument for information on when the type argument is applied to default arguments.
有关何时将 type 参数应用于默认参数的信息,请参阅 default 关键字参数部分。

To ease the use of various types of files, the argparse module provides the factory FileType which takes the mode=, bufsize=, encoding= and errors= arguments of the open() function. For example, FileType(‘w’) can be used to create a writable file:
为了便于使用各种类型的文件,argparse 模块提供了 FileType,它接受 open() 函数的 mode=, bufsize=, encoding= and errors= arguments。例如,FileType(‘w’) 可用于创建可写文件:

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

type= can take any callable that takes a single string argument and returns the converted value:
type = 可以接受任何带有单个字符串参数的 callable 并返回转换后的值:

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

The choices keyword argument may be more convenient for type checkers that simply check against a range of values:
对于只检查一系列值的类型检查器,choices 关键字参数可能更方便:

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

3.7 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(). 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:
应从一组受限制的值中选择某些命令行参数。这些可以通过将容器对象作为 choice 关键字参数传递给 add_argument() 来处理。解析命令行时,将检查参数值,如果参数不是可接受的值之一,则会显示错误消息:

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

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:
请注意,在执行任何类型转换后,将检查选项容器中的包含,因此选择容器中对象的类型应与指定的类型匹配:

>>> 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 object that supports the in operator can be passed as the choices value, so dict objects, set objects, custom containers, etc. are all supported.
任何支持 in 运算符的对象都可以作为选项值传递,因此支持 dict 对象、set 对象、自定义容器等。

3.8 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. To make an option required, True can be specified for the required= keyword argument to add_argument():
通常,argparse 模块假定 -f 和 --bar 之类的标志指示可选参数,在命令行中始终可以省略这些参数。要创建所需的选项,可以为 add_argument() 的 required = keyword参数指定 True:

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

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() 将报告错误。

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

3.9 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 the command line), these help descriptions will be displayed with each argument:
help 值是一个包含参数简要描述的字符串。当用户请求帮助时 (通常在命令行中使用 -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

optional arguments:
 -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. The available specifiers include the program name, %(prog)s and most keyword arguments to add_argument(), e.g. %(default)s, %(type)s, etc.:
help 字符串可以包含各种格式说明符,以避免重复诸如程序名称或参数默认值之类的事情。可用的说明符包括程序名,%(prog)s 和 add_argument() 的大多数关键字参数,e.g. %(default)s, %(type)s, etc.:

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

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

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

As the help string supports %-formatting, if you want a literal % to appear in the help string, you must escape it as %%.
由于帮助字符串支持 %-formatting,如果要在帮助字符串中显示文字 %,则必须将其作为 %% 转义。

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

escape [ɪ'skeɪp; e-]:vt. 逃避,避开,避免,被忘掉,被忽视 vi. 逃脱,避开,溜走,(气体,液体等) 漏出,(未受伤或只受了一点伤害而) 逃脱,声音 (不自觉地) 由...发出 n. 逃跑,逃亡,逃走,逃跑工具或方法,野生种,泄漏
silence ['saɪləns]:n. 沉默,寂静,缄默,不谈,无声状态 vt. 使沉默,使安静,压制,消除噪音 int. 安静!,别作声!
>>> parser = argparse.ArgumentParser(prog='frobble')
>>> parser.add_argument('--foo', help=argparse.SUPPRESS)
>>> parser.print_help()
usage: frobble [-h]

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

3.10 metavar

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

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

positional arguments:
 bar

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

An alternative name can be specified with metavar:
可以使用 metavar 指定替代名称:

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

positional arguments:
 XXX

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

Note that metavar only changes the displayed name - the name of the attribute on the parse_args() object is still determined by the dest value.
请注意,metavar 仅更改显示的名称 - parse_args() 对象上的属性名称仍由 dest 值确定。

Different values of nargs may cause the metavar to be used multiple times. Providing a tuple to metavar specifies a different display for each of the arguments:
不同的 nargs 值可能导致 metavar 被多次使用。为 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]

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

3.11 dest

Most ArgumentParser actions add some value as an attribute of the object returned by parse_args(). The name of this attribute is determined by the dest keyword argument of add_argument(). For positional argument actions, dest is normally supplied as the first argument to add_argument():
大多数 ArgumentParser 操作都会添加一些值作为 parse_args() 返回的对象的属性。此属性的名称由 add_argument() 的 dest 关键字参数确定。对于位置参数动作,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. ArgumentParser generates the value of dest by taking the first long option string and stripping away the initial – string. If no long option strings were supplied, dest will be derived from the first short option string by stripping the initial - character. Any internal - characters will be converted to _ characters to make sure the string is a valid attribute name. The examples below illustrate this behavior:
对于可选参数操作,dest 的值通常从选项字符串中推断出来。ArgumentParser 通过获取第一个长选项字符串并剥离初始 – 字符串来生成 dest 的值。如果没有提供长选项字符串,则将通过剥离初始 - 字符从第一个短选项字符串派生 dest。任何内部 - 字符都将转换为 _ 字符,以确保该字符串是有效的属性名称。以下示例说明了此行为:

>>> 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:
dest 允许提供自定义属性名称:

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

你可能感兴趣的:(Python,3.x,-,Python,2.x)