argparse --- 命令行選項、參數和子命令解析器?

3.2 新版功能.

源代碼: Lib/argparse.py


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:

parser = argparse.ArgumentParser(
                    prog = 'ProgramName',
                    description = 'What the program does',
                    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:

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

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

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

示例?

以下代碼是一個(gè) Python 程序,它獲取一個(gè)整數列表并計算總和或者最大值:

import argparse

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

args = parser.parse_args()
print(args.accumulate(args.integers))

Assuming the 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:

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

Process some integers.

positional arguments:
 N           an integer for the accumulator

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

當使用適當的參數運行時(shí),它會(huì )輸出命令行傳入整數的總和或者最大值:

$ python prog.py 1 2 3 4
4

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

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

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

以下部分將引導你完成這個(gè)示例。

創(chuàng )建一個(gè)解析器?

使用 argparse 的第一步是創(chuàng )建一個(gè) ArgumentParser 對象:

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

ArgumentParser 對象包含將命令行解析成 Python 數據類(lèi)型所需的全部信息。

添加參數?

給一個(gè) ArgumentParser 添加程序參數信息是通過(guò)調用 add_argument() 方法完成的。通常,這些調用指定 ArgumentParser 如何獲取命令行字符串并將其轉換為對象。這些信息在 parse_args() 調用時(shí)被存儲和使用。例如:

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

Later, calling parse_args() will return an object with two attributes, integers and accumulate. 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 通過(guò) parse_args() 方法解析參數。它將檢查命令行,把每個(gè)參數轉換為適當的類(lèi)型然后調用相應的操作。在大多數情況下,這意味著(zhù)一個(gè)簡(jiǎn)單的 Namespace 對象將從命令行解析出的屬性構建:

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

在腳本中,通常 parse_args() 會(huì )被不帶參數調用,而 ArgumentParser 將自動(dòng)從 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)?

創(chuàng )建一個(gè)新的 ArgumentParser 對象。所有的參數都應當作為關(guān)鍵字參數傳入。每個(gè)參數在下面都有它更詳細的描述,但簡(jiǎn)而言之,它們是:

  • prog - The name of the program (default: os.path.basename(sys.argv[0]))

  • usage - 描述程序用途的字符串(默認值:從添加到解析器的參數生成)

  • description - 在參數幫助文檔之前顯示的文本(默認值:無(wú))

  • epilog - 在參數幫助文檔之后顯示的文本(默認值:無(wú))

  • parents - 一個(gè) ArgumentParser 對象的列表,它們的參數也應包含在內

  • formatter_class - 用于自定義幫助文檔輸出格式的類(lèi)

  • prefix_chars - 可選參數的前綴字符集合(默認值: '-')

  • fromfile_prefix_chars - 當需要從文件中讀取其他參數時(shí),用于標識文件名的前綴字符集合(默認值: None

  • argument_default - 參數的全局默認值(默認值: None

  • conflict_handler - 解決沖突選項的策略(通常是不必要的)

  • add_help - 為解析器添加一個(gè) -h/--help 選項(默認值: True

  • allow_abbrev - 如果縮寫(xiě)是無(wú)歧義的,則允許縮寫(xiě)長(cháng)選項 (默認值:True

  • exit_on_error - 決定當錯誤發(fā)生時(shí)是否讓 ArgumentParser 附帶錯誤信息退出。 (默認值: True)

在 3.5 版更改: 增加了 allow_abbrev 參數。

在 3.8 版更改: 在之前的版本中,allow_abbrev 還會(huì )禁用短旗標分組,例如 -vv 表示為 -v -v。

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

以下部分描述這些參數如何使用。

prog?

默認情況下,ArgumentParser 對象使用 sys.argv[0] 來(lái)確定如何在幫助消息中顯示程序名稱(chēng)。這一默認值幾乎總是可取的,因為它將使幫助消息與從命令行調用此程序的方式相匹配。例如,對于有如下代碼的名為 myprogram.py 的文件:

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

該程序的幫助信息將顯示 myprogram.py 作為程序名稱(chēng)(無(wú)論程序從何處被調用):

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

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

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

要更改這樣的默認行為,可以使用 prog= 參數為 ArgumentParser 指定另一個(gè)值:

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

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

需要注意的是,無(wú)論是從 sys.argv[0] 或是從 prog= 參數確定的程序名稱(chēng),都可以在幫助消息里通過(guò) %(prog)s 格式說(shuō)明符來(lái)引用。

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

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

usage?

默認情況下,ArgumentParser 根據它包含的參數來(lái)構建用法消息:

>>>
>>> parser = argparse.ArgumentParser(prog='PROG')
>>> parser.add_argument('--foo', nargs='?', help='foo help')
>>> parser.add_argument('bar', nargs='+', help='bar help')
>>> parser.print_help()
usage: PROG [-h] [--foo [FOO]] bar [bar ...]

positional arguments:
 bar          bar help

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

可以通過(guò) usage= 關(guān)鍵字參數覆蓋這一默認消息:

>>>
>>> parser = argparse.ArgumentParser(prog='PROG', usage='%(prog)s [options]')
>>> parser.add_argument('--foo', nargs='?', help='foo help')
>>> parser.add_argument('bar', nargs='+', help='bar help')
>>> parser.print_help()
usage: PROG [options]

positional arguments:
 bar          bar help

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

在用法消息中可以使用 %(prog)s 格式說(shuō)明符來(lái)填入程序名稱(chēng)。

description?

大多數對 ArgumentParser 構造方法的調用都會(huì )使用 description= 關(guān)鍵字參數。 這個(gè)參數簡(jiǎn)要描述這個(gè)程序做什么以及怎么做。 在幫助消息中,這個(gè)描述會(huì )顯示在命令行用法字符串和各種參數的幫助消息之間:

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

A foo that bars

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

在默認情況下,description 將被換行以便適應給定的空間。如果想改變這種行為,見(jiàn) formatter_class 參數。

epilog?

一些程序喜歡在 description 參數后顯示額外的對程序的描述。這種文字能夠通過(guò)給 ArgumentParser:: 提供 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

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

And that's how you'd foo a bar

description 參數一樣,epilog= text 在默認情況下會(huì )換行,但是這種行為能夠被調整通過(guò)提供 formatter_class 參數給 ArgumentParse.

parents?

有些時(shí)候,少數解析器會(huì )使用同一系列參數。 單個(gè)解析器能夠通過(guò)提供 parents= 參數給 ArgumentParser 而使用相同的參數而不是重復這些參數的定義。parents= 參數使用 ArgumentParser 對象的列表,從它們那里收集所有的位置和可選的行為,然后將這寫(xiě)行為加到正在構建的 ArgumentParser 對象。

>>>
>>> parent_parser = argparse.ArgumentParser(add_help=False)
>>> parent_parser.add_argument('--parent', type=int)

>>> foo_parser = argparse.ArgumentParser(parents=[parent_parser])
>>> foo_parser.add_argument('foo')
>>> foo_parser.parse_args(['--parent', '2', 'XXX'])
Namespace(foo='XXX', parent=2)

>>> bar_parser = argparse.ArgumentParser(parents=[parent_parser])
>>> bar_parser.add_argument('--bar')
>>> bar_parser.parse_args(['--bar', 'YYY'])
Namespace(bar='YYY', parent=None)

請注意大多數父解析器會(huì )指定 add_help=False . 否則, ArgumentParse 將會(huì )看到兩個(gè) -h/--help 選項(一個(gè)在父參數中一個(gè)在子參數中)并且產(chǎn)生一個(gè)錯誤。

備注

你在通過(guò)``parents=`` 傳遞解析器之前必須完全初始化它們。 如果你在子解析器之后改變父解析器,這些改變將不會(huì )反映在子解析器上。

formatter_class?

ArgumentParser 對象允許通過(guò)指定備用格式化類(lèi)來(lái)自定義幫助格式。目前,有四種這樣的類(lèi)。

class argparse.RawDescriptionHelpFormatter?
class argparse.RawTextHelpFormatter?
class argparse.ArgumentDefaultsHelpFormatter?
class argparse.MetavarTypeHelpFormatter?

RawDescriptionHelpFormatterRawTextHelpFormatter 在正文的描述和展示上給與了更多的控制。ArgumentParser 對象會(huì )將 descriptionepilog 的文字在命令行中自動(dòng)換行。

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

this description was indented weird but that is okay

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

likewise for this epilog whose whitespace will be cleaned up and whose words
will be wrapped across a couple lines

RawDescriptionHelpFormatterformatter_class= 表示 descriptionepilog 已經(jīng)被正確的格式化了,不能在命令行中被自動(dòng)換行:

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

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

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

RawTextHelpFormatter 保留所有種類(lèi)文字的空格,包括參數的描述。然而,多重的新行會(huì )被替換成一行。如果你想保留多重的空白行,可以在新行之間加空格。

ArgumentDefaultsHelpFormatter 自動(dòng)添加默認的值的信息到每一個(gè)幫助信息的參數中:

>>>
>>> parser = argparse.ArgumentParser(
...     prog='PROG',
...     formatter_class=argparse.ArgumentDefaultsHelpFormatter)
>>> parser.add_argument('--foo', type=int, default=42, help='FOO!')
>>> parser.add_argument('bar', nargs='*', default=[1, 2, 3], help='BAR!')
>>> parser.print_help()
usage: PROG [-h] [--foo FOO] [bar ...]

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

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

MetavarTypeHelpFormatter 為它的值在每一個(gè)參數中使用 type 的參數名當作它的顯示名(而不是使用通常的格式 dest ):

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

positional arguments:
  float

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

prefix_chars?

許多命令行會(huì )使用 - 當作前綴,比如 -f/--foo。如果解析器需要支持不同的或者額外的字符,比如像 +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')

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:

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

從文件讀取的參數在默認情況下必須一個(gè)一行(但是可參見(jiàn) convert_arg_line_to_args())并且它們被視為與命令行上的原始文件引用參數位于同一位置。所以在以上例子中,['-f', 'foo', '@args.txt'] 的表示和 ['-f', 'foo', '-f', 'bar'] 的表示相同。

fromfile_prefix_chars= 參數默認為 None,意味著(zhù)參數不會(huì )被當作文件對待。

argument_default?

一般情況下,參數默認會(huì )通過(guò)設置一個(gè)默認到 add_argument() 或者調用帶一組指定鍵值對的 ArgumentParser.set_defaults() 方法。但是有些時(shí)候,為參數指定一個(gè)普遍適用的解析器會(huì )更有用。這能夠通過(guò)傳輸 argument_default= 關(guān)鍵詞參數給 ArgumentParser 來(lái)完成。舉個(gè)栗子,要全局禁止在 parse_args() 中創(chuàng )建屬性,我們提供 argument_default=SUPPRESS:

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

allow_abbrev?

正常情況下,當你向 ArgumentParserparse_args() 方法傳入一個(gè)參數列表時(shí),它會(huì ) recognizes abbreviations。

這個(gè)特性可以設置 allow_abbrevFalse 來(lái)關(guān)閉:

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

3.5 新版功能.

conflict_handler?

ArgumentParser 對象不允許在相同選項字符串下有兩種行為。默認情況下, ArgumentParser 對象會(huì )產(chǎn)生一個(gè)異常如果去創(chuàng )建一個(gè)正在使用的選項字符串參數。

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

有些時(shí)候(例如:使用 parents),重寫(xiě)舊的有相同選項字符串的參數會(huì )更有用。為了產(chǎn)生這種行為, 'resolve' 值可以提供給 ArgumentParserconflict_handler= 參數:

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

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

注意 ArgumentParser 對象只能移除一個(gè)行為如果它所有的選項字符串都被重寫(xiě)。所以,在上面的例子中,舊的 -f/--foo 行為 回合 -f 行為保持一樣, 因為只有 --foo 選項字符串被重寫(xiě)。

add_help?

默認情況下,ArgumentParser 對象添加一個(gè)簡(jiǎn)單的顯示解析器幫助信息的選項。舉個(gè)栗子,考慮一個(gè)名為 myprogram.py 的文件包含如下代碼:

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

如果 -h or --help 在命令行中被提供, 參數解析器幫助信息會(huì )打印:

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

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

有時(shí)候可能會(huì )需要關(guān)閉額外的幫助信息。這可以通過(guò)在 ArgumentParser 中設置 add_help= 參數為 False 來(lái)實(shí)現。

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

options:
 --foo FOO  foo help

幫助選項一般為 -h/--help。如果 prefix_chars= 被指定并且沒(méi)有包含 - 字符,在這種情況下, -h --help 不是有效的選項。此時(shí), prefix_chars 的第一個(gè)字符將用作幫助選項的前綴。

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

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

exit_on_error?

正常情況下,當你向 ArgumentParserparse_args() 方法傳入一個(gè)無(wú)效的參數列表時(shí),它將會(huì )退出并發(fā)出錯誤信息。

如果用戶(hù)想要手動(dòng)捕獲錯誤,可通過(guò)將 exit_on_error 設為 False 來(lái)啟用該特性:

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

3.9 新版功能.

add_argument() 方法?

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

定義單個(gè)的命令行參數應當如何解析。每個(gè)形參都在下面有它自己更多的描述,長(cháng)話(huà)短說(shuō)有:

  • name or flags - 一個(gè)命名或者一個(gè)選項字符串的列表,例如 foo-f, --foo。

  • action - 當參數在命令行中出現時(shí)使用的動(dòng)作基本類(lèi)型。

  • nargs - 命令行參數應當消耗的數目。

  • const - 被一些 actionnargs 選擇所需求的常數。

  • default - 當參數未在命令行中出現并且也不存在于命名空間對象時(shí)所產(chǎn)生的值。

  • type - 命令行參數應當被轉換成的類(lèi)型。

  • choices - 可用的參數的容器。

  • required - 此命令行選項是否可省略 (僅選項可用)。

  • help - 一個(gè)此選項作用的簡(jiǎn)單描述。

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

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

而位置參數可以這么創(chuàng )建:

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

parse_args() 被調用,選項會(huì )以 - 前綴識別,剩下的參數則會(huì )被假定為位置參數:

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

action?

ArgumentParser 對象將命令行參數與動(dòng)作相關(guān)聯(lián)。這些動(dòng)作可以做與它們相關(guān)聯(lián)的命令行參數的任何事,盡管大多數動(dòng)作只是簡(jiǎn)單的向 parse_args() 返回的對象上添加屬性。action 命名參數指定了這個(gè)命令行參數應當如何處理。供應的動(dòng)作有:

  • 'store' - 存儲參數的值。這是默認的動(dòng)作。例如:

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

    >>>
    >>> parser = argparse.ArgumentParser()
    >>> parser.add_argument('--foo', action='store_const', const=42)
    >>> parser.parse_args(['--foo'])
    Namespace(foo=42)
    
  • 'store_true' and 'store_false' - 這些是 'store_const' 分別用作存儲 TrueFalse 值的特殊用例。另外,它們的默認值分別為 FalseTrue。例如:

    >>>
    >>> 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. It is useful to allow an option to be specified multiple times. If the default value is non-empty, the default elements will be present in the parsed value for the option, with any values from the command line appended after those default values. Example usage:

    >>>
    >>> parser = argparse.ArgumentParser()
    >>> parser.add_argument('--foo', action='append')
    >>> parser.parse_args('--foo 1 --foo 2'.split())
    Namespace(foo=['1', '2'])
    
  • 'append_const' - This stores a list, and appends the value specified by the const keyword argument to the list; note that the const keyword argument defaults to None. The 'append_const' action is typically useful when multiple arguments need to store constants to the same list. For example:

    >>>
    >>> parser = argparse.ArgumentParser()
    >>> parser.add_argument('--str', dest='types', action='append_const', const=str)
    >>> parser.add_argument('--int', dest='types', action='append_const', const=int)
    >>> parser.parse_args('--str --int'.split())
    Namespace(types=[<class 'str'>, <class 'int'>])
    
  • 'count' - 計算一個(gè)關(guān)鍵字參數出現的數目或次數。例如,對于一個(gè)增長(cháng)的詳情等級來(lái)說(shuō)有用:

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

    請注意,default 將為 None,除非顯式地設為 0。

  • 'help' - 打印所有當前解析器中的選項和參數的完整幫助信息,然后退出。默認情況下,一個(gè) help 動(dòng)作會(huì )被自動(dòng)加入解析器。關(guān)于輸出是如何創(chuàng )建的,參與 ArgumentParser。

  • 'version' - 期望有一個(gè) 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
    
  • 'extend' - 這會(huì )存儲一個(gè)列表,并將每個(gè)參數值加入到列表中。 示例用法:

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

    3.8 新版功能.

你還可以通過(guò)傳遞一個(gè) Action 子類(lèi)或實(shí)現相同接口的其他對象來(lái)指定任意操作。 BooleanOptionalActionargparse 中可用并會(huì )添加對布爾型操作例如 --foo--no-foo 的支持:

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

3.9 新版功能.

創(chuàng )建自定義動(dòng)作的推薦方式是擴展 Action,重載 __call__ 方法以及可選的 __init__format_usage 方法。

一個(gè)自定義動(dòng)作的例子:

>>>
>>> class FooAction(argparse.Action):
...     def __init__(self, option_strings, dest, nargs=None, **kwargs):
...         if nargs is not None:
...             raise ValueError("nargs not allowed")
...         super().__init__(option_strings, dest, **kwargs)
...     def __call__(self, parser, namespace, values, option_string=None):
...         print('%r %r %r' % (namespace, values, option_string))
...         setattr(namespace, self.dest, values)
...
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo', action=FooAction)
>>> parser.add_argument('bar', action=FooAction)
>>> args = parser.parse_args('1 --foo 2'.split())
Namespace(bar=None, foo=None) '1' None
Namespace(bar='1', foo=None) '2' '--foo'
>>> args
Namespace(bar='1', foo='2')

更多描述,見(jiàn) Action。

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. See also Specifying ambiguous arguments. The supported values are:

  • N (一個(gè)整數)。命令行中的 N 個(gè)參數會(huì )被聚集到一個(gè)列表中。 例如:

    >>>
    >>> 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 會(huì )產(chǎn)生一個(gè)單元素列表。這和默認的元素本身是不同的。

  • '?'。如果可能的話(huà),會(huì )從命令行中消耗一個(gè)參數,并產(chǎn)生一個(gè)單一項。如果當前沒(méi)有命令行參數,則會(huì )產(chǎn)生 default 值。注意,對于選項,有另外的用例 - 選項字符串出現但沒(méi)有跟隨命令行參數,則會(huì )產(chǎn)生 const 值。一些說(shuō)用用例:

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

    nargs='?' 的一個(gè)更普遍用法是允許可選的輸入或輸出文件:

    >>>
    >>> 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'>)
    
  • '*'。所有當前命令行參數被聚集到一個(gè)列表中。注意通過(guò) nargs='*' 來(lái)實(shí)現多個(gè)位置參數通常沒(méi)有意義,但是多個(gè)選項是可能的。例如:

    >>>
    >>> 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'])
    
  • '+'。和 '*' 類(lèi)似,所有當前命令行參數被聚集到一個(gè)列表中。另外,當前沒(méi)有至少一個(gè)命令行參數時(shí)會(huì )產(chǎn)生一個(gè)錯誤信息。例如:

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

如果不提供 nargs 命名參數,則消耗參數的數目將被 action 決定。通常這意味著(zhù)單一項目(非列表)消耗單一命令行參數。

const?

add_argument() 的``const`` 參數用于保存不從命令行中讀取但被各種 ArgumentParser 動(dòng)作需求的常數值。最常用的兩例為:

  • 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. If const is not provided to add_argument(), it will receive a default value of None.

  • 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 to be None instead. See the nargs description for examples.

在 3.11 版更改: const=None by default, including when action='append_const' or action='store_const'.

默認值?

所有選項和一些位置參數可能在命令行中被忽略。add_argument() 的命名參數 default,默認值為 None,指定了在命令行參數未出現時(shí)應當使用的值。對于選項, default 值在選項未在命令行中出現時(shí)使用:

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

如果目標命名空間已經(jīng)有一個(gè)屬性集,則 default 動(dòng)作不會(huì )覆蓋它:

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

如果 default 值是一個(gè)字符串,解析器解析此值就像一個(gè)命令行參數。特別是,在將屬性設置在 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)

對于 nargs 等于 ?* 的位置參數, default 值在沒(méi)有命令行參數出現時(shí)使用。

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

提供 default=argparse.SUPPRESS 導致命令行參數未出現時(shí)沒(méi)有屬性被添加:

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

type -- 類(lèi)型?

默認情況下,解析器會(huì )將命令行參數當作簡(jiǎn)單字符串讀入。 然而,命令行字符串經(jīng)常應當被解讀為其他類(lèi)型,例如 floatint。 add_argument()type 關(guān)鍵字允許執行任何必要的類(lèi)型檢查和類(lèi)型轉換。

如果 type 關(guān)鍵字使用了 default 關(guān)鍵字,則類(lèi)型轉換器僅會(huì )在默認值為字符串時(shí)被應用。

傳給 type 的參數可以是任何接受單個(gè)字符串的可調用對象。 如果函數引發(fā)了 ArgumentTypeError, TypeErrorValueError,異常會(huì )被捕獲并顯示經(jīng)過(guò)良好格式化的錯誤消息。 其他異常類(lèi)型則不會(huì )被處理。

普通內置類(lèi)型和函數可被用作類(lèi)型轉換器:

import argparse
import pathlib

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

用戶(hù)自定義的函數也可以被使用:

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

不建議將 bool() 函數用作類(lèi)型轉換器。 它所做的只是將空字符串轉為 False 而將非空字符串轉為 True。 這通常不是用戶(hù)所想要的。

通常,type 關(guān)鍵字是僅應被用于只會(huì )引發(fā)上述三種被支持的異常的簡(jiǎn)單轉換的便捷選項。 任何具有更復雜錯誤處理或資源管理的轉換都應當在參數被解析后由下游代碼來(lái)完成。

For example, JSON or YAML conversions have complex error cases that require better reporting than can be given by the type keyword. A JSONDecodeError would not be well formatted and a FileNotFound exception would not be handled at all.

即使 FileType 在用于 type 關(guān)鍵字時(shí)也存在限制。 如果一個(gè)參數使用了 FileType 并且有一個(gè)后續參數出錯,則將報告一個(gè)錯誤但文件并不會(huì )被自動(dòng)關(guān)閉。 在此情況下,更好的做法是等待直到解析器運行完畢再使用 with 語(yǔ)句來(lái)管理文件。

對于簡(jiǎn)單地檢查一組固定值的類(lèi)型檢查器,請考慮改用 choices 關(guān)鍵字。

choices?

某些命令行參數應當從一組受限值中選擇。 這可通過(guò)將一個(gè)容器對象作為 choices 關(guān)鍵字參數傳給 add_argument() 來(lái)處理。 當執行命令行解析時(shí),參數值將被檢查,如果參數不是可接受的值之一就將顯示錯誤消息:

>>>
>>> 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 容器包含的內容會(huì )在執行任意 type 轉換之后被檢查,因此 choices 容器中對象的類(lèi)型應當與指定的 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)

任何容器都可作為 choices 值傳入,因此 list 對象,set 對象以及自定義容器都是受支持的。

不建議使用 enum.Enum,因為要控制其在用法、幫助和錯誤消息中的外觀(guān)是很困難的。

Formatted choices override the default metavar which is normally derived from dest. This is usually what you want because the user never sees the dest parameter. If this display isn't desirable (perhaps because there are many choices), just specify an explicit metavar.

required?

通常,argparse 模塊會(huì )認為 -f--bar 等旗標是指明 可選的 參數,它們總是可以在命令行中被忽略。 要讓一個(gè)選項成為 必需的,則可以將 True 作為 required= 關(guān)鍵字參數傳給 add_argument():

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

如這個(gè)例子所示,如果一個(gè)選項被標記為 required,則當該選項未在命令行中出現時(shí),parse_args() 將會(huì )報告一個(gè)錯誤。

備注

必需的選項通常被認為是不適宜的,因為用戶(hù)會(huì )預期 options 都是 可選的,因此在可能的情況下應當避免使用它們。

help?

help 值是一個(gè)包含參數簡(jiǎn)短描述的字符串。 當用戶(hù)請求幫助時(shí)(一般是通過(guò)在命令行中使用 -h--help 的方式),這些 help 描述將隨每個(gè)參數一同顯示:

>>>
>>> parser = argparse.ArgumentParser(prog='frobble')
>>> parser.add_argument('--foo', action='store_true',
...                     help='foo the bars before frobbling')
>>> parser.add_argument('bar', nargs='+',
...                     help='one of the bars to be frobbled')
>>> parser.parse_args(['-h'])
usage: frobble [-h] [--foo] bar [bar ...]

positional arguments:
 bar     one of the bars to be frobbled

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

help 字符串可包括各種格式描述符以避免重復使用程序名稱(chēng)或參數 default 等文本。 有效的描述符包括程序名稱(chēng) %(prog)s 和傳給 add_argument() 的大部分關(guān)鍵字參數,例如 %(default)s, %(type)s 等等:

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

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

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

由于幫助字符串支持 %-formatting,如果你希望在幫助字符串中顯示 % 字面值,你必須將其轉義為 %%。

argparse 支持靜默特定選項的幫助,具體做法是將 help 的值設為 argparse.SUPPRESS:

>>>
>>> parser = argparse.ArgumentParser(prog='frobble')
>>> parser.add_argument('--foo', help=argparse.SUPPRESS)
>>> parser.print_help()
usage: frobble [-h]

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

metavar?

ArgumentParser 生成幫助消息時(shí),它需要用某種方式來(lái)引用每個(gè)預期的參數。 默認情況下,ArgumentParser 對象使用 dest 值作為每個(gè)對象的 "name"。 默認情況下,對于位置參數動(dòng)作,dest 值將被直接使用,而對于可選參數動(dòng)作,dest 值將被轉為大寫(xiě)形式。 因此,一個(gè)位置參數 dest='bar' 的引用形式將為 bar。 一個(gè)帶有單獨命令行參數的可選參數 --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

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

可以使用 metavar 來(lái)指定一個(gè)替代名稱(chēng):

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

positional arguments:
 XXX

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

請注意 metavar 僅改變 顯示的 名稱(chēng) - parse_args() 對象的屬性名稱(chēng)仍然會(huì )由 dest 值確定。

不同的 nargs 值可能導致 metavar 被多次使用。 提供一個(gè)元組給 metavar 即為每個(gè)參數指定不同的顯示信息:

>>>
>>> parser = argparse.ArgumentParser(prog='PROG')
>>> parser.add_argument('-x', nargs=2)
>>> parser.add_argument('--foo', nargs=2, metavar=('bar', 'baz'))
>>> parser.print_help()
usage: PROG [-h] [-x X X] [--foo bar baz]

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

dest?

大多數 ArgumentParser 動(dòng)作會(huì )添加一些值作為 parse_args() 所返回對象的一個(gè)屬性。 該屬性的名稱(chēng)由 add_argument()dest 關(guān)鍵字參數確定。 對于位置參數動(dòng)作,dest 通常會(huì )作為 add_argument() 的第一個(gè)參數提供:

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

對于可選參數動(dòng)作,dest 的值通常取自選項字符串。 ArgumentParser 會(huì )通過(guò)接受第一個(gè)長(cháng)選項字符串并去掉開(kāi)頭的 -- 字符串來(lái)生成 dest 的值。 如果沒(méi)有提供長(cháng)選項字符串,則 dest 將通過(guò)接受第一個(gè)短選項字符串并去掉開(kāi)頭的 - 字符來(lái)獲得。 任何內部的 - 字符都將被轉換為 _ 字符以確保字符串是有效的屬性名稱(chēng)。 下面的例子顯示了這種行為:

>>>
>>> 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 允許提供自定義屬性名稱(chēng):

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

Action 類(lèi)?

Action 類(lèi)實(shí)現了 Action API,它是一個(gè)返回可調用對象的可調用對象,返回的可調用對象可處理來(lái)自命令行的參數。 任何遵循此 API 的對象均可作為 action 形參傳給 add_argument()。

class argparse.Action(option_strings, dest, nargs=None, const=None, default=None, type=None, choices=None, required=False, help=None, metavar=None)?

Action 對象會(huì )被 ArgumentParser 用來(lái)表示解析從命令行中的一個(gè)或多個(gè)字符串中解析出單個(gè)參數所必須的信息。 Action 類(lèi)必須接受兩個(gè)位置參數以及傳給 ArgumentParser.add_argument() 的任何關(guān)鍵字參數,除了 action 本身。

Action 的實(shí)例(或作為or return value of any callable to the action 形參的任何可調用對象的返回值)應當定義 "dest", "option_strings", "default", "type", "required", "help" 等屬性。 確保這些屬性被定義的最容易方式是調用 Action.__init__。

Action 的實(shí)例應當為可調用對象,因此所有子類(lèi)都必須重載 __call__ 方法,該方法應當接受四個(gè)形參:

  • parser - 包含此動(dòng)作的 ArgumentParser 對象。

  • namespace - 將由 parse_args() 返回的 Namespace 對象。 大多數動(dòng)作會(huì )使用 setattr() 為此對象添加屬性。

  • values - 已關(guān)聯(lián)的命令行參數,并提供相應的類(lèi)型轉換。 類(lèi)型轉換由 add_argument()type 關(guān)鍵字參數來(lái)指定。

  • option_string - 被用來(lái)發(fā)起調用此動(dòng)作的選項字符串。 option_string 參數是可選的,且此參數在動(dòng)作關(guān)聯(lián)到位置參數時(shí)將被略去。

__call__ 方法可以執行任意動(dòng)作,但通常將基于 destvalues 來(lái)設置 namespace 的屬性。

動(dòng)作子類(lèi)可定義 format_usage 方法,該方法不帶參數,所返回的字符串將被用于打印程序的用法說(shuō)明。 如果未提供此方法,則將使用適當的默認值。

parse_args() 方法?

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

將參數字符串轉換為對象并將其設為命名空間的屬性。 返回帶有成員的命名空間。

之前對 add_argument() 的調用決定了哪些對象被創(chuàng )建以及它們如何被賦值。 請參閱 add_argument() 的文檔了解詳情。

  • args - 要解析的字符串列表。 默認值是從 sys.argv 獲取。

  • namespace - 用于獲取屬性的對象。 默認值是一個(gè)新的空 Namespace 對象。

選項值語(yǔ)法?

parse_args() 方法支持多種指定選項值的方式(如果它接受選項的話(huà))。 在最簡(jiǎn)單的情況下,選項和它的值是作為兩個(gè)單獨參數傳入的:

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

對于長(cháng)選項(名稱(chēng)長(cháng)度超過(guò)一個(gè)字符的選項),選項和值也可以作為單個(gè)命令行參數傳入,使用 = 分隔它們即可:

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

對于短選項(長(cháng)度只有一個(gè)字符的選項),選項和它的值可以拼接在一起:

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

有些短選項可以使用單個(gè) - 前綴來(lái)進(jìn)行合并,如果僅有最后一個(gè)選項(或沒(méi)有任何選項)需要值的話(huà):

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

無(wú)效的參數?

在解析命令行時(shí),parse_args() 會(huì )檢測多種錯誤,包括有歧義的選項、無(wú)效的類(lèi)型、無(wú)效的選項、錯誤的位置參數個(gè)數等等。 當遇到這種錯誤時(shí),它將退出并打印出錯誤文本同時(shí)附帶用法消息:

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

包含 - 的參數?

parse_args() 方法會(huì )在用戶(hù)明顯出錯時(shí)嘗試給出錯誤信息,但某些情況本身就存在歧義。 例如,命令行參數 -1 可能是嘗試指定一個(gè)選項也可能是嘗試提供一個(gè)位置參數。 parse_args() 方法在此會(huì )謹慎行事:位置參數只有在它們看起來(lái)像負數并且解析器中沒(méi)有任何選項看起來(lái)像負數時(shí)才能以 - 打頭。:

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

如果你有必須以 - 打頭的位置參數并且看起來(lái)不像負數,你可以插入偽參數 '--' 以告訴 parse_args() 在那之后的內容是一個(gè)位置參數:

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

See also the argparse howto on ambiguous arguments for more details.

參數縮寫(xiě)(前綴匹配)?

parse_args() 方法 在默認情況下 允許將長(cháng)選項縮寫(xiě)為前綴,如果縮寫(xiě)無(wú)歧義(即前綴與一個(gè)特定選項相匹配)的話(huà):

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

可產(chǎn)生一個(gè)以上選項的參數會(huì )引發(fā)錯誤。 此特定可通過(guò)將 allow_abbrev 設為 False 來(lái)禁用。

sys.argv 以外?

有時(shí)在 sys.argv 以外用 ArgumentParser 解析參數也是有用的。 這可以通過(guò)將一個(gè)字符串列表傳給 parse_args() 來(lái)實(shí)現。 它適用于在交互提示符下進(jìn)行檢測:

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

命名空間對象?

class argparse.Namespace?

parse_args() 默認使用的簡(jiǎn)單類(lèi),可創(chuàng )建一個(gè)存放屬性的對象并將其返回。

這個(gè)類(lèi)被有意做得很簡(jiǎn)單,只是一個(gè)具有可讀字符串表示形式的 object。 如果你更喜歡類(lèi)似字典的屬性視圖,你可以使用標準 Python 中慣常的 vars():

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

另一個(gè)用處是讓 ArgumentParser 為一個(gè)已存在對象而不是為一個(gè)新的 Namespace 對象的屬性賦值。 這可以通過(guò)指定 namespace= 關(guān)鍵字參數來(lái)實(shí)現:

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

其它實(shí)用工具?

子命令?

ArgumentParser.add_subparsers([title][, description][, prog][, parser_class][, action][, option_strings][, dest][, required][, help][, metavar])?

許多程序都會(huì )將其功能拆分為一系列子命令,例如,svn 程序包含的子命令有 svn checkout, svn updatesvn commit。 當一個(gè)程序能執行需要多組不同種類(lèi)命令行參數時(shí)這種拆分功能的方式是一個(gè)非常好的主意。 ArgumentParser 通過(guò) add_subparsers() 方法支持創(chuàng )建這樣的子命令。 add_subparsers() 方法通常不帶參數地調用并返回一個(gè)特殊的動(dòng)作對象。 這種對象只有一個(gè)方法 add_parser(),它接受一個(gè)命令名稱(chēng)和任意多個(gè) ArgumentParser 構造器參數,并返回一個(gè)可以通常方式進(jìn)行修改的 ArgumentParser 對象。

形參的描述

  • title - 輸出幫助的子解析器分組的標題;如果提供了描述則默認為 "subcommands",否則使用位置參數的標題

  • description - 輸出幫助中對子解析器的描述,默認為 None

  • prog - 將與子命令幫助一同顯示的用法信息,默認為程序名稱(chēng)和子解析器參數之前的任何位置參數。

  • parser_class - 將被用于創(chuàng )建子解析器實(shí)例的類(lèi),默認為當前解析器類(lèi)(例如 ArgumentParser)

  • action - 當此參數在命令行中出現時(shí)要執行動(dòng)作的基本類(lèi)型

  • dest - 將被用于保存子命令名稱(chēng)的屬性名;默認為 None 即不保存任何值

  • required - 是否必須要提供子命令,默認為 False (在 3.7 中新增)

  • help - 在輸出幫助中的子解析器分組幫助信息,默認為 None

  • metavar - 幫助信息中表示可用子命令的字符串;默認為 None 并以 {cmd1, cmd2, ..} 的形式表示子命令

一些使用示例:

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

請注意 parse_args() 返回的對象將只包含主解析器和由命令行所選擇的子解析器的屬性(而沒(méi)有任何其他子解析器)。 因此在上面的例子中,當指定了 a 命令時(shí),將只存在 foobar 屬性,而當指定了 b 命令時(shí),則只存在 foobaz 屬性。

類(lèi)似地,當從一個(gè)子解析器請求幫助消息時(shí),只有該特定解析器的幫助消息會(huì )被打印出來(lái)。 幫助消息將不包括父解析器或同級解析器的消息。 (每個(gè)子解析器命令一條幫助消息,但是,也可以像上面那樣通過(guò)提供 help= 參數給 add_parser() 來(lái)給出。)

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

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

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

>>> parser.parse_args(['a', '--help'])
usage: PROG a [-h] bar

positional arguments:
  bar     bar help

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

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

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

add_subparsers() 方法也支持 titledescription 關(guān)鍵字參數。 當兩者都存在時(shí),子解析器的命令將出現在輸出幫助消息中它們自己的分組內。 例如:

>>>
>>> parser = argparse.ArgumentParser()
>>> subparsers = parser.add_subparsers(title='subcommands',
...                                    description='valid subcommands',
...                                    help='additional help')
>>> subparsers.add_parser('foo')
>>> subparsers.add_parser('bar')
>>> parser.parse_args(['-h'])
usage:  [-h] {foo,bar} ...

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

subcommands:
  valid subcommands

  {foo,bar}   additional help

此外,add_parser 還支持附加的 aliases 參數,它允許多個(gè)字符串指向同一子解析器。 這個(gè)例子類(lèi)似于 svn,將別名 co 設為 checkout 的縮寫(xiě)形式:

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

一個(gè)特別有效的處理子命令的方式是將 add_subparsers() 方法與對 set_defaults() 的調用結合起來(lái)使用,這樣每個(gè)子解析器就能知道應當執行哪個(gè) Python 函數。 例如:

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

通過(guò)這種方式,你可以在參數解析結束后讓 parse_args() 執行調用適當函數的任務(wù)。 像這樣將函數關(guān)聯(lián)到動(dòng)作通常是你處理每個(gè)子解析器的不同動(dòng)作的最簡(jiǎn)便方式。 但是,如果有必要檢查被發(fā)起調用的子解析器的名稱(chēng),則 add_subparsers() 調用的 dest 關(guān)鍵字參數將可實(shí)現:

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

在 3.7 版更改: 新增 required 關(guān)鍵字參數。

FileType 對象?

class argparse.FileType(mode='r', bufsize=- 1, encoding=None, errors=None)?

FileType 工廠(chǎng)類(lèi)用于創(chuàng )建可作為 ArgumentParser.add_argument() 的 type 參數傳入的對象。 以 FileType 對象作為其類(lèi)型的參數將使用命令行參數以所請求模式、緩沖區大小、編碼格式和錯誤處理方式打開(kāi)文件(請參閱 open() 函數了解詳情):

>>>
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--raw', type=argparse.FileType('wb', 0))
>>> parser.add_argument('out', type=argparse.FileType('w', encoding='UTF-8'))
>>> parser.parse_args(['--raw', 'raw.dat', 'file.txt'])
Namespace(out=<_io.TextIOWrapper name='file.txt' mode='w' encoding='UTF-8'>, raw=<_io.FileIO name='raw.dat' mode='wb'>)

FileType 對象能理解偽參數 '-' 并會(huì )自動(dòng)將其轉換為 sys.stdin 用于可讀的 FileType 對象,或是 sys.stdout 用于可寫(xiě)的 FileType 對象:

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

3.4 新版功能: encodingserrors 關(guān)鍵字參數。

參數組?

ArgumentParser.add_argument_group(title=None, description=None)?

在默認情況下,ArgumentParser 會(huì )在顯示幫助消息時(shí)將命令行參數分為“位置參數”和“可選參數”兩組。 當存在比默認更好的參數分組概念時(shí),可以使用 add_argument_group() 方法來(lái)創(chuàng )建適當的分組:

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

group:
  bar    bar help
  --foo FOO  foo help

add_argument_group() 方法返回一個(gè)具有 add_argument() 方法的參數分組對象,這與常規的 ArgumentParser 一樣。 當一個(gè)參數被加入分組時(shí),解析器會(huì )將它視為一個(gè)正常的參數,但是會(huì )在不同的幫助消息分組中顯示該參數。 add_argument_group() 方法接受 titledescription 參數,它們可被用來(lái)定制顯示內容:

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

請注意任意不在你的自定義分組中的參數最終都將回到通常的“位置參數”和“可選參數”分組中。

在 3.11 版更改: Calling add_argument_group() on an argument group is deprecated. This feature was never supported and does not always work correctly. The function exists on the API by accident through inheritance and will be removed in the future.

互斥?

ArgumentParser.add_mutually_exclusive_group(required=False)?

創(chuàng )建一個(gè)互斥組。 argparse 將會(huì )確?;コ饨M中只有一個(gè)參數在命令行中可用:

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

add_mutually_exclusive_group() 方法也接受一個(gè) required 參數,表示在互斥組中至少有一個(gè)參數是需要的:

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

注意,目前互斥參數組不支持 add_argument_group()titledescription 參數。

在 3.11 版更改: Calling add_argument_group() or add_mutually_exclusive_group() on a mutually exclusive group is deprecated. These features were never supported and do not always work correctly. The functions exist on the API by accident through inheritance and will be removed in the future.

解析器默認值?

ArgumentParser.set_defaults(**kwargs)?

在大多數時(shí)候,parse_args() 所返回對象的屬性將完全通過(guò)檢查命令行參數和參數動(dòng)作來(lái)確定。 set_defaults() 則允許加入一些無(wú)須任何命令行檢查的額外屬性:

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

請注意解析器層級的默認值總是會(huì )覆蓋參數層級的默認值:

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

解析器層級默認值在需要多解析器時(shí)會(huì )特別有用。 請參閱 add_subparsers() 方法了解此類(lèi)型的一個(gè)示例。

ArgumentParser.get_default(dest)?

獲取一個(gè)命名空間屬性的默認值,該值是由 add_argument()set_defaults() 設置的:

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

打印幫助?

在大多數典型應用中,parse_args() 將負責任何用法和錯誤消息的格式化和打印。 但是,也可使用某些其他格式化方法:

ArgumentParser.print_usage(file=None)?

打印一段簡(jiǎn)短描述,說(shuō)明應當如何在命令行中發(fā)起調用 ArgumentParser。 如果 fileNone,則默認使用 sys.stdout。

ArgumentParser.print_help(file=None)?

打印一條幫助消息,包括程序用法和通過(guò) ArgumentParser 注冊的相關(guān)參數信息。 如果 fileNone,則默認使用 sys.stdout。

還存在這些方法的幾個(gè)變化形式,它們只返回字符串而不打印消息:

ArgumentParser.format_usage()?

返回一個(gè)包含簡(jiǎn)短描述的字符串,說(shuō)明應當如何在命令行中發(fā)起調用 ArgumentParser。

ArgumentParser.format_help()?

反回一個(gè)包含幫助消息的字符串,包括程序用法和通過(guò) ArgumentParser 注冊的相關(guān)參數信息。

部分解析?

ArgumentParser.parse_known_args(args=None, namespace=None)?

有時(shí)一個(gè)腳本可能只解析部分命令行參數,而將其余的參數繼續傳遞給另一個(gè)腳本或程序。 在這種情況下,parse_known_args() 方法會(huì )很有用處。 它的作用方式很類(lèi)似 parse_args() 但區別在于當存在額外參數時(shí)它不會(huì )產(chǎn)生錯誤。 而是會(huì )返回一個(gè)由兩個(gè)條目構成的元組,其中包含帶成員的命名空間和剩余參數字符串的列表。

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

警告

前綴匹配 規則應用于 parse_known_args()。 一個(gè)選項即使只是已知選項的前綴部分解析器也能識別該選項,不會(huì )將其放入剩余參數列表。

自定義文件解析?

ArgumentParser.convert_arg_line_to_args(arg_line)?

從文件讀取的參數(見(jiàn) ArgumentParserfromfile_prefix_chars 關(guān)鍵字參數)將是一行讀取一個(gè)參數。 convert_arg_line_to_args() 可被重載以使用更復雜的讀取方式。

此方法接受從參數文件讀取的字符串形式的單個(gè)參數 arg_line。 它返回從該字符串解析出的參數列表。 此方法將在每次按順序從參數文件讀取一行時(shí)被調用一次。

此方法的一個(gè)有用的重載是將每個(gè)以空格分隔的單詞視為一個(gè)參數。 下面的例子演示了如何實(shí)現此重載:

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

退出方法?

ArgumentParser.exit(status=0, message=None)?

此方法將終結程序,退出時(shí)附帶指定的 status,并且如果給出了 message 則會(huì )在退出前將其打印輸出。 用戶(hù)可重載此方法以不同方式來(lái)處理這些步驟:

class ErrorCatchingArgumentParser(argparse.ArgumentParser):
    def exit(self, status=0, message=None):
        if status:
            raise Exception(f'Exiting because of an error: {message}')
        exit(status)
ArgumentParser.error(message)?

此方法將向標準錯誤打印包括 message 的用法消息并附帶狀態(tài)碼 2 終結程序。

混合解析?

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

許多 Unix 命令允許用戶(hù)混用可選參數與位置參數。 parse_intermixed_args()parse_known_intermixed_args() 方法均支持這種解析風(fēng)格。

這些解析器并不支持所有的 argparse 特性,并且當未支持的特性被使用時(shí)將會(huì )引發(fā)異常。 特別地,子解析器,argparse.REMAINDER 以及同時(shí)包括可選與位置參數的互斥分組是不受支持的。

下面的例子顯示了 parse_known_args()parse_intermixed_args() 之間的差異:前者會(huì )將 ['2', '3'] 返回為未解析的參數,而后者會(huì )將所有位置參數收集至 rest 中。

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

parse_known_intermixed_args() 返回由兩個(gè)條目組成的元組,其中包含帶成員的命名空間以及剩余參數字符串列表。 當存在任何剩余的未解析參數字符串時(shí) parse_intermixed_args() 將引發(fā)一個(gè)錯誤。

3.7 新版功能.

升級 optparse 代碼?

起初,argparse 曾經(jīng)嘗試通過(guò) optparse 來(lái)維持兼容性。 但是,optparse 很難透明地擴展,特別是那些為支持新的 nargs= 描述方式和更好的用法消息所需的修改。當When most everything in optparse 中幾乎所有內容都已被復制粘貼或打上補丁時(shí),維持向下兼容看來(lái)已是不切實(shí)際的。

argparse 模塊在許多方面對標準庫的 optparse 模塊進(jìn)行了增強,包括:

  • 處理位置參數。

  • 支持子命令。

  • 允許替代選項前綴例如 +/。

  • 處理零個(gè)或多個(gè)以及一個(gè)或多個(gè)風(fēng)格的參數。

  • 生成更具信息量的用法消息。

  • 提供用于定制 typeaction 的更為簡(jiǎn)單的接口。

optparseargparse 的部分升級路徑:

  • 將所有 optparse.OptionParser.add_option() 調用替換為 ArgumentParser.add_argument() 調用。

  • (options, args) = parser.parse_args() 替換為 args = parser.parse_args() 并為位置參數添加額外的 ArgumentParser.add_argument() 調用。 請注意之前所謂的 optionsargparse 上下文中被稱(chēng)為 args。

  • 通過(guò)使用 parse_intermixed_args() 而非 parse_args() 來(lái)替換 optparse.OptionParser.disable_interspersed_args()。

  • 將回調動(dòng)作和 callback_* 關(guān)鍵字參數替換為 typeaction 參數。

  • type 關(guān)鍵字參數字符串名稱(chēng)替換為相應的類(lèi)型對象(例如 int, float, complex 等)。

  • optparse.Values 替換為 Namespace 并將 optparse.OptionErroroptparse.OptionValueError 替換為 ArgumentError。

  • 將隱式參數字符串例如使用標準 Python 字典語(yǔ)法的 %default%prog 替換為格式字符串,即 %(default)s%(prog)s。

  • 將 OptionParser 構造器 version 參數替換為對 parser.add_argument('--version', action='version', version='<the version>') 的調用。