创新互联Python教程:argparse—-命令行选项、参数和子命令解析器

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

3.2 新版功能.

源代码: Lib/argparse.py


教程

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

The argparse module makes it easy to write user-friendly command-line interfaces. The program defines what arguments it requires, and argparse will figure out how to parse those out of sys.argv. The argparse module also automatically generates help and usage messages. The module will also issue errors when users give the program invalid arguments.

Core Functionality

The argparse module’s support for command-line interfaces is built around an instance of argparse.ArgumentParser. It is a container for argument specifications and has options that apply the parser as whole:

 
 
 
 
  1. parser = argparse.ArgumentParser(
  2. prog = 'ProgramName',
  3. description = 'What the program does',
  4. epilog = 'Text at the bottom of help')

The ArgumentParser.add_argument() method attaches individual argument specifications to the parser. It supports positional arguments, options that accept values, and on/off flags:

 
 
 
 
  1. parser.add_argument('filename') # positional argument
  2. parser.add_argument('-c', '--count') # option that takes a value
  3. parser.add_argument('-v', '--verbose',
  4. action='store_true') # on/off flag

The ArgumentParser.parse_args() method runs the parser and places the extracted data in a argparse.Namespace object:

 
 
 
 
  1. args = parser.parse_args()
  2. print(args.filename, args.count, args.verbose)

Quick Links for add_argument()

Name

Description

Values

action

Specify how an argument should be handled

‘store’, ‘store_const’, ‘store_true’, ‘append’, ‘append_const’, ‘count’, ‘help’, ‘version’

choices

Limit values to a specific set of choices

[‘foo’, ‘bar’], range(1, 10), or Container instance

const

Store a constant value

default

Default value used when an argument is not provided

Defaults to None

dest

Specify the attribute name used in the result namespace

help

Help message for an argument

metavar

Alternate display name for the argument as shown in help

nargs

Number of times the argument can be used

int, ‘?’, ‘*’, ‘+’, or argparse.REMAINDER

required

Indicate whether an argument is required or optional

True or False

type

Automatically convert an argument to the given type

int, float, argparse.FileType(‘w’), or callable function

示例

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

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

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

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

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

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

If invalid arguments are passed in, an error will be displayed:

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

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

创建一个解析器

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

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

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

添加参数

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

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

Later, calling parse_args() will return an object with two attributes, integers and accumulate. The integers attribute will be a list of one or more integers, 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.

解析参数

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

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

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

ArgumentParser 对象

class argparse.ArgumentParser(prog=None, usage=None, description=None, epilog=None, parents=[], formatter_class=argparse.HelpFormatter, prefix_chars=’-‘, fromfile_prefix_chars=None, argument_default=None, conflict_handler=’error’, add_help=True, allow_abbrev=True, exit_on_error=True)

创建一个新的 ArgumentParser 对象。所有的参数都应当作为关键字参数传入。每个参数在下面都有它更详细的描述,但简而言之,它们是:

  • prog - 程序的名称 (默认值: os.path.basename(sys.argv[0]))

  • usage - 描述程序用途的字符串(默认值:从添加到解析器的参数生成)

  • description - Text to display before the argument help (by default, no text)

  • epilog - Text to display after the argument help (by default, no text)

  • parents - 一个 ArgumentParser 对象的列表,它们的参数也应包含在内

  • formatter_class - 用于自定义帮助文档输出格式的类

  • prefix_chars - 可选参数的前缀字符集合(默认值: ‘-‘)

  • fromfile_prefix_chars - 当需要从文件中读取其他参数时,用于标识文件名的前缀字符集合(默认值: None

  • argument_default - 参数的全局默认值(默认值: None

  • conflict_handler - 解决冲突选项的策略(通常是不必要的)

  • add_help - 为解析器添加一个 -h/--help 选项(默认值: True

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

  • exit_on_error - 决定当错误发生时是否让 ArgumentParser 附带错误信息退出。 (默认值: True)

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

在 3.8 版更改: 在之前的版本中,allow_abbrev 还会禁用短旗标分组,例如 -vv 表示为 -v -v

在 3.9 版更改: 添加了 exit_on_error 形参。

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

prog

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

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

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

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

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

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

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

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

usage

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

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

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

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

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

description

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

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

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

epilog

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

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

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

parents

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

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

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

备注

你在通过``parents=`` 传递解析器之前必须完全初始化它们。 如果你在子解析器之后改变父解析器,这些改变将不会反映在子解析器上。

formatter_class

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

class argparse.RawDescriptionHelpFormatter

class argparse.RawTextHelpFormatter

class argparse.ArgumentDefaultsHelpFormatter

class argparse.MetavarTypeHelpFormatter

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

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

传 RawDescriptionHelpFormatter 给 formatter_class= 表示 description 和 epilog 已经被正确的格式化了,不能在命令行中被自动换行:

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

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

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

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

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

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

prefix_chars

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

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

prefix_chars= 参数默认使用 '-'。 提供一组不包括 - 的字符将导致 -f/--foo 选项不被允许。

fromfile_prefix_chars

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

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

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

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

argument_default

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

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

allow_abbrev

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

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

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

3.5 新版功能.

conflict_handler

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

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

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

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

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

add_help

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

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

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

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

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

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

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

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

exit_on_error

正常情况下,当你向 ArgumentParser 的 parse_args() 方法传入一个无效的参数列表时,它将会退出并发出错误信息。

如果用户想要手动捕获错误,可通过将 exit_on_error 设为 False 来启用该特性:

 
 
 
 
  1. >>> parser = argparse.ArgumentParser(exit_on_error=False)
  2. >>> parser.add_argument('--integers', type=int)
  3. _StoreAction(option_strings=['--integers'], dest='integers', nargs=None, const=None, default=None, type=, choices=None, help=None, metavar=None)
  4. >>> try:
  5. ... parser.parse_args('--integers a'.split())
  6. ... except argparse.ArgumentError:
  7. ... print('Catching an argumentError')
  8. ...
  9. Catching an argumentError

3.9 新版功能.

add_argument() 方法

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

定义单个的命令行参数应当如何解析。每个形参都在下面有它自己更多的描述,长话短说有:

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

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

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

  • const - 被一些 action 和 nargs 选择所需求的常数。

  • default - 当参数未在命令行中出现并且也不存在于命名空间对象时所产生的值。

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

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

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

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

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

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

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

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:

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

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

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

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

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

action

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

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

       
       
       
       
    1. >>> parser = argparse.ArgumentParser()
    2. >>> parser.add_argument('--foo')
    3. >>> parser.parse_args('--foo 1'.split())
    4. Namespace(foo='1')
  • 'store_const' - This stores the value specified by the const keyword argument; note that the const keyword argument defaults to None. The 'store_const' action is most commonly used with optional arguments that specify some sort of flag. For example:

       
       
       
       
    1. >>> parser = argparse.ArgumentParser()
    2. >>> 文章名称:创新互联Python教程:argparse—-命令行选项、参数和子命令解析器
      浏览路径:http://www.shufengxianlan.com/qtweb/news38/356788.html

      网站建设、网络推广公司-创新互联,是专注品牌与效果的网站制作,网络营销seo公司;服务项目有等

      广告

      声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联