python模块-argparse、optparse

摘要

本文记录一些python中optparse和argparse模块的常用方法

optparse

optparse模块主要用来为脚本传递命令参数,采用预先定义好的选项来解析命令行参数。

首先需要引入optparser模块,然后执行初始化,实例化一个OptionParser对象(可以带参,也可以不带参数),再为命令行添加选项

1
2
3
4
5
6
7
8
import optparse
usage="python %prog -H <target host> -p/-P <target ports>" #用于显示帮助信息
parser=optparse.OptionParser(usage) #创建对象实例
parser.add_option('-H',dest='Host',type='string',help='target host') ##需要的命令行参数
parser.add_option('-P','-p',dest='Ports',type='string',help='target ports' default="20,21") ## -p/-P 都可以
(options,args)=parser.parse_args()
print(options.Host)
print(options.Ports)
1
2
3
4
5
6
7
8
9
10

from optparse import OptionParser
usage="show something usefull
-- for example: how to use this program"
parser = OptionParser(usage) #带参的话会把参数变量的内容作为帮助信息输出
parser.add_option("-f","--file",dest="filename",help="read picture from File",metavar="FILE",action = "store",type="string")
parser.add_option("-s","--save",dest="save_mold",help="save image to file or not",default = True)
(options,args)=parser.parse_args()
print options.filename
print options.save_mold
1
2
3
4
5
6
7
8
9
10
各个参数的含义:

dest:用于保存输入的临时变量,其值通过options的属性进行访问,存储的内容是dest之前输入的参数,多个参数用逗号分隔
type: 用于检查命令行参数传入的参数的数据类型是否符合要求,有 string,int,float 等类型
help:用于生成帮助信息
default: 给dest的默认值,如果用户没有在命令行参数给dest分配值,则使用默认值
action: 用于指导程序在遇到命令行参数时候该如何处理,有三种值可选: store,store_false和store_true,默认值是store
  store:读取参数,如果参数类型符合type的要求,则将参数值传递给dest变量,作为options的一个属性供使用。
  store_true/store_false: 一般作为一个标记使用,分别设置dest变量的值为True和False
metavar: 占位字符串,用于在输出帮助信息时,代替当前命令选项的附加参数的值进行输出,只在帮助信息里有用,注意其和default的区别

argparse

1
2
3
4
5
6
7
8
9
10
11
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))
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
$ 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

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

使用步骤

1
2
3
4
5
6
7
8
9
10
# 导入模块
1:import argparse
# 创建解析对象
2:parser = argparse.ArgumentParser()
# 添加参数项
3:parser.add_argument()
# 解析参数项
4:args = parser.parse_args()
# 使用
5:args.xxx

ArgumentParser对象参数解析

这部分并非重点内容,只要知道前几个参数的用法即可

1
2
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)
Create a new ArgumentParser object. 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: 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
  • 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)
  • 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)
  • allow_abbrev - Allows long options to be abbreviated if the abbreviation is unambiguous. (default: True)

prog

prog参数相当于python中的sys.argv[0],默认为当前执行脚本的脚本名,可以进行自定义。

1
parser = argparse.ArgumentParser(prog='myprogram')

usage

usage参数用来提示参数项使用方式,默认会自动生成,可以进行自定义

1
parser = argparse.ArgumentParser(prog='PROG', usage='%(prog)s [options]')

description

description用来添加帮助菜单中的描述信息,默认为空。

1
parser = argparse.ArgumentParser(description='A foo that bars')

epilog

epilog用来添加帮助菜单中的程序结尾描述信息,默认为空。

1
2
3
parser = argparse.ArgumentParser(
description='A foo that bars',
epilog="And that's how you'd foo a bar")

parents

有时候,有些参数项可能作为一组通用参数项来分享给不通的程序,而无需重复的来定义这些参数项,这时候就可以用到parents参数,子对象会继承parents的所有参数项。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# 首先定义一个用来继承的parents,需要关闭add_help参数
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)

formatter_class

使用这个参数的几个选项可以把帮助信息中的格式进行修改。

RawDescriptionHelpFormatter

定制描述信息缩进格式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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
'''))

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

ArgumentDefaultsHelpFormatter

自动增加defaults值显示

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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!')

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

用参数类型来替代帮助信息

1
2
3
4
5
6
7
8
9
10
11
12
13
14
parser = argparse.ArgumentParser(
prog='PROG',
formatter_class=argparse.MetavarTypeHelpFormatter)
parser.add_argument('--foo', type=int)
parser.add_argument('bar', type=float)

usage: PROG [-h] [--foo int] float

positional arguments:
float

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

prefix_chars

prefix_chars可以定义选项参数的前缀,默认为[-/–]。

1
2
3
parser = argparse.ArgumentParser(prog='PROG', prefix_chars='-+')
parser.add_argument('+f')
parser.add_argument('++bar')

fromfile_prefix_chars

fromfile_prefix_chars可以指定文件为添加参数项值。

1
2
3
4
5
6
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')

argument_default

正常来说给一个参数项设定默认值可以通过add_argument()或者set_defaults()方法来添加,但是只能对每个参数单独制定,但是使用argument_default参数可以给所有没有默认值的参数一个默认值。

1
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. 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. For example, to globally suppress attribute creation on parse_args() calls, we supply argument_default=SUPPRESS:

这个参数没看懂,贴一下官方文档吧

1
parser = argparse.ArgumentParser(argument_default=argparse.SUPPRESS)

allow_abbrev

通常情况,当你传递一个参数项的时候,可以传递一个缩写的参数项,allow_abbrev参数可以关闭缩写参数项(python3)。

1
2
3
4
5
6
7
8
9
10
11
12
13
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

# 不关闭的情况
parser.parse_args(['--foob'])
Namespace(foobar=True, foonley=True)
parser.parse_args(['--foon'])
Namespace(foobar=False, foonley=False)

conflict_handler

正常来说你指定了一个参数项,是不能在此指定来覆盖已经指定的参数项的,conflict_handler可以开放这个功能。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
>>> 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


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

add_help

可以用这个参数来关闭默认的help信息,然后自定义。关闭了之后还是可以用parser.print_help() 来打印帮助信息的。

1
parser = argparse.ArgumentParser(prog='PROG', add_help=False)

add_argument方法参数解析

这个才是本文的重点

1
2
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.
  • 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.
  • dest - The name of the attribute to be added to the object returned by parse_args().

name or flags

选项名、参数名、标签。分为两种

  • 带前缀:-f -foo ,参数项
  • 不带前缀:bar,位置变量
1
2
parser.add_argument('-f', '--foo')
parser.add_argument('bar')

action

action用来定义添加参数项的属性类型。

store

默认类型,只是用来存储一个值。

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

store_const

和const参数一起使用,存储一个常量。

1
2
3
4
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo', action='store_const', const=42)
>>> parser.parse_args(['--foo'])
Namespace(foo=42)

store_true & store_false

存储常量的特殊类型,存储布尔值。

1
2
3
4
5
6
>>> 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

追加属性,参数项可以多次出现,多次值会追加成一个list。

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

append_const

和const一起使用,用来追加常量。

1
2
3
4
5
>>> 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

数量统计,参数项可以多次出现,记录出现次数为选项的值。

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

help

自定义help选项的时候使用的。

version

创建版本信息使用。

1
2
3
4
5
>>> 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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
>>> 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')

nargs

这个参数用来规定添加的参数项对应参数值的个数。

  • 1、2、3…
  • ‘?’ 0或1个
  • ‘+’ 至少一个
  • ‘*’ 0到多个
  • argparse.REMAINDER ???
1
2
3
4
5
>>> parser.add_argument('--foo', nargs=2)
>>> parser.add_argument('bar', nargs=1)
>>> parser.add_argument('--foo', nargs='?', const='c', default='d')
>>> parser.add_argument('--bar', nargs='*')
>>> parser.add_argument('foo', nargs='+')

const

设定一个常量的值,与store_const 和append_const 一起使用。

default

设定一个默认值

type

设定参数项的值的类型。默认str类型,可以int、float等。

1
2
3
4
5
6
7
8
9
10
>>> 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)

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

可以自定义类型

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
>>> 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参数来定义参数值范围

1
2
3
4
5
6
7
>>> 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)

choices

用来限制参数值的选定范围

1
2
parser.add_argument('move', choices=['rock', 'paper', 'scissors'])
parser.add_argument('door', type=int, choices=range(1, 4))

required

设定这个属性可是让参数项变成必选项。

1
2
3
4
5
6
7
>>> 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

help

用来添加参数项的帮助信息

metavar

打印帮助信息时,参数项的演示值。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
>>> 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


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

dest

可以用来指定参数项名字。

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

parse_args()方法参数说明

用来解析参数项,这部分不是重点,看看就好。

Option value syntax

参数项使用方式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
>>> 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)

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

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

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

错误输出,参数项或参数值不符合规定时会提示错误信息

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
>>> 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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
>>> 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

Argument abbreviations (prefix matching)

1
2
3
4
5
6
7
8
9
10
>>> 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

Beyond sys.argv

1
2
3
4
5
6
7
8
9
10
11
>>> 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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo')
>>> args = parser.parse_args(['--foo', 'BAR'])
>>> vars(args)
{'foo': 'BAR'}



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

其他方法

这部分内容有一些东西还是比较有用的

Sub-commands

子参数项,可以设置子参数项的参数项。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
>>> # 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)


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

positional arguments:
{a,b} sub-command help
a a help
b b help

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

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

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

optional arguments:
-h, --help show this help message and exit
--baz {X,Y,Z} baz help

还可以设置单独的标题和描述信息

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
>>> 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} ...

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

subcommands:
valid subcommands

{foo,bar} additional help

可以添加别名

1
2
3
4
5
6
>>> 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')
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
>>> # 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))
1
2
3
4
5
6
7
8
>>> 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')

FileType objects

1
2
3
4
5
6
7
8
9
10
>>> 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'>)

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

Argument groups

参数项组

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
>>> 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

Mutual exclusion

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
>>> 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

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

Parser defaults

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
>>> 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)


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


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

Printing help

1
2
3
4
5
6
7
8
9
10
11
12
13
ArgumentParser.print_usage(file=None)
Print a brief description of how the ArgumentParser should be invoked on the command line. If file is None, sys.stdout is assumed.

ArgumentParser.print_help(file=None)
Print a help message, including the program usage and information about the arguments registered with the ArgumentParser. If file is None, sys.stdout is assumed.

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.format_help()
Return a string containing a help message, including the program usage and information about the arguments registered with the ArgumentParser.

Partial parsing

1
2
3
4
5
>>> 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'])

Customizing file parsing

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

Exiting methods

1
2
3
4
5
ArgumentParser.exit(status=0, message=None)
This method terminates the program, exiting with the specified status and, if given, it prints a message before that.

ArgumentParser.error(message)
This method prints a usage message including the message to the standard error and terminates the program with a status code of 2.
Donate