argparse模块

2023-05-16

  • 1模块简介
  • 2Example
  • 3argparse三个主要函数
    • parser argparseArgumentParser
    • parseradd_argument
    • args parserparse_args
  • 4ArgumentParser对象
    • 对象参数简介
    • 对象参数的具体用法
      • prog 程序文件名
      • usage 程序使用说明
      • description 程序目的说明
      • epilog 程序说明后记
      • parents 父对象列表
      • formatter_class 格式化类用以说明显示格式
        • prefix_chars 可选参数前缀符
      • fromfile_prefix_chars 文件前缀字符
      • 9 argument_default 参数的默认值
      • allow_abbrev 是否支持缩写
      • conflict_handler 冲突处理
      • add_help 是否显示帮助信息
  • 5add_argument方法
    • 函数参数简介
    • 函数参数的具体用法
      • name or flags
      • action
      • nargs
      • const
      • default
      • type
      • choices
      • required
      • help
      • metavar
      • dest
  • 6parse_args方法
  • 7The Namespace object

(1)模块简介

argparse是Python中的一个常用模块,和sys.argv()功能类似,主要用于编写命令行接口:对于程序所需要的参数,它可以进行正确的解析。另外,argparse还可以自动的生成helpusage信息,当程序的参数无效时,它可以自动生成错误信息。
[参考文档]:https://docs.python.org/3/library/argparse.html

(2)Example

下列代码是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))

假定上述代码保存为prog.py,它可以在命令行执行并自动提供有用的help信息:

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

Process some integers.

positional arguments:
 N           an integer for the accumulator

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

该程序可以接受相应的参数并给出相应的输出:

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

如果传入无效的参数,它可以自动生成error信息:

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

(3)argparse三个主要函数:

1. parser = argparse.ArgumentParser()

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

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

ArgumentParser对象保存了所有必要的信息,用以将命令行参数解析为相应的python数据类型。

2. parser.add_argument()

调用add_argument()向ArgumentParser对象添加命令行参数信息,这些信息告诉ArgumentParser对象如何处理命令行参数。可以通过调用parse_agrs()来使用这些命令行参数。例如:

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

之后,调用parse.args()将返回一个对象,它具有两个属性:integersaccumulate,前者是一个整数集合,后者根据命令行参数的不同,代表不同的函数,可以是max(),也可以是sum()。

3. args = parser.parse_args()

通过调用parse_args()来解析ArgumentParser对象中保存的命令行参数:将命令行参数解析成相应的数据类型并采取相应的动作,它返回一个Namespace对象。

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

在实际的python脚本中,parse_args()一般并不使用参数,它的参数由sys.argv决定。

(4)ArgumentParser对象

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

对象参数简介:

  • prog - The name of the program (default: 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)
    • 程序目的说明
  • epilog - Text to display after the argument help (default: none)
    • 程序说明后记
  • parents - A list of ArgumentParser objects whose arguments should also be included (default: [])
    • ArgumentParser对象的父对象的参数列表
  • formatter_class - A class for customizing the help output
    • help信息的说明格式
  • 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)
  • argument_default - The global default value for arguments (default: None)
    • 参数的全局默认值
  • conflict_handler - The strategy for resolving conflicting optionals (usually unnecessary)
    • 冲突处理
  • add_help - Add a -h/–help option to the parser (default: True)
    • 是否增加help选项
  • allow_abbrev - Allows long options to be abbreviated if the abbreviation is unambiguous. (default: True)
    • 是否使用参数的缩写

对象参数的具体用法

1. prog 程序文件名

默认情况下,ArgumentParser对象使用sys.argv[0]来决定如何在help信息中显示程序的文件名。
例如:下列代码的文件名为myprogram.py

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

它的help信息将显示程序的文件名,而不管程序在何处进行调用。

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

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

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

使用prog参数可以修改ArgumentParser对象的默认文件名:

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

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

不论程序的文件名是来自sys.argv[0],不是来自参数prog,都可以通过%(prog)s来引用程序的文件名。

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

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

2. usage 程序使用说明

默认情况下,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

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

可以使用参数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

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

3. description 程序目的说明

一般情况下,ArgumentParser对象会使用参数description来说明程序的用途以及目的。description信息一般位于usage信息和help信息之间。

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

A foo that bars

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

默认情况下,description会自动调整间距来适应显示空间。可以通过formatter_class类来修改它的显示方式。

4. epilog 程序说明后记

一些程序喜欢在参数描述信息之后添加额外的信息,这些信息可以通过参数epilog来指定。

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

A foo that bars

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

And that's how you'd foo a bar

description类似,epilog会自动调整间距来适应显示空间。可以通过formatter_class类来修改它的显示方式。

5. parents 父对象列表

有时候,parsers会共享很多参数,为了避免参数的重复定义,可以定义一个包涵共享参数的parent_parser。当定义需要共享参数的ArgumentParser对象child_parser时,可以通过参数parent把共享参数传递给child_parser,只需要ArgumentParser对象的参数parent=[parent_parser]即可。注意,parent参数的值是一系列父对象的列表。

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

注意,当使用参数parent是,父对象的参数add_help要设置为False,否则,ArgumentParser对象会生成两个-h/--help选项,从而出错。
注意,在通过参数parent进行传递之前,parent_parser必须显示初始化。另外,传递结束之后,任何对父对象的修改都不会影响子对象的值。

6. formatter_class 格式化类,用以说明显示格式

参数formatter_class不常用,因此没翻译此部分。
ArgumentParser objects allow the help formatting to be customized by specifying an alternate formatting class. Currently, there are four such classes:

class argparse.RawDescriptionHelpFormatter
class argparse.RawTextHelpFormatter
class argparse.ArgumentDefaultsHelpFormatter
class argparse.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:

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

this description was indented weird but that is okay

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

likewise for this epilog whose whitespace will be cleaned up and whose words
will be wrapped across a couple lines
Passing RawDescriptionHelpFormatter as formatter_class= indicates that description and epilog are already correctly formatted and should not be line-wrapped:

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

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

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

RawTextHelpFormatter maintains whitespace for all sorts of help text, including argument descriptions. 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 [bar ...]]

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

optional arguments:
 -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):

$ 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

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

7. prefix_chars 可选参数前缀符

大部分命令行参数选项使用-作为前缀,例如: -f/–foo. 可以通过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')

默认情况下使用-作为前缀,当使用其它字符作为前缀后,-将被作为一个普通字符,以-开头的字符串也不会被认为是参数选项,而是普通的字符串。

8. fromfile_prefix_chars 文件前缀字符

一般情况下,命令行参数是通过命令行直接输入的,也可以将它们存储在某个文件中,然后从文件中读取。在这种情况下,就需要定义存储参数值的文件的前缀引导符。例如:

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

注意,命令行参数在文件中的保存格式和它们的命令行直接输入的顺序保持一致。例如: [‘-f’, ‘foo’, ‘@args.txt’]和[‘-f’, ‘foo’, ‘-f’, ‘bar’]等价。
参数fromfile_prefix_chars默认为None,意味着直接在命令行进行输入。

.9. argument_default 参数的默认值

一般情况下,参数的默认值通过add_argument()方法或者set_default()方法来设定。有时候,我们可以通过参数argument_default设定ArgumentParser对象级别的默认值。例如,当argument_default=argparse.SUPPERSS时,调用parse_args()并不会生成相应的属性。

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

10. allow_abbrev 是否支持缩写

当命令行参数字符串比较长时,可以通过指定allow_abbrev=True来使用长字符串参数的缩写进行参数引用。
注意,缩写形式有时候会遇到名称冲突,即两个不同的参数的缩写一样。

$ 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

11. conflict_handler 冲突处理

参数confict_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:

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

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

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

Note that ArgumentParser objects only remove an action if all of its option strings are overridden. So, in the example above, the old -f/–foo action is retained as the -f action, because only the –foo option string was overridden.

12. add_help 是否显示帮助信息

默认情况下,ArgumentParser对象会自动生成-h/--help选项。
例如上面的myprogram.py文件:

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

在命令行输入-h/--help时,终端会输出以下信息:

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

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

可以设定add_help=False来取消帮助选项的自动生成。

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

optional arguments:
 --foo FOO  foo help

注意:帮助选项默认是使用-前缀,当prefix_chars设定为别的字符是,帮选项同样使用prefix_chars做为前缀。例如:

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

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

(5)add_argument()方法

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

通过add-argument()方法来给ArgumentParser对象添加新的命令行参数,参数的类型和相应的处理方法由不同的参数决定。

函数参数简介

  • name or flags - Either a name or a list of option strings, e.g. foo or -f, –foo.
    • 参数名或者参数标识
    • -的为可选参数(optional parameter)
    • 不带-的为必选参数(positional parametrer)。
  • action - The basic type of action to be taken when this argument is encountered at the command line.
    • 参数的处理方法
  • nargs - The number of command-line arguments that should be consumed.
    • 参数的数量
  • const - A constant value required by some action and nargs selections.
    • 参数的常量值
  • default - The value produced if the argument is absent from the command line.
    • 参数的默认值
  • type - The type to which the command-line argument should be converted.
    • 参数的数据类型
  • choices - A container of the allowable values for the argument.
    • 参数的取值范围
  • required - Whether or not the command-line option may be omitted (optionals only).
    • 参数是否可以忽略不写 ,仅对可选参数有效
  • help - A brief description of what the argument does.
    • 参数的说明信息
  • metavar - A name for the argument in usage messages.
    • 参数在说明信息usage中的名称
  • dest - The name of the attribute to be added to the object returned by
    parse_args().
    • 对象的属性名

函数参数的具体用法

1. name or flags

必选参数名或者可选参数标识符,它必须作为add_argument()方法的第一个参数。

# 可选参数
$ parser.add_argument('-f', '--foo')
# 必选参数
$ parser.add_argument('bar')

可选参数默认以-开始,其它的为必选参数。

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

2. action

ArgumentParser对象将命令行参数与动作联系在一起,这些动作可以对命令行参数进行适当的处理,最常用的动作就是在parse_args()返回的对象中添加一个属性。参数action说明了命令行参数应该如何被处理。
‘store’ - 存储参数的值。即在parser_args()方法返回的Namespace对象中添加属性,并设定它的值。它是action的默认值。

$ parser = argparse.ArgumentParser()
$ parser.add_argument('--foo')
$ parser.parse_args('--foo 1'.split())
Namespace(foo='1')

‘store_const’ - 将命令行参数的值设定为参数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’ - 将命令行参数的值设定为True或者False。

$ 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’ - 将命令行参数的值设定为一个列表,它可以用来处理同一个命令行参数出现多次的情况。

$ parser = argparse.ArgumentParser()
$ parser.add_argument('--foo', action='append')
$ parser.parse_args('--foo 1 --foo 2'.split())
Namespace(foo=['1', '2'])

‘append_const’ - 将命令行参数的值设定为一个列表,列表中的每个值都来自参数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=[<class 'str'>, <class 'int'>])

‘count’ - 命令行参数的出现次数。

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

‘help’ - 命令行参数的帮助信息。

‘version’ - 和参数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

可以新建一个类,来实现任何别的动作。最常用的方法是通过Action类生成一个子类,然后重写它的call方法和init方法。

$ 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. nargs

这个使用也不多,暂时不翻译了。
一般情况下,每个命令行参数只与一个动作相联系,参数nargs可以让多个参数与一个动作都联系,即一个动作可以处理多个参数:
N (an integer). N个参数被组合成一个列表

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

注意,当nargs=1进,它生成一个只包涵一个元素的列表。不使用nargs的情况下,参数只是一个简单的参数自身。

‘?’. 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:

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

下面的更复杂的用法:

$ 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. 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: too few arguments

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:

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

4. const

命令行参数的常量值,通常与append_const和store_const相关。

5. default

必选参数和可选的参数的默认值。

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

参数默认值的解析与参数的类型有关:

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

$ 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.:

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

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

type可以是任意Python支持的数据类型。

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

注意,choices列表中元素的类型应该与type批定的类型相兼容。

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

See the choices section for more details.

7. choices

说明命令行参数的取值范围,它的值一般是一个列表。

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

注意,choices列表中元素的类型应该与type批定的类型相兼容。

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

8. required

说明参数是否必须进行输入,只支持可选参数。

$ 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

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

help信息中使用格式化字符来避免重复的输入,例如:

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

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

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

因为help支持格式化字符,因此想要输出一个%,可以通过%%来进行转义。

$ 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

10. metavar

当ArgumentParser生成帮助信息时,它需要指定所需要参数的值。默认情况下,ArgumentParser使用dest的值作为每个参数的值。对于必选参数来说,直接使用dest的值 作为每个参数的值,对于可选参数来说,使用dest的值的大写形式作为每个参数的值。如下所示:

$ 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

可以通过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

注意,metavar只改变参数在帮助信息中的显示值,parse_args()返回的Namespace对象中的属性的名依然由dest决定。

$ 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

11. dest

绝大部分的ArgumentParser动作为parse_args()方法返回的Namespace对象的属性进行赋值,而属性的名称是由参数dest决定的。对于必选参数来说,dest默认等于必选参数的字面值。

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

对于可选参数来说,dest的值根据-s/--string来推定:优先选择长字符串,具体的方法是:把字符串两侧的-删掉,字符串中间的-转换为_

$ 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参数来设定属性的名称:

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

(6)parse_args()方法

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

parse_args()方法将命令行参数字符串转换为相应对象并赋值给Namespace对象的相应属性,默认返回一个Namespace对象。

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对象。

(7)The Namespace object

class argparse.Namespace

调用parse_args()的返回值是一个Namespace对象,它具有很多属性,每个属性都代表相应的命令行参数。

Namespace对象是一个非常简单的类,可以通过vars()将之转换成字典类型。例如:

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

另外还可以将ArgumentParser对象赋值给别的命令空间,而不是新建一个Namespace对象,例如:

$ class C:
...     pass
...
$ c = C()
$ parser = argparse.ArgumentParser()
$ parser.add_argument('--foo')
$ parser.parse_args(args=['--foo', 'BAR'], namespace=c)
$ c.foo
'BAR'
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

argparse模块 的相关文章

  • max_help_position 在 python argparse 库中不起作用

    嗨 同事 我有代码 max help position 是 2000 formatter class lambda prog argparse HelpFormatter prog max help position 2000 parser
  • argparse 子解析器整体帮助输出

    我的 argparse 在顶层只有 3 个标志 store true 其他所有内容都通过子解析器处理 当我跑步时myprog py help 输出像平常一样显示所有子命令的列表 sub1 sub2 sub3 sub4 所以 默认设置效果很好
  • 使用“argparse”而不是 sys.argv

    我的脚本当前使用sys argv检查提供给程序的输入文件 我正在尝试利用argparse相反 但我似乎无法让它发挥作用 我能够设置它并添加一个参数 但是当我解析一个参数并打印该解析的参数时 我得到一个名称空间 我怎样才能得到一个字符串 基本
  • 使用 argparse 输出来调用函数

    目前我的代码如下所示 它允许我解析我的程序脚本获取的多个参数 有没有更接近 最佳实践 的不同方法 我还没有看到实际使用输出的代码argparse 仅介绍如何设置 def useArguments x 0 while x lt 5 if x
  • Python 'sys.argv' 的最大参数数量有限制吗?

    我有一个Python脚本需要处理大量文件 为了解决 Linux 对可传递给命令的参数数量相对较小的限制 我使用find print0 with xargs 0 我知道另一种选择是使用 Python 的 glob 模块 但是当我有更高级的模块
  • 设置主函数测试的命令行参数

    我在 python 中有一个获取命令行参数的 main 函数 有没有办法让我为此函数编写 pytest 测试并在代码中定义参数 e g def main argparse code args other arg parser parse k
  • 如何为 argparse 设计面向对象的子解析器?

    Problem 我正在构建一个包含很多子命令的包管理器 我希望有一个类似于以下的类结构 class ListCommand def init self name list alias ls short description A usefu
  • 允许多个字符的 argparse 选项的缩写形式

    我正在检查这个蟒蛇文件 https github com rafaelpadilla Object Detection Metrics blob master pascalvoc py L178它似乎使用了一个包含 2 个字符的简短参数 p
  • argparse 和互斥组,每个组都有自己所需的设置

    我有一个程序需要有一个选项来测试服务器 ID 列表OR对服务器发出命令 这意味着 如果我发出 test 那么不需要其他任何东西 它对每台服务器运行全部测试并打印结果 但是 如果我不指定 test 那么它应该需要一些选项 例如 id and
  • 在 python 中调试 argparse

    我可以知道调试 argpars 函数的最佳实践是什么 假设我有一个 py 文件 test file py 其中包含以下几行 Script start import argparse import os parser argparse Arg
  • argparse —— 可选参数需要 2 个值或没有值

    我正在尝试为脚本创建一个可选参数 该参数可以不带任何值 也可以带 2 个值 仅此而已 你能使用 argparse 来完成这个任务吗 desired output script py a gt works script py a val1 g
  • 当不带任何参数调用脚本时,使用 Python argparse 显示帮助消息

    假设我有一个程序使用argparse处理命令行参数 选项 以下将打印 帮助 消息 myprogram h or myprogram help 但是 如果我在没有任何参数的情况下运行脚本 它不会执行任何操作 我想要它做的是在不带参数调用它时显
  • 如何检查特定的子解析器?

    如何检查特定的子解析器 import argparse if name main mainparser argparse ArgumentParser submainadder mainparser add subparsers title
  • Python argparse 值范围帮助消息外观

    我有一个程序的参数 它是 1 100 之间的整数 我只是不喜欢它在使用 argparse 时在 h 帮助消息中显示的方式 它实际上列出了 0 1 2 3 4 5 等 有什么方法可以改变这一点或以其他方式表示它吗 Thanks EDIT 对于
  • 如何使用 argparse 为参数创建可选值?

    我正在创建一个 python 脚本 我想要一个参数来控制作为输出获得的搜索结果数量 我目前已命名该参数 head 这是我希望它具有的功能 When head未在命令行中传递我希望它默认为一个值 在这种情况下 一个相当大的 比如 80 Whe
  • argparse 参数顺序

    我有一个小问题 I use argparse来解析我的论点 而且效果很好 为了获得参数 我这样做 p args parser parse args argv args dict p args get kwargs 但问题是p args是我不
  • 如何使用 argparse 将列表作为命令行参数传递?

    我正在尝试将列表作为参数传递给命令行程序 有没有一个argparse https docs python org 3 library argparse html将列表作为选项传递的选项 parser add argument l list
  • 命名空间、argparse 和用法

    这确实是几个问题 argparse 使用名称空间而不是字典有原因吗 假设我有一个班级 init self init method args The init method参数告诉 init function 我想用哪种方式初始化类 而arg
  • 一起使用 Argparse 和 Json

    我是 Python 初学者 我想知道 Argparse 和 JSON 是否可以一起使用 说 我有变量p q r 我可以将它们添加到 argparse 中 parser add argument p param1 help x variabl
  • 在解析器/子解析器的开头使用 argparse.REMAINDER

    我想实现一个 arg 解析器 它允许我将单元测试作为子命令之一运行 盲目地将参数传递给 unittest main 例如 foo py unittest args to pass to unittest main 以及其他子命令 foo p

随机推荐

  • ACM:n!的位数 :斯特林公式

    n 的位数 Time Limit 2000MS Memory Limit 65536K Description 针对每个非负整数n xff0c 计算其n 的位数 Input 输入数据中含有一些整数n xff08 0 n xff1c 10 7
  • java 自定义封装jdbc dao类

    手动封装jdbc和dao层 xff0c 体会其中的优点与不足 注 xff1a 本次采用的mysql数据库记得添加数据库的驱动包 Dbhelper类 xff1a 对jdbc进行封装 xff0c 采用单例模式 xff0c 不用每次都去连接数据库
  • Mybatis 二级缓存

    mybatis的缓存分为一级缓存和二级缓存 xff0c 缓存是用来缓存部分经常性访问的数据 xff0c 而不必每一次都跑到数据库获取或运算 xff0c 目标是提高系统的性能 一级缓存 对于每一个sqlSession 其中有一个HashMap
  • win10系统下CUDA示例项目编译出错MSB3721解决

    在win10系统下安装好cuda9 1后 xff0c 在VS2017中打开cuda corporation中的项目 xff0c 编译发现一直报错MSB3721 xff0c 无法导入windows h文件 xff0c 错误提示如下 xff1a
  • Wi-Fi放大器、中继、桥接和mesh组网的理解

    前言 针对路由器其实有很多的知识可以去学习 xff0c 包括路由器的路由功能 Wi Fi放大功能 中继 桥接和近几年才流行的mesh组网功能 xff0c 下面我将针对这几个功能说说我自己的通过相关资料的学习形成自己的一些理解 xff0c 强
  • MAC下虚拟机PD转换成win上可以用的vmware

    最近是需要mac机子转windows xff0c 然后之前在mac上面安装的虚拟机Ubuntu需要移到window上面使用 xff0c mac上面是使用Parallel Desktop安装的虚拟机 xff0c 在windows上面使用的是V
  • Openresty之实现http访问请求

    如果是第一次看这个文章 xff0c 可以先看下这篇openresty介绍性的文章 xff1a Openresty概述介绍 在openresty里面可能有访问其他服务的需求 xff0c 我们当时是需要定时去另外一个服务拉取一些配置信息 xff
  • 服务器系统缓存问题总结

    做后端的同学都知道缓存 xff0c 而且越是大的访问量的后端服务 xff0c 缓存的作用越是重要 最近看了些大佬的解说 xff0c 觉得说的很好 xff0c 在此将我理解的记录下来 xff0c 下面总结下后端缓存的一些知识点 顾名思义 xf
  • fwknop的安装和使用测试

    SPA名为单包授权 xff0c 是一种认证方法 xff0c 它是一种端口敲门的方法 xff0c 是之前早起端口敲门的升级版本 目的是为了隐藏服务端口 xff0c 防止DOS等其他网络攻击 xff0c 保证服务端的安全 SPA的具体定义这里不
  • win7连接共享“请检查名称的拼写.否则网络可能有问题”

    我他妈也是这个问题 xff0c 折腾了我好多天 xff0c 我的win7电脑突然就不能连接FTP的服务器 xff0c 然后我虚拟机的samba共享也连接不上 xff0c 终于找到解决办法 xff0c 别人的电脑没事 xff0c 就我的电脑有
  • Intel RealSense D435i + BundleFusion 实现实时三维建图

    内容概览 摘要操作环境RealSense D435i 介绍BundleFusion工程环境配置安装 RealSense SDKRealSense SDK 本地环境配置BundleFusion 工程属性表相机类型设置修改 GlobalAppS
  • CrazePony与计算机视觉

    大家好 我是CrazePony的视觉攻城狮 Ziv Lin 我擅长的部分是计算机视觉和嵌入式编程 非常荣幸地能够加入CrazePony团队 众所周知 一个飞行器想要做到悬停的话 xff0c 必须引入一个位置环进行反馈 xff0c 也就是说需
  • Mac OS系统下kernel_task占用大量CPU资源导致系统卡顿

    来这里找解决方案的童鞋 xff0c 如果你的机器还没过保 果断去找官修 xff0c 忽略这篇文章 xff01 心急的童鞋直接看目录 xff0c 有传送门 xff01 但是仔细看文章可能有奇效 xff01 最近博客更新进度严重滞后 因为我遭遇
  • linux环境打包python工程为可执行程序

    本次又个需求 xff0c 在ubuntu上面开发的python代码程序需要打包成一个可执行程序然后交付给甲方 xff0c 因为不能直接给源码给甲方 xff0c 所以寻找方法将python开发的源码打包成一个可执行程序 xff0c 注意是打包
  • windows下python调用海康威视网络摄像头sdk

    本文参考以下博文加自己的实践 xff0c 发现有些步骤是不必要的 xff0c 例如不需要为opencv等第三方库指定路径 运行环境 xff1a 准备工作 1 海康SDK下载 2 下载安装vcpkg 3 安装Swig 4 下载OpenCV s
  • Apollo代码学习(七)—MPC与LQR比较

    Apollo代码学习 MPC与LQR比较 前言研究对象状态方程工作时域目标函数求解方法 前言 Apollo中用到了PID MPC和LQR三种控制器 xff0c 其中 xff0c MPC和LQR控制器在状态方程的形式 状态变量的形式 目标函数
  • 27 | Ubuntu18.04.5 安装python3.7及卸载

    目录 1 前期准备1 1安装所需依赖 重要 1 2 配置Python版本切换1 2 1 查看候选列表中已有的Python版本1 2 2 添加 python amp python3 指向选择1 2 3 查看候选列表中已有的Python版本1
  • opencv库作为第三方库

    在编译一个依赖opencv库的库时 xff0c 报出以下错误 xff1a undefined reference to symbol ZN2cv6imreadERKNS 6StringEi libopencv core so 2 4 err
  • 银河麒麟V10系统NetworkManager服务启动失败的解决方法

    目录 一 NetworkManger网络服务启动失败 二 故障定位过程 xff08 一 xff09 重装NetworkManager未解决 xff08 二 xff09 重装openssl未解决 三 解决方案 xff08 一 xff09 修改
  • argparse模块

    1模块简介2Example3argparse三个主要函数 parser argparseArgumentParserparseradd argumentargs parserparse args 4ArgumentParser对象 对象参数