### 導航
- [索引](../genindex.xhtml "總目錄")
- [模塊](../py-modindex.xhtml "Python 模塊索引") |
- [下一頁](getopt.xhtml "getopt --- C-style parser for command line options") |
- [上一頁](time.xhtml "time --- 時間的訪問和轉換") |
- 
- [Python](https://www.python.org/) ?
- zh\_CN 3.7.3 [文檔](../index.xhtml) ?
- [Python 標準庫](index.xhtml) ?
- [通用操作系統服務](allos.xhtml) ?
- $('.inline-search').show(0); |
# [`argparse`](#module-argparse "argparse: Command-line option and argument parsing library.") --- 命令行選項、參數和子命令解析器
3\.2 新版功能.
**源代碼:** [Lib/argparse.py](https://github.com/python/cpython/tree/3.7/Lib/argparse.py) \[https://github.com/python/cpython/tree/3.7/Lib/argparse.py\]
- - - - - -
教程
此頁面包含該 API 的參考信息。有關 Python 命令行解析更細致的介紹,請參閱 [argparse 教程](../howto/argparse.xhtml#id1)。
[`argparse`](#module-argparse "argparse: Command-line option and argument parsing library.") 模塊可以讓人輕松編寫用戶友好的命令行接口。程序定義它需要的參數,然后 [`argparse`](#module-argparse "argparse: Command-line option and argument parsing library.") 將弄清如何從 [`sys.argv`](sys.xhtml#sys.argv "sys.argv") 解析出那些參數。 [`argparse`](#module-argparse "argparse: Command-line option and argument parsing library.") 模塊還會自動生成幫助和使用手冊,并在用戶給程序傳入無效參數時報出錯誤信息。
## 示例
以下代碼是一個 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))
```
假設上面的 Python 代碼保存在名為 `prog.py` 的文件中,它可以在命令行運行并提供有用的幫助消息:
```
$ 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'
```
以下部分將引導你完成這個示例。
### 創建一個解析器
使用 [`argparse`](#module-argparse "argparse: Command-line option and argument parsing library.") 的第一步是創建一個 [`ArgumentParser`](#argparse.ArgumentParser "argparse.ArgumentParser") 對象:
```
>>> parser = argparse.ArgumentParser(description='Process some integers.')
```
[`ArgumentParser`](#argparse.ArgumentParser "argparse.ArgumentParser") 對象包含將命令行解析成 Python 數據類型所需的全部信息。
### 添加參數
給一個 [`ArgumentParser`](#argparse.ArgumentParser "argparse.ArgumentParser") 添加程序參數信息是通過調用 [`add_argument()`](#argparse.ArgumentParser.add_argument "argparse.ArgumentParser.add_argument") 方法完成的。通常,這些調用指定 [`ArgumentParser`](#argparse.ArgumentParser "argparse.ArgumentParser") 如何獲取命令行字符串并將其轉換為對象。這些信息在 [`parse_args()`](#argparse.ArgumentParser.parse_args "argparse.ArgumentParser.parse_args") 調用時被存儲和使用。例如:
```
>>> 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()`](#argparse.ArgumentParser.parse_args "argparse.ArgumentParser.parse_args") 將返回一個具有 `integers` 和 `accumulate` 兩個屬性的對象。`integers` 屬性將是一個包含一個或多個整數的列表,而 `accumulate` 屬性當命令行中指定了 `--sum` 參數時將是 [`sum()`](functions.xhtml#sum "sum") 函數,否則則是 [`max()`](functions.xhtml#max "max") 函數。
### 解析參數
[`ArgumentParser`](#argparse.ArgumentParser "argparse.ArgumentParser") 通過 [`parse_args()`](#argparse.ArgumentParser.parse_args "argparse.ArgumentParser.parse_args") 方法解析參數。它將檢查命令行,把每個參數轉換為適當的類型然后調用相應的操作。在大多數情況下,這意味著一個簡單的 [`Namespace`](#argparse.Namespace "argparse.Namespace") 對象將從命令行參數中解析出的屬性構建:
```
>>> parser.parse_args(['--sum', '7', '-1', '42'])
Namespace(accumulate=<built-in function sum>, integers=[7, -1, 42])
```
在腳本中,通常 [`parse_args()`](#argparse.ArgumentParser.parse_args "argparse.ArgumentParser.parse_args") 會被不帶參數調用,而 [`ArgumentParser`](#argparse.ArgumentParser "argparse.ArgumentParser") 將自動從 [`sys.argv`](sys.xhtml#sys.argv "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*)創建一個新的 [`ArgumentParser`](#argparse.ArgumentParser "argparse.ArgumentParser") 對象。所有的參數都應當作為關鍵字參數傳入。每個參數在下面都有它更詳細的描述,但簡而言之,它們是:
- [prog](#prog) - 程序的名稱(默認:`sys.argv[0]`)
- [usage](#usage) - 描述程序用途的字符串(默認值:從添加到解析器的參數生成)
- [description](#description) - 在參數幫助文檔之前顯示的文本(默認值:無)
- [epilog](#epilog) - 在參數幫助文檔之后顯示的文本(默認值:無)
- [parents](#parents) - 一個 [`ArgumentParser`](#argparse.ArgumentParser "argparse.ArgumentParser") 對象的列表,它們的參數也應包含在內
- [formatter\_class](#formatter-class) - 用于自定義幫助文檔輸出格式的類
- [prefix\_chars](#prefix-chars) - 可選參數的前綴字符集合(默認值:'-')
- [fromfile\_prefix\_chars](#fromfile-prefix-chars) - 當需要從文件中讀取其他參數時,用于標識文件名的前綴字符集合(默認值:`None`)
- [argument\_default](#argument-default) - 參數的全局默認值(默認值: `None`)
- [conflict\_handler](#conflict-handler) - 解決沖突選項的策略(通常是不必要的)
- [add\_help](#add-help) - 為解析器添加一個 `-h/--help` 選項(默認值: `True`)
- [allow\_abbrev](#allow-abbrev) - 如果縮寫是無歧義的,則允許縮寫長選項 (默認值:`True`)
在 3.5 版更改: 添加 *allow\_abbrev* 參數。
以下部分描述這些參數如何使用。
### prog
默認情況下,[`ArgumentParser`](#argparse.ArgumentParser "argparse.ArgumentParser") 對象使用 `sys.argv[0]` 來確定如何在幫助消息中顯示程序名稱。這一默認值幾乎總是可取的,因為它將使幫助消息與從命令行調用此程序的方式相匹配。例如,對于有如下代碼的名為 `myprogram.py` 的文件:
```
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--foo', help='foo help')
args = parser.parse_args()
```
該程序的幫助信息將顯示 `myprogram.py` 作為程序名稱(無論程序從何處被調用):
```
$ 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`](#argparse.ArgumentParser "argparse.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
```
### usage
默認情況下,[`ArgumentParser`](#argparse.ArgumentParser "argparse.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
```
在用法消息中可以使用 `%(prog)s` 格式說明符來填入程序名稱。
### description
大多數對 [`ArgumentParser`](#argparse.ArgumentParser "argparse.ArgumentParser") 構造方法的調用都會使用 `description=` 關鍵字參數。這個參數簡要描述這個程度做什么以及怎么做。在幫助消息中,這個描述會顯示在命令行用法字符串和各種參數的幫助消息之間:
```
>>> 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](#formatter-class) 參數。
### epilog
一些程序喜歡在 description 參數后顯示額外的對程序的描述。這種文字能夠通過給 [`ArgumentParser`](#argparse.ArgumentParser "argparse.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
optional arguments:
-h, --help show this help message and exit
And that's how you'd foo a bar
```
和 [description](#description) 參數一樣,`epilog=` text 在默認情況下會換行,但是這種行為能夠被調整通過提供 [formatter\_class](#formatter-class) 參數給 `ArgumentParse`.
### parents
有些時候,少數解析器會使用同一系列參數。 單個解析器能夠通過提供 `parents=` 參數給 [`ArgumentParser`](#argparse.ArgumentParser "argparse.ArgumentParser") 而使用相同的參數而不是重復這些參數的定義。`parents=` 參數使用 [`ArgumentParser`](#argparse.ArgumentParser "argparse.ArgumentParser") 對象的列表,從它們那里收集所有的位置和可選的行為,然后將這寫行為加到正在構建的 [`ArgumentParser`](#argparse.ArgumentParser "argparse.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)
```
請注意大多數父解析器會指定 `add_help=False` . 否則, `ArgumentParse` 將會看到兩個 `-h/--help` 選項(一個在父參數中一個在子參數中)并且產生一個錯誤。
注解
你在傳``parents=``給那些解析器時必須完全初始化它們。如果你在子解析器之后改變父解析器是,這些改變不會反映在子解析器上。
### formatter\_class
[`ArgumentParser`](#argparse.ArgumentParser "argparse.ArgumentParser") 對象允許通過指定備用格式化類來自定義幫助格式。目前,有四種這樣的類。
*class* `argparse.``RawDescriptionHelpFormatter`*class* `argparse.``RawTextHelpFormatter`*class* `argparse.``ArgumentDefaultsHelpFormatter`*class* `argparse.``MetavarTypeHelpFormatter`[`RawDescriptionHelpFormatter`](#argparse.RawDescriptionHelpFormatter "argparse.RawDescriptionHelpFormatter") 和 [`RawTextHelpFormatter`](#argparse.RawTextHelpFormatter "argparse.RawTextHelpFormatter") 在正文的描述和展示上給與了更多的控制。[`ArgumentParser`](#argparse.ArgumentParser "argparse.ArgumentParser") 對象會將 [description](#description) 和 [epilog](#epilog) 的文字在命令行中自動換行。
```
>>> 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
```
傳 [`RawDescriptionHelpFormatter`](#argparse.RawDescriptionHelpFormatter "argparse.RawDescriptionHelpFormatter") 給 `formatter_class=` 表示 [description](#description) 和 [epilog](#epilog) 已經被正確的格式化了,不能在命令行中被自動換行:
```
>>> 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`](#argparse.RawTextHelpFormatter "argparse.RawTextHelpFormatter") 保留所有種類文字的空格,包括參數的描述。然而,多重的新行會被替換成一行。如果你想保留多重的空白行,可以在新行之間加空格。
[`ArgumentDefaultsHelpFormatter`](#argparse.ArgumentDefaultsHelpFormatter "argparse.ArgumentDefaultsHelpFormatter") 自動添加默認的值的信息到每一個幫助信息的參數中:
```
>>> 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`](#argparse.MetavarTypeHelpFormatter "argparse.MetavarTypeHelpFormatter") 為它的值在每一個參數中使用 [type](#type) 的參數名當作它的顯示名(而不是使用通常的格式 [dest](#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
optional arguments:
-h, --help show this help message and exit
--foo int
```
### prefix\_chars
許多命令行會使用 `-` 當作前綴,比如 `-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')
```
The `prefix_chars=` 參數默認使用 `'-'`. 支持一系列字符,但是不包括 `-` ,這樣會產生不被允許的 `-f/--foo` 選項。
### fromfile\_prefix\_chars
有些時候,先舉個例子,當處理一個特別長的參數列表的時候,把它存入一個文件中而不是在命令行打出來會很有意義。如果 `fromfile_prefix_chars=` 參數提供給 [`ArgumentParser`](#argparse.ArgumentParser "argparse.ArgumentParser") 構造函數,之后所有類型的字符的參數都會被當成文件處理,并且會被文件包含的參數替代。舉個栗子:
```
>>> 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')
```
從文件讀取的參數在默認情況下必須一個一行(但是可參見 [`convert_arg_line_to_args()`](#argparse.ArgumentParser.convert_arg_line_to_args "argparse.ArgumentParser.convert_arg_line_to_args"))并且它們被視為與命令行上的原始文件引用參數位于同一位置。所以在以上例子中,`['-f', 'foo', '@args.txt']` 的表示和 `['-f', 'foo', '-f', 'bar']` 的表示相同。
`fromfile_prefix_chars=` 參數默認為 `None`,意味著參數不會被當作文件對待。
### argument\_default
一般情況下,參數默認會通過設置一個默認到 [`add_argument()`](#argparse.ArgumentParser.add_argument "argparse.ArgumentParser.add_argument") 或者調用帶一組指定鍵值對的 [`ArgumentParser.set_defaults()`](#argparse.ArgumentParser.set_defaults "argparse.ArgumentParser.set_defaults") 方法。但是有些時候,為參數指定一個普遍適用的解析器會更有用。這能夠通過傳輸 `argument_default=` 關鍵詞參數給 [`ArgumentParser`](#argparse.ArgumentParser "argparse.ArgumentParser") 來完成。舉個栗子,要全局禁止在 [`parse_args()`](#argparse.ArgumentParser.parse_args "argparse.ArgumentParser.parse_args") 中創建屬性,我們提供 `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
正常情況下,當你向 [`ArgumentParser`](#argparse.ArgumentParser "argparse.ArgumentParser") 的 [`parse_args()`](#argparse.ArgumentParser.parse_args "argparse.ArgumentParser.parse_args") 方法傳入一個參數列表時,它會 [recognizes abbreviations](#prefix-matching)。
這個特性可以設置 `allow_abbrev` 為 `False` 來關閉:
```
>>> 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`](#argparse.ArgumentParser "argparse.ArgumentParser") 對象不允許在相同選項字符串下有兩種行為。默認情況下, [`ArgumentParser`](#argparse.ArgumentParser "argparse.ArgumentParser") 對象會產生一個異常如果去創建一個正在使用的選項字符串參數。
```
>>> 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
```
有些時候(例如:使用 [parents](#parents)),重寫舊的有相同選項字符串的參數會更有用。為了產生這種行為, `'resolve'` 值可以提供給 [`ArgumentParser`](#argparse.ArgumentParser "argparse.ArgumentParser") 的 `conflict_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]
optional arguments:
-h, --help show this help message and exit
-f FOO old foo help
--foo FOO new foo help
```
注意 [`ArgumentParser`](#argparse.ArgumentParser "argparse.ArgumentParser") 對象只能移除一個行為如果它所有的選項字符串都被重寫。所以,在上面的例子中,舊的 `-f/--foo` 行為 回合 `-f` 行為保持一樣, 因為只有 `--foo` 選項字符串被重寫。
### add\_help
默認情況下,ArgumentParser 對象添加一個簡單的顯示解析器幫助信息的選項。舉個栗子,考慮一個名為 `myprogram.py` 的文件包含如下代碼:
```
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--foo', help='foo help')
args = parser.parse_args()
```
如果 `-h` or `--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
```
有時候可能會需要關閉額外的幫助信息。這可以通過在 [`ArgumentParser`](#argparse.ArgumentParser "argparse.ArgumentParser") 中設置 `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
```
幫助選項一般為 `-h/--help`。如果 `prefix_chars=` 被指定并且沒有包含 `-` 字符,在這種情況下, `-h``--help` 不是有效的選項。此時, `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
```
## add\_argument() 方法
`ArgumentParser.``add_argument`(*name or flags...*\[, *action*\]\[, *nargs*\]\[, *const*\]\[, *default*\]\[, *type*\]\[, *choices*\]\[, *required*\]\[, *help*\]\[, *metavar*\]\[, *dest*\])定義單個的命令行參數應當如何解析。每個形參都在下面有它自己更多的描述,長話短說有:
- [name or flags](#name-or-flags) - 一個命名或者一個選項字符串的列表,例如 `foo` 或 `-f, --foo`。
- [action](#action) - 當參數在命令行中出現時使用的動作基本類型。
- [nargs](#nargs) - 命令行參數應當消耗的數目。
- [const](#const) - 被一些 [action](#action) 和 [nargs](#nargs) 選擇所需求的常數。
- [default](#default) - 當參數未在命令行中出現時使用的值。
- [type](#type) - 命令行參數應當被轉換成的類型。
- [choices](#choices) - 可用的參數的容器。
- [required](#required) - 此命令行選項是否可省略 (僅選項可用)。
- [help](#help) - 一個此選項作用的簡單描述。
- [metavar](#metavar) - 在使用方法消息中使用的參數值示例。
- [dest](#dest) - 被添加到 [`parse_args()`](#argparse.ArgumentParser.parse_args "argparse.ArgumentParser.parse_args") 所返回對象上的屬性名。
以下部分描述這些參數如何使用。
### name or flags
[`add_argument()`](#argparse.ArgumentParser.add_argument "argparse.ArgumentParser.add_argument") 方法必須知道它是否是一個選項,例如 `-f` 或 `--foo`,或是一個位置參數,例如一組文件名。第一個傳遞給 [`add_argument()`](#argparse.ArgumentParser.add_argument "argparse.ArgumentParser.add_argument") 的參數必須是一系列 flags 或者是一個簡單的參數名。例如,可以選項可以被這樣創建:
```
>>> parser.add_argument('-f', '--foo')
```
而位置參數可以這么創建:
```
>>> parser.add_argument('bar')
```
當 [`parse_args()`](#argparse.ArgumentParser.parse_args "argparse.ArgumentParser.parse_args") 被調用,選項會以 `-` 前綴識別,剩下的參數則會被假定為位置參數:
```
>>> 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`](#argparse.ArgumentParser "argparse.ArgumentParser") 對象將命令行參數與動作相關聯。這些動作可以做與它們相關聯的命令行參數的任何事,盡管大多數動作只是簡單的向 [`parse_args()`](#argparse.ArgumentParser.parse_args "argparse.ArgumentParser.parse_args") 返回的對象上添加屬性。`action` 命名參數指定了這個命令行參數應當如何處理。供應的動作有:
- `'store'` - 存儲參數的值。這是默認的動作。例如:
```
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo')
>>> parser.parse_args('--foo 1'.split())
Namespace(foo='1')
```
- `'store_const'` - 存儲被 [const](#const) 命名參數指定的值。 `'store_const'` 動作通常用在選項中來指定一些標志。例如:
```
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo', action='store_const', const=42)
>>> parser.parse_args(['--foo'])
Namespace(foo=42)
```
- `'store_true'` and `'store_false'` - 這些是 `'store_const'` 分別用作存儲 `True` 和 `False` 值的特殊用例。另外,它們的默認值分別為 `False` 和 `True`。例如:
```
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo', action='store_true')
>>> parser.add_argument('--bar', action='store_false')
>>> parser.add_argument('--baz', action='store_false')
>>> parser.parse_args('--foo --bar'.split())
Namespace(foo=True, bar=False, baz=True)
```
- `'append'` - 存儲一個列表,并且將每個參數值追加到列表中。在允許多次使用選項時很有用。例如:
```
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo', action='append')
>>> parser.parse_args('--foo 1 --foo 2'.split())
Namespace(foo=['1', '2'])
```
- `'append_const'` - 這存儲一個列表,并將 [const](#const) 命名參數指定的值追加到列表中。(注意 [const](#const) 命名參數默認為 `None`。)``'append\_const'`` 動作一般在多個參數需要在同一列表中存儲常數時會有用。例如:
```
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--str', dest='types', action='append_const', const=str)
>>> parser.add_argument('--int', dest='types', action='append_const', const=int)
>>> parser.parse_args('--str --int'.split())
Namespace(types=[<class 'str'>, <class 'int'>])
```
- `'count'` - 計算一個關鍵字參數出現的數目或次數。例如,對于一個增長的詳情等級來說有用:
```
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--verbose', '-v', action='count')
>>> parser.parse_args(['-vvv'])
Namespace(verbose=3)
```
- `'help'` - 打印所有當前解析器中的選項和參數的完整幫助信息,然后退出。默認情況下,一個 help 動作會被自動加入解析器。關于輸出是如何創建的,參與 [`ArgumentParser`](#argparse.ArgumentParser "argparse.ArgumentParser")。
- `'version'` - 期望有一個 `version=` 命名參數在 [`add_argument()`](#argparse.ArgumentParser.add_argument "argparse.ArgumentParser.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
```
您還可以通過傳遞 Action 子類或實現相同接口的其他對象來指定任意操作。建議的方法是擴展 [`Action`](#argparse.Action "argparse.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')
```
更多描述,見 [`Action`](#argparse.Action "argparse.Action")。
### nargs
ArgumentParser 對象通常關聯一個單獨的命令行參數到一個單獨的被執行的動作。 `nargs` 命名參數關聯不同數目的命令行參數到單一動作。支持的值有:
- `N` (一個整數)。命令行中的 `N` 個參數會被聚集到一個列表中。 例如:
```
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo', nargs=2)
>>> parser.add_argument('bar', nargs=1)
>>> parser.parse_args('c --foo a b'.split())
Namespace(bar=['c'], foo=['a', 'b'])
```
注意 `nargs=1` 會產生一個單元素列表。這和默認的元素本身是不同的。
- `'?'`。如果可能的話,會從命令行中消耗一個參數,并產生一個單一項。如果當前沒有命令行參數,則會產生 [default](#default) 值。注意,對于選項,有另外的用例 - 選項字符串出現但沒有跟隨命令行參數,則會產生 [const](#const) 值。一些說用用例:
```
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo', nargs='?', const='c', default='d')
>>> parser.add_argument('bar', nargs='?', default='d')
>>> parser.parse_args(['XX', '--foo', 'YY'])
Namespace(bar='XX', foo='YY')
>>> parser.parse_args(['XX', '--foo'])
Namespace(bar='XX', foo='c')
>>> parser.parse_args([])
Namespace(bar='d', foo='d')
```
`nargs='?'` 的一個更普遍用法是允許可選的輸入或輸出文件:
```
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('infile', nargs='?', type=argparse.FileType('r'),
... default=sys.stdin)
>>> parser.add_argument('outfile', nargs='?', type=argparse.FileType('w'),
... default=sys.stdout)
>>> parser.parse_args(['input.txt', 'output.txt'])
Namespace(infile=<_io.TextIOWrapper name='input.txt' encoding='UTF-8'>,
outfile=<_io.TextIOWrapper name='output.txt' encoding='UTF-8'>)
>>> parser.parse_args([])
Namespace(infile=<_io.TextIOWrapper name='<stdin>' encoding='UTF-8'>,
outfile=<_io.TextIOWrapper name='<stdout>' encoding='UTF-8'>)
```
- `'*'`。所有當前命令行參數被聚集到一個列表中。注意通過 `nargs='*'` 來實現多個位置參數通常沒有意義,但是多個選項是可能的。例如:
```
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo', nargs='*')
>>> parser.add_argument('--bar', nargs='*')
>>> parser.add_argument('baz', nargs='*')
>>> parser.parse_args('a b --foo x y --bar 1 2'.split())
Namespace(bar=['1', '2'], baz=['a', 'b'], foo=['x', 'y'])
```
- `'+'`。和 `'*'` 類似,所有當前命令行參數被聚集到一個列表中。另外,當前沒有至少一個命令行參數時會產生一個錯誤信息。例如:
```
>>> 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
```
- `argarse.REMAINDER`。所有剩余的命令行參數被聚集到一個列表中。這通常在從一個命令行功能傳遞參數到另一個命令行功能中時有用:
```
>>> parser = argparse.ArgumentParser(prog='PROG')
>>> parser.add_argument('--foo')
>>> parser.add_argument('command')
>>> parser.add_argument('args', nargs=argparse.REMAINDER)
>>> print(parser.parse_args('--foo B cmd --arg1 XX ZZ'.split()))
Namespace(args=['--arg1', 'XX', 'ZZ'], command='cmd', foo='B')
```
如果不提供 `nargs` 命名參數,則消耗參數的數目將被 [action](#action) 決定。通常這意味著單一項目(非列表)消耗單一命令行參數。
### const
[`add_argument()`](#argparse.ArgumentParser.add_argument "argparse.ArgumentParser.add_argument") 的``const`` 參數用于保存不從命令行中讀取但被各種 [`ArgumentParser`](#argparse.ArgumentParser "argparse.ArgumentParser") 動作需求的常數值。最常用的兩例為:
- 當 [`add_argument()`](#argparse.ArgumentParser.add_argument "argparse.ArgumentParser.add_argument") 通過 `action='store_const'` 或 `action='append_const` 調用時。這些動作將 `const` 值添加到 [`parse_args()`](#argparse.ArgumentParser.parse_args "argparse.ArgumentParser.parse_args") 返回的對象的屬性中。在 [action](#action) 的描述中查看案例。
- 當 [`add_argument()`](#argparse.ArgumentParser.add_argument "argparse.ArgumentParser.add_argument") 通過選項(例如 `-f` 或 `--foo`)調用并且 `nargs='?'` 時。這會創建一個可以跟隨零個或一個命令行參數的選項。當解析命令行時,如果選項后沒有參數,則將用 `const` 代替。在 [nargs](#nargs) 描述中查看案例。
對 `'store_const'` 和 `'append_const'` 動作, `const` 命名參數必須給出。對其他動作,默認為 `None`。
### default
所有選項和一些位置參數可能在命令行中被忽略。[`add_argument()`](#argparse.ArgumentParser.add_argument "argparse.ArgumentParser.add_argument") 的命名參數 `default`,默認值為 `None`,指定了在命令行參數未出現時應當使用的值。對于選項, `default` 值在選項未在命令行中出現時使用:
```
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo', default=42)
>>> parser.parse_args(['--foo', '2'])
Namespace(foo='2')
>>> parser.parse_args([])
Namespace(foo=42)
```
如果 `default` 值是一個字符串,解析器解析此值就像一個命令行參數。特別是,在將屬性設置在 [`Namespace`](#argparse.Namespace "argparse.Namespace") 的返回值之前,解析器應用任何提供的 [type](#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](#nargs) 等于 `?` 或 `*` 的位置參數, `default` 值在沒有命令行參數出現時使用。
```
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('foo', nargs='?', default=42)
>>> parser.parse_args(['a'])
Namespace(foo='a')
>>> parser.parse_args([])
Namespace(foo=42)
```
提供 `default=argparse.SUPPRESS` 導致命令行參數未出現時沒有屬性被添加:
```
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo', default=argparse.SUPPRESS)
>>> parser.parse_args([])
Namespace()
>>> parser.parse_args(['--foo', '1'])
Namespace(foo='1')
```
### type
By default, [`ArgumentParser`](#argparse.ArgumentParser "argparse.ArgumentParser") objects read command-line arguments in as simple strings. However, quite often the command-line string should instead be interpreted as another type, like a [`float`](functions.xhtml#float "float") or [`int`](functions.xhtml#int "int"). The `type` keyword argument of [`add_argument()`](#argparse.ArgumentParser.add_argument "argparse.ArgumentParser.add_argument") allows any necessary type-checking and type conversions to be performed. Common built-in types and functions can be used directly as the value of the `type` argument:
```
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('foo', type=int)
>>> parser.add_argument('bar', type=open)
>>> parser.parse_args('2 temp.txt'.split())
Namespace(bar=<_io.TextIOWrapper name='temp.txt' encoding='UTF-8'>, foo=2)
```
See the section on the [default](#default) keyword argument for information on when the `type` argument is applied to default arguments.
To ease the use of various types of files, the argparse module provides the factory FileType which takes the `mode=`, `bufsize=`, `encoding=` and `errors=` arguments of the [`open()`](functions.xhtml#open "open") function. For example, `FileType('w')` can be used to create a writable file:
```
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('bar', type=argparse.FileType('w'))
>>> parser.parse_args(['out.txt'])
Namespace(bar=<_io.TextIOWrapper name='out.txt' encoding='UTF-8'>)
```
`type=` can take any callable that takes a single string argument and returns the converted value:
```
>>> def perfect_square(string):
... value = int(string)
... sqrt = math.sqrt(value)
... if sqrt != int(sqrt):
... msg = "%r is not a perfect square" % string
... raise argparse.ArgumentTypeError(msg)
... return value
...
>>> parser = argparse.ArgumentParser(prog='PROG')
>>> parser.add_argument('foo', type=perfect_square)
>>> parser.parse_args(['9'])
Namespace(foo=9)
>>> parser.parse_args(['7'])
usage: PROG [-h] foo
PROG: error: argument foo: '7' is not a perfect square
```
The [choices](#choices) keyword argument may be more convenient for type checkers that simply check against a range of values:
```
>>> 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](#choices) section for more details.
### choices
Some command-line arguments should be selected from a restricted set of values. These can be handled by passing a container object as the *choices* keyword argument to [`add_argument()`](#argparse.ArgumentParser.add_argument "argparse.ArgumentParser.add_argument"). When the command line is parsed, argument values will be checked, and an error message will be displayed if the argument was not one of the acceptable values:
```
>>> parser = argparse.ArgumentParser(prog='game.py')
>>> parser.add_argument('move', choices=['rock', 'paper', 'scissors'])
>>> parser.parse_args(['rock'])
Namespace(move='rock')
>>> parser.parse_args(['fire'])
usage: game.py [-h] {rock,paper,scissors}
game.py: error: argument move: invalid choice: 'fire' (choose from 'rock',
'paper', 'scissors')
```
Note that inclusion in the *choices* container is checked after any [type](#type)conversions have been performed, so the type of the objects in the *choices*container should match the [type](#type) specified:
```
>>> parser = argparse.ArgumentParser(prog='doors.py')
>>> parser.add_argument('door', type=int, choices=range(1, 4))
>>> print(parser.parse_args(['3']))
Namespace(door=3)
>>> parser.parse_args(['4'])
usage: doors.py [-h] {1,2,3}
doors.py: error: argument door: invalid choice: 4 (choose from 1, 2, 3)
```
Any object that supports the `in` operator can be passed as the *choices*value, so [`dict`](stdtypes.xhtml#dict "dict") objects, [`set`](stdtypes.xhtml#set "set") objects, custom containers, etc. are all supported.
### required
In general, the [`argparse`](#module-argparse "argparse: Command-line option and argument parsing library.") module assumes that flags like `-f` and `--bar`indicate *optional* arguments, which can always be omitted at the command line. To make an option *required*, `True` can be specified for the `required=`keyword argument to [`add_argument()`](#argparse.ArgumentParser.add_argument "argparse.ArgumentParser.add_argument"):
```
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo', required=True)
>>> parser.parse_args(['--foo', 'BAR'])
Namespace(foo='BAR')
>>> parser.parse_args([])
usage: argparse.py [-h] [--foo FOO]
argparse.py: error: option --foo is required
```
As the example shows, if an option is marked as `required`, [`parse_args()`](#argparse.ArgumentParser.parse_args "argparse.ArgumentParser.parse_args") will report an error if that option is not present at the command line.
注解
Required options are generally considered bad form because users expect *options* to be *optional*, and thus they should be avoided when possible.
### help
The `help` value is a string containing a brief description of the argument. When a user requests help (usually by using `-h` or `--help` at the command line), these `help` descriptions will be displayed with each argument:
```
>>> parser = argparse.ArgumentParser(prog='frobble')
>>> parser.add_argument('--foo', action='store_true',
... help='foo the bars before frobbling')
>>> parser.add_argument('bar', nargs='+',
... help='one of the bars to be frobbled')
>>> parser.parse_args(['-h'])
usage: frobble [-h] [--foo] bar [bar ...]
positional arguments:
bar one of the bars to be frobbled
optional arguments:
-h, --help show this help message and exit
--foo foo the bars before frobbling
```
The `help` strings can include various format specifiers to avoid repetition of things like the program name or the argument [default](#default). The available specifiers include the program name, `%(prog)s` and most keyword arguments to [`add_argument()`](#argparse.ArgumentParser.add_argument "argparse.ArgumentParser.add_argument"), e.g. `%(default)s`, `%(type)s`, etc.:
```
>>> parser = argparse.ArgumentParser(prog='frobble')
>>> parser.add_argument('bar', nargs='?', type=int, default=42,
... help='the bar to %(prog)s (default: %(default)s)')
>>> parser.print_help()
usage: frobble [-h] [bar]
positional arguments:
bar the bar to frobble (default: 42)
optional arguments:
-h, --help show this help message and exit
```
As the help string supports %-formatting, if you want a literal `%` to appear in the help string, you must escape it as `%%`.
[`argparse`](#module-argparse "argparse: Command-line option and argument parsing library.") supports silencing the help entry for certain options, by setting the `help` value to `argparse.SUPPRESS`:
```
>>> 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
```
### metavar
When [`ArgumentParser`](#argparse.ArgumentParser "argparse.ArgumentParser") generates help messages, it needs some way to refer to each expected argument. By default, ArgumentParser objects use the [dest](#dest)value as the "name" of each object. By default, for positional argument actions, the [dest](#dest) value is used directly, and for optional argument actions, the [dest](#dest) value is uppercased. So, a single positional argument with `dest='bar'` will be referred to as `bar`. A single optional argument `--foo` that should be followed by a single command-line argument will be referred to as `FOO`. An example:
```
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo')
>>> parser.add_argument('bar')
>>> parser.parse_args('X --foo Y'.split())
Namespace(bar='X', foo='Y')
>>> parser.print_help()
usage: [-h] [--foo FOO] bar
positional arguments:
bar
optional arguments:
-h, --help show this help message and exit
--foo FOO
```
An alternative name can be specified with `metavar`:
```
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo', metavar='YYY')
>>> parser.add_argument('bar', metavar='XXX')
>>> parser.parse_args('X --foo Y'.split())
Namespace(bar='X', foo='Y')
>>> parser.print_help()
usage: [-h] [--foo YYY] XXX
positional arguments:
XXX
optional arguments:
-h, --help show this help message and exit
--foo YYY
```
Note that `metavar` only changes the *displayed* name - the name of the attribute on the [`parse_args()`](#argparse.ArgumentParser.parse_args "argparse.ArgumentParser.parse_args") object is still determined by the [dest](#dest) value.
Different values of `nargs` may cause the metavar to be used multiple times. Providing a tuple to `metavar` specifies a different display for each of the arguments:
```
>>> 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
Most [`ArgumentParser`](#argparse.ArgumentParser "argparse.ArgumentParser") actions add some value as an attribute of the object returned by [`parse_args()`](#argparse.ArgumentParser.parse_args "argparse.ArgumentParser.parse_args"). The name of this attribute is determined by the `dest` keyword argument of [`add_argument()`](#argparse.ArgumentParser.add_argument "argparse.ArgumentParser.add_argument"). For positional argument actions, `dest` is normally supplied as the first argument to [`add_argument()`](#argparse.ArgumentParser.add_argument "argparse.ArgumentParser.add_argument"):
```
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('bar')
>>> parser.parse_args(['XXX'])
Namespace(bar='XXX')
```
For optional argument actions, the value of `dest` is normally inferred from the option strings. [`ArgumentParser`](#argparse.ArgumentParser "argparse.ArgumentParser") generates the value of `dest` by taking the first long option string and stripping away the initial `--`string. If no long option strings were supplied, `dest` will be derived from the first short option string by stripping the initial `-` character. Any internal `-` characters will be converted to `_` characters to make sure the string is a valid attribute name. The examples below illustrate this behavior:
```
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('-f', '--foo-bar', '--foo')
>>> parser.add_argument('-x', '-y')
>>> parser.parse_args('-f 1 -x 2'.split())
Namespace(foo_bar='1', x='2')
>>> parser.parse_args('--foo 1 -y 2'.split())
Namespace(foo_bar='1', x='2')
```
`dest` allows a custom attribute name to be provided:
```
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo', dest='bar')
>>> parser.parse_args('--foo XXX'.split())
Namespace(bar='XXX')
```
### Action classes
Action classes implement the Action API, a callable which returns a callable which processes arguments from the command-line. Any object which follows this API may be passed as the `action` parameter to `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 objects are used by an ArgumentParser to represent the information needed to parse a single argument from one or more strings from the command line. The Action class must accept the two positional arguments plus any keyword arguments passed to [`ArgumentParser.add_argument()`](#argparse.ArgumentParser.add_argument "argparse.ArgumentParser.add_argument")except for the `action` itself.
Instances of Action (or return value of any callable to the `action`parameter) should have attributes "dest", "option\_strings", "default", "type", "required", "help", etc. defined. The easiest way to ensure these attributes are defined is to call `Action.__init__`.
Action instances should be callable, so subclasses must override the `__call__` method, which should accept four parameters:
- `parser` - The ArgumentParser object which contains this action.
- `namespace` - The [`Namespace`](#argparse.Namespace "argparse.Namespace") object that will be returned by [`parse_args()`](#argparse.ArgumentParser.parse_args "argparse.ArgumentParser.parse_args"). Most actions add an attribute to this object using [`setattr()`](functions.xhtml#setattr "setattr").
- `values` - The associated command-line arguments, with any type conversions applied. Type conversions are specified with the [type](#type) keyword argument to [`add_argument()`](#argparse.ArgumentParser.add_argument "argparse.ArgumentParser.add_argument").
- `option_string` - The option string that was used to invoke this action. The `option_string` argument is optional, and will be absent if the action is associated with a positional argument.
The `__call__` method may perform arbitrary actions, but will typically set attributes on the `namespace` based on `dest` and `values`.
## The parse\_args() method
`ArgumentParser.``parse_args`(*args=None*, *namespace=None*)Convert argument strings to objects and assign them as attributes of the namespace. Return the populated namespace.
Previous calls to [`add_argument()`](#argparse.ArgumentParser.add_argument "argparse.ArgumentParser.add_argument") determine exactly what objects are created and how they are assigned. See the documentation for [`add_argument()`](#argparse.ArgumentParser.add_argument "argparse.ArgumentParser.add_argument") for details.
- [args](#args) - List of strings to parse. The default is taken from [`sys.argv`](sys.xhtml#sys.argv "sys.argv").
- [namespace](#namespace) - An object to take the attributes. The default is a new empty [`Namespace`](#argparse.Namespace "argparse.Namespace") object.
### Option value syntax
The [`parse_args()`](#argparse.ArgumentParser.parse_args "argparse.ArgumentParser.parse_args") method supports several ways of specifying the value of an option (if it takes one). In the simplest case, the option and its value are passed as two separate arguments:
```
>>> 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)
```
For long options (options with names longer than a single character), the option and value can also be passed as a single command-line argument, using `=` to separate them:
```
>>> parser.parse_args(['--foo=FOO'])
Namespace(foo='FOO', x=None)
```
For short options (options only one character long), the option and its value can be concatenated:
```
>>> parser.parse_args(['-xX'])
Namespace(foo=None, x='X')
```
Several short options can be joined together, using only a single `-` prefix, as long as only the last option (or none of them) requires a value:
```
>>> 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
While parsing the command line, [`parse_args()`](#argparse.ArgumentParser.parse_args "argparse.ArgumentParser.parse_args") checks for a variety of errors, including ambiguous options, invalid types, invalid options, wrong number of positional arguments, etc. When it encounters such an error, it exits and prints the error along with a usage message:
```
>>> 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 `-`
The [`parse_args()`](#argparse.ArgumentParser.parse_args "argparse.ArgumentParser.parse_args") method attempts to give errors whenever the user has clearly made a mistake, but some situations are inherently ambiguous. For example, the command-line argument `-1` could either be an attempt to specify an option or an attempt to provide a positional argument. The [`parse_args()`](#argparse.ArgumentParser.parse_args "argparse.ArgumentParser.parse_args") method is cautious here: positional arguments may only begin with `-` if they look like negative numbers and there are no options in the parser that look like negative numbers:
```
>>> 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
```
If you have positional arguments that must begin with `-` and don't look like negative numbers, you can insert the pseudo-argument `'--'` which tells [`parse_args()`](#argparse.ArgumentParser.parse_args "argparse.ArgumentParser.parse_args") that everything after that is a positional argument:
```
>>> parser.parse_args(['--', '-f'])
Namespace(foo='-f', one=None)
```
### Argument abbreviations (prefix matching)
The [`parse_args()`](#argparse.ArgumentParser.parse_args "argparse.ArgumentParser.parse_args") method [by default](#allow-abbrev)allows long options to be abbreviated to a prefix, if the abbreviation is unambiguous (the prefix matches a unique option):
```
>>> 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
```
An error is produced for arguments that could produce more than one options. This feature can be disabled by setting [allow\_abbrev](#allow-abbrev) to `False`.
### Beyond `sys.argv`
Sometimes it may be useful to have an ArgumentParser parse arguments other than those of [`sys.argv`](sys.xhtml#sys.argv "sys.argv"). This can be accomplished by passing a list of strings to [`parse_args()`](#argparse.ArgumentParser.parse_args "argparse.ArgumentParser.parse_args"). This is useful for testing at the interactive prompt:
```
>>> 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
*class* `argparse.``Namespace`Simple class used by default by [`parse_args()`](#argparse.ArgumentParser.parse_args "argparse.ArgumentParser.parse_args") to create an object holding attributes and return it.
This class is deliberately simple, just an [`object`](functions.xhtml#object "object") subclass with a readable string representation. If you prefer to have dict-like view of the attributes, you can use the standard Python idiom, [`vars()`](functions.xhtml#vars "vars"):
```
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo')
>>> args = parser.parse_args(['--foo', 'BAR'])
>>> vars(args)
{'foo': 'BAR'}
```
It may also be useful to have an [`ArgumentParser`](#argparse.ArgumentParser "argparse.ArgumentParser") assign attributes to an already existing object, rather than a new [`Namespace`](#argparse.Namespace "argparse.Namespace") object. This can be achieved by specifying the `namespace=` keyword argument:
```
>>> class C:
... pass
...
>>> c = C()
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo')
>>> parser.parse_args(args=['--foo', 'BAR'], namespace=c)
>>> c.foo
'BAR'
```
## Other utilities
### Sub-commands
`ArgumentParser.``add_subparsers`(\[*title*\]\[, *description*\]\[, *prog*\]\[, *parser\_class*\]\[, *action*\]\[, *option\_string*\]\[, *dest*\]\[, *required*\]\[, *help*\]\[, *metavar*\])Many programs split up their functionality into a number of sub-commands, for example, the `svn` program can invoke sub-commands like
```
svn
checkout
```
, `svn update`, and `svn commit`. Splitting up functionality this way can be a particularly good idea when a program performs several different functions which require different kinds of command-line arguments. [`ArgumentParser`](#argparse.ArgumentParser "argparse.ArgumentParser") supports the creation of such sub-commands with the [`add_subparsers()`](#argparse.ArgumentParser.add_subparsers "argparse.ArgumentParser.add_subparsers") method. The [`add_subparsers()`](#argparse.ArgumentParser.add_subparsers "argparse.ArgumentParser.add_subparsers") method is normally called with no arguments and returns a special action object. This object has a single method, `add_parser()`, which takes a command name and any [`ArgumentParser`](#argparse.ArgumentParser "argparse.ArgumentParser") constructor arguments, and returns an [`ArgumentParser`](#argparse.ArgumentParser "argparse.ArgumentParser") object that can be modified as usual.
Description of parameters:
- title - title for the sub-parser group in help output; by default "subcommands" if description is provided, otherwise uses title for positional arguments
- description - description for the sub-parser group in help output, by default `None`
- prog - usage information that will be displayed with sub-command help, by default the name of the program and any positional arguments before the subparser argument
- parser\_class - class which will be used to create sub-parser instances, by default the class of the current parser (e.g. ArgumentParser)
- [action](#action) - the basic type of action to be taken when this argument is encountered at the command line
- [dest](#dest) - name of the attribute under which sub-command name will be stored; by default `None` and no value is stored
- [required](#required) - Whether or not a subcommand must be provided, by default `False`.
- [help](#help) - help for sub-parser group in help output, by default `None`
- [metavar](#metavar) - string presenting available sub-commands in help; by default it is `None` and presents sub-commands in form {cmd1, cmd2, ..}
Some example usage:
```
>>> # 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)
```
Note that the object returned by [`parse_args()`](#argparse.ArgumentParser.parse_args "argparse.ArgumentParser.parse_args") will only contain attributes for the main parser and the subparser that was selected by the command line (and not any other subparsers). So in the example above, when the `a` command is specified, only the `foo` and `bar` attributes are present, and when the `b` command is specified, only the `foo` and `baz` attributes are present.
Similarly, when a help message is requested from a subparser, only the help for that particular parser will be printed. The help message will not include parent parser or sibling parser messages. (A help message for each subparser command, however, can be given by supplying the `help=` argument to `add_parser()` as above.)
```
>>> 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
```
The [`add_subparsers()`](#argparse.ArgumentParser.add_subparsers "argparse.ArgumentParser.add_subparsers") method also supports `title` and `description`keyword arguments. When either is present, the subparser's commands will appear in their own group in the help output. For example:
```
>>> 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
```
Furthermore, `add_parser` supports an additional `aliases` argument, which allows multiple strings to refer to the same subparser. This example, like `svn`, aliases `co` as a shorthand for `checkout`:
```
>>> 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')
```
One particularly effective way of handling sub-commands is to combine the use of the [`add_subparsers()`](#argparse.ArgumentParser.add_subparsers "argparse.ArgumentParser.add_subparsers") method with calls to [`set_defaults()`](#argparse.ArgumentParser.set_defaults "argparse.ArgumentParser.set_defaults") so that each subparser knows which Python function it should execute. For example:
```
>>> # 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))
```
This way, you can let [`parse_args()`](#argparse.ArgumentParser.parse_args "argparse.ArgumentParser.parse_args") do the job of calling the appropriate function after argument parsing is complete. Associating functions with actions like this is typically the easiest way to handle the different actions for each of your subparsers. However, if it is necessary to check the name of the subparser that was invoked, the `dest` keyword argument to the [`add_subparsers()`](#argparse.ArgumentParser.add_subparsers "argparse.ArgumentParser.add_subparsers") call will work:
```
>>> 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
*class* `argparse.``FileType`(*mode='r'*, *bufsize=-1*, *encoding=None*, *errors=None*)The [`FileType`](#argparse.FileType "argparse.FileType") factory creates objects that can be passed to the type argument of [`ArgumentParser.add_argument()`](#argparse.ArgumentParser.add_argument "argparse.ArgumentParser.add_argument"). Arguments that have [`FileType`](#argparse.FileType "argparse.FileType") objects as their type will open command-line arguments as files with the requested modes, buffer sizes, encodings and error handling (see the [`open()`](functions.xhtml#open "open") function for more details):
```
>>> 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 objects understand the pseudo-argument `'-'` and automatically convert this into `sys.stdin` for readable [`FileType`](#argparse.FileType "argparse.FileType") objects and `sys.stdout` for writable [`FileType`](#argparse.FileType "argparse.FileType") objects:
```
>>> 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 新版功能: The *encodings* and *errors* keyword arguments.
### Argument groups
`ArgumentParser.``add_argument_group`(*title=None*, *description=None*)By default, [`ArgumentParser`](#argparse.ArgumentParser "argparse.ArgumentParser") groups command-line arguments into "positional arguments" and "optional arguments" when displaying help messages. When there is a better conceptual grouping of arguments than this default one, appropriate groups can be created using the [`add_argument_group()`](#argparse.ArgumentParser.add_argument_group "argparse.ArgumentParser.add_argument_group") method:
```
>>> 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
```
The [`add_argument_group()`](#argparse.ArgumentParser.add_argument_group "argparse.ArgumentParser.add_argument_group") method returns an argument group object which has an [`add_argument()`](#argparse.ArgumentParser.add_argument "argparse.ArgumentParser.add_argument") method just like a regular [`ArgumentParser`](#argparse.ArgumentParser "argparse.ArgumentParser"). When an argument is added to the group, the parser treats it just like a normal argument, but displays the argument in a separate group for help messages. The [`add_argument_group()`](#argparse.ArgumentParser.add_argument_group "argparse.ArgumentParser.add_argument_group") method accepts *title* and *description* arguments which can be used to customize this display:
```
>>> 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
```
Note that any arguments not in your user-defined groups will end up back in the usual "positional arguments" and "optional arguments" sections.
### Mutual exclusion
`ArgumentParser.``add_mutually_exclusive_group`(*required=False*)創建一個互斥組。 [`argparse`](#module-argparse "argparse: Command-line option and argument parsing library.") 將會確保互斥組中只有一個參數在命令行中可用:
```
>>> 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()`](#argparse.ArgumentParser.add_mutually_exclusive_group "argparse.ArgumentParser.add_mutually_exclusive_group") 方法也接受一個 *required* 參數,表示在互斥組中至少有一個參數是需要的:
```
>>> 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()`](#argparse.ArgumentParser.add_argument_group "argparse.ArgumentParser.add_argument_group") 的 *title* 和 *description* 參數。
### Parser defaults
`ArgumentParser.``set_defaults`(*\*\*kwargs*)Most of the time, the attributes of the object returned by [`parse_args()`](#argparse.ArgumentParser.parse_args "argparse.ArgumentParser.parse_args")will be fully determined by inspecting the command-line arguments and the argument actions. [`set_defaults()`](#argparse.ArgumentParser.set_defaults "argparse.ArgumentParser.set_defaults") allows some additional attributes that are determined without any inspection of the command line to be added:
```
>>> 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)
```
Note that parser-level defaults always override argument-level defaults:
```
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo', default='bar')
>>> parser.set_defaults(foo='spam')
>>> parser.parse_args([])
Namespace(foo='spam')
```
Parser-level defaults can be particularly useful when working with multiple parsers. See the [`add_subparsers()`](#argparse.ArgumentParser.add_subparsers "argparse.ArgumentParser.add_subparsers") method for an example of this type.
`ArgumentParser.``get_default`(*dest*)Get the default value for a namespace attribute, as set by either [`add_argument()`](#argparse.ArgumentParser.add_argument "argparse.ArgumentParser.add_argument") or by [`set_defaults()`](#argparse.ArgumentParser.set_defaults "argparse.ArgumentParser.set_defaults"):
```
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo', default='badger')
>>> parser.get_default('foo')
'badger'
```
### Printing help
In most typical applications, [`parse_args()`](#argparse.ArgumentParser.parse_args "argparse.ArgumentParser.parse_args") will take care of formatting and printing any usage or error messages. However, several formatting methods are available:
`ArgumentParser.``print_usage`(*file=None*)Print a brief description of how the [`ArgumentParser`](#argparse.ArgumentParser "argparse.ArgumentParser") should be invoked on the command line. If *file* is `None`, [`sys.stdout`](sys.xhtml#sys.stdout "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`](#argparse.ArgumentParser "argparse.ArgumentParser"). If *file* is `None`, [`sys.stdout`](sys.xhtml#sys.stdout "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`](#argparse.ArgumentParser "argparse.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`](#argparse.ArgumentParser "argparse.ArgumentParser").
### Partial parsing
`ArgumentParser.``parse_known_args`(*args=None*, *namespace=None*)Sometimes a script may only parse a few of the command-line arguments, passing the remaining arguments on to another script or program. In these cases, the [`parse_known_args()`](#argparse.ArgumentParser.parse_known_args "argparse.ArgumentParser.parse_known_args") method can be useful. It works much like [`parse_args()`](#argparse.ArgumentParser.parse_args "argparse.ArgumentParser.parse_args") except that it does not produce an error when extra arguments are present. Instead, it returns a two item tuple containing the populated namespace and the list of remaining argument strings.
```
>>> 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'])
```
警告
[Prefix matching](#prefix-matching) rules apply to `parse_known_args()`. The parser may consume an option even if it's just a prefix of one of its known options, instead of leaving it in the remaining arguments list.
### Customizing file parsing
`ArgumentParser.``convert_arg_line_to_args`(*arg\_line*)Arguments that are read from a file (see the *fromfile\_prefix\_chars*keyword argument to the [`ArgumentParser`](#argparse.ArgumentParser "argparse.ArgumentParser") constructor) are read one argument per line. [`convert_arg_line_to_args()`](#argparse.ArgumentParser.convert_arg_line_to_args "argparse.ArgumentParser.convert_arg_line_to_args") can be overridden for fancier reading.
This method takes a single argument *arg\_line* which is a string read from the argument file. It returns a list of arguments parsed from this string. The method is called once per line read from the argument file, in order.
A useful override of this method is one that treats each space-separated word as an argument. The following example demonstrates how to do this:
```
class MyArgumentParser(argparse.ArgumentParser):
def convert_arg_line_to_args(self, arg_line):
return arg_line.split()
```
### Exiting methods
`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.
### Intermixed parsing
`ArgumentParser.``parse_intermixed_args`(*args=None*, *namespace=None*)`ArgumentParser.``parse_known_intermixed_args`(*args=None*, *namespace=None*)A number of Unix commands allow the user to intermix optional arguments with positional arguments. The [`parse_intermixed_args()`](#argparse.ArgumentParser.parse_intermixed_args "argparse.ArgumentParser.parse_intermixed_args")and [`parse_known_intermixed_args()`](#argparse.ArgumentParser.parse_known_intermixed_args "argparse.ArgumentParser.parse_known_intermixed_args") methods support this parsing style.
These parsers do not support all the argparse features, and will raise exceptions if unsupported features are used. In particular, subparsers, `argparse.REMAINDER`, and mutually exclusive groups that include both optionals and positionals are not supported.
The following example shows the difference between [`parse_known_args()`](#argparse.ArgumentParser.parse_known_args "argparse.ArgumentParser.parse_known_args") and [`parse_intermixed_args()`](#argparse.ArgumentParser.parse_intermixed_args "argparse.ArgumentParser.parse_intermixed_args"): the former returns
```
['2',
'3']
```
as unparsed arguments, while the latter collects all the positionals into `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()`](#argparse.ArgumentParser.parse_known_intermixed_args "argparse.ArgumentParser.parse_known_intermixed_args") returns a two item tuple containing the populated namespace and the list of remaining argument strings. [`parse_intermixed_args()`](#argparse.ArgumentParser.parse_intermixed_args "argparse.ArgumentParser.parse_intermixed_args") raises an error if there are any remaining unparsed argument strings.
3\.7 新版功能.
## Upgrading optparse code
Originally, the [`argparse`](#module-argparse "argparse: Command-line option and argument parsing library.") module had attempted to maintain compatibility with [`optparse`](optparse.xhtml#module-optparse "optparse: Command-line option parsing library. (已移除)"). However, [`optparse`](optparse.xhtml#module-optparse "optparse: Command-line option parsing library. (已移除)") was difficult to extend transparently, particularly with the changes required to support the new `nargs=` specifiers and better usage messages. When most everything in [`optparse`](optparse.xhtml#module-optparse "optparse: Command-line option parsing library. (已移除)") had either been copy-pasted over or monkey-patched, it no longer seemed practical to try to maintain the backwards compatibility.
The [`argparse`](#module-argparse "argparse: Command-line option and argument parsing library.") module improves on the standard library [`optparse`](optparse.xhtml#module-optparse "optparse: Command-line option parsing library. (已移除)")module in a number of ways including:
- Handling positional arguments.
- Supporting sub-commands.
- Allowing alternative option prefixes like `+` and `/`.
- Handling zero-or-more and one-or-more style arguments.
- Producing more informative usage messages.
- Providing a much simpler interface for custom `type` and `action`.
A partial upgrade path from [`optparse`](optparse.xhtml#module-optparse "optparse: Command-line option parsing library. (已移除)") to [`argparse`](#module-argparse "argparse: Command-line option and argument parsing library."):
- Replace all [`optparse.OptionParser.add_option()`](optparse.xhtml#optparse.OptionParser.add_option "optparse.OptionParser.add_option") calls with [`ArgumentParser.add_argument()`](#argparse.ArgumentParser.add_argument "argparse.ArgumentParser.add_argument") calls.
- Replace `(options, args) = parser.parse_args()` with
```
args =
parser.parse_args()
```
and add additional [`ArgumentParser.add_argument()`](#argparse.ArgumentParser.add_argument "argparse.ArgumentParser.add_argument")calls for the positional arguments. Keep in mind that what was previously called `options`, now in the [`argparse`](#module-argparse "argparse: Command-line option and argument parsing library.") context is called `args`.
- Replace [`optparse.OptionParser.disable_interspersed_args()`](optparse.xhtml#optparse.OptionParser.disable_interspersed_args "optparse.OptionParser.disable_interspersed_args")by using [`parse_intermixed_args()`](#argparse.ArgumentParser.parse_intermixed_args "argparse.ArgumentParser.parse_intermixed_args") instead of [`parse_args()`](#argparse.ArgumentParser.parse_args "argparse.ArgumentParser.parse_args").
- Replace callback actions and the `callback_*` keyword arguments with `type` or `action` arguments.
- Replace string names for `type` keyword arguments with the corresponding type objects (e.g. int, float, complex, etc).
- Replace `optparse.Values` with [`Namespace`](#argparse.Namespace "argparse.Namespace") and `optparse.OptionError` and `optparse.OptionValueError` with `ArgumentError`.
- Replace strings with implicit arguments such as `%default` or `%prog` with the standard Python syntax to use dictionaries to format strings, that is, `%(default)s` and `%(prog)s`.
- Replace the OptionParser constructor `version` argument with a call to `parser.add_argument('--version', action='version', version='<the version>')`.
### 導航
- [索引](../genindex.xhtml "總目錄")
- [模塊](../py-modindex.xhtml "Python 模塊索引") |
- [下一頁](getopt.xhtml "getopt --- C-style parser for command line options") |
- [上一頁](time.xhtml "time --- 時間的訪問和轉換") |
- 
- [Python](https://www.python.org/) ?
- zh\_CN 3.7.3 [文檔](../index.xhtml) ?
- [Python 標準庫](index.xhtml) ?
- [通用操作系統服務](allos.xhtml) ?
- $('.inline-search').show(0); |
? [版權所有](../copyright.xhtml) 2001-2019, Python Software Foundation.
Python 軟件基金會是一個非盈利組織。 [請捐助。](https://www.python.org/psf/donations/)
最后更新于 5月 21, 2019. [發現了問題](../bugs.xhtml)?
使用[Sphinx](http://sphinx.pocoo.org/)1.8.4 創建。
- Python文檔內容
- Python 有什么新變化?
- Python 3.7 有什么新變化
- 摘要 - 發布重點
- 新的特性
- 其他語言特性修改
- 新增模塊
- 改進的模塊
- C API 的改變
- 構建的改變
- 性能優化
- 其他 CPython 實現的改變
- 已棄用的 Python 行為
- 已棄用的 Python 模塊、函數和方法
- 已棄用的 C API 函數和類型
- 平臺支持的移除
- API 與特性的移除
- 移除的模塊
- Windows 專屬的改變
- 移植到 Python 3.7
- Python 3.7.1 中的重要變化
- Python 3.7.2 中的重要變化
- Python 3.6 有什么新變化A
- 摘要 - 發布重點
- 新的特性
- 其他語言特性修改
- 新增模塊
- 改進的模塊
- 性能優化
- Build and C API Changes
- 其他改進
- 棄用
- 移除
- 移植到Python 3.6
- Python 3.6.2 中的重要變化
- Python 3.6.4 中的重要變化
- Python 3.6.5 中的重要變化
- Python 3.6.7 中的重要變化
- Python 3.5 有什么新變化
- 摘要 - 發布重點
- 新的特性
- 其他語言特性修改
- 新增模塊
- 改進的模塊
- Other module-level changes
- 性能優化
- Build and C API Changes
- 棄用
- 移除
- Porting to Python 3.5
- Notable changes in Python 3.5.4
- What's New In Python 3.4
- 摘要 - 發布重點
- 新的特性
- 新增模塊
- 改進的模塊
- CPython Implementation Changes
- 棄用
- 移除
- Porting to Python 3.4
- Changed in 3.4.3
- What's New In Python 3.3
- 摘要 - 發布重點
- PEP 405: Virtual Environments
- PEP 420: Implicit Namespace Packages
- PEP 3118: New memoryview implementation and buffer protocol documentation
- PEP 393: Flexible String Representation
- PEP 397: Python Launcher for Windows
- PEP 3151: Reworking the OS and IO exception hierarchy
- PEP 380: Syntax for Delegating to a Subgenerator
- PEP 409: Suppressing exception context
- PEP 414: Explicit Unicode literals
- PEP 3155: Qualified name for classes and functions
- PEP 412: Key-Sharing Dictionary
- PEP 362: Function Signature Object
- PEP 421: Adding sys.implementation
- Using importlib as the Implementation of Import
- 其他語言特性修改
- A Finer-Grained Import Lock
- Builtin functions and types
- 新增模塊
- 改進的模塊
- 性能優化
- Build and C API Changes
- 棄用
- Porting to Python 3.3
- What's New In Python 3.2
- PEP 384: Defining a Stable ABI
- PEP 389: Argparse Command Line Parsing Module
- PEP 391: Dictionary Based Configuration for Logging
- PEP 3148: The concurrent.futures module
- PEP 3147: PYC Repository Directories
- PEP 3149: ABI Version Tagged .so Files
- PEP 3333: Python Web Server Gateway Interface v1.0.1
- 其他語言特性修改
- New, Improved, and Deprecated Modules
- 多線程
- 性能優化
- Unicode
- Codecs
- 文檔
- IDLE
- Code Repository
- Build and C API Changes
- Porting to Python 3.2
- What's New In Python 3.1
- PEP 372: Ordered Dictionaries
- PEP 378: Format Specifier for Thousands Separator
- 其他語言特性修改
- New, Improved, and Deprecated Modules
- 性能優化
- IDLE
- Build and C API Changes
- Porting to Python 3.1
- What's New In Python 3.0
- Common Stumbling Blocks
- Overview Of Syntax Changes
- Changes Already Present In Python 2.6
- Library Changes
- PEP 3101: A New Approach To String Formatting
- Changes To Exceptions
- Miscellaneous Other Changes
- Build and C API Changes
- 性能
- Porting To Python 3.0
- What's New in Python 2.7
- The Future for Python 2.x
- Changes to the Handling of Deprecation Warnings
- Python 3.1 Features
- PEP 372: Adding an Ordered Dictionary to collections
- PEP 378: Format Specifier for Thousands Separator
- PEP 389: The argparse Module for Parsing Command Lines
- PEP 391: Dictionary-Based Configuration For Logging
- PEP 3106: Dictionary Views
- PEP 3137: The memoryview Object
- 其他語言特性修改
- New and Improved Modules
- Build and C API Changes
- Other Changes and Fixes
- Porting to Python 2.7
- New Features Added to Python 2.7 Maintenance Releases
- Acknowledgements
- Python 2.6 有什么新變化
- Python 3.0
- Changes to the Development Process
- PEP 343: The 'with' statement
- PEP 366: Explicit Relative Imports From a Main Module
- PEP 370: Per-user site-packages Directory
- PEP 371: The multiprocessing Package
- PEP 3101: Advanced String Formatting
- PEP 3105: print As a Function
- PEP 3110: Exception-Handling Changes
- PEP 3112: Byte Literals
- PEP 3116: New I/O Library
- PEP 3118: Revised Buffer Protocol
- PEP 3119: Abstract Base Classes
- PEP 3127: Integer Literal Support and Syntax
- PEP 3129: Class Decorators
- PEP 3141: A Type Hierarchy for Numbers
- 其他語言特性修改
- New and Improved Modules
- Deprecations and Removals
- Build and C API Changes
- Porting to Python 2.6
- Acknowledgements
- What's New in Python 2.5
- PEP 308: Conditional Expressions
- PEP 309: Partial Function Application
- PEP 314: Metadata for Python Software Packages v1.1
- PEP 328: Absolute and Relative Imports
- PEP 338: Executing Modules as Scripts
- PEP 341: Unified try/except/finally
- PEP 342: New Generator Features
- PEP 343: The 'with' statement
- PEP 352: Exceptions as New-Style Classes
- PEP 353: Using ssize_t as the index type
- PEP 357: The 'index' method
- 其他語言特性修改
- New, Improved, and Removed Modules
- Build and C API Changes
- Porting to Python 2.5
- Acknowledgements
- What's New in Python 2.4
- PEP 218: Built-In Set Objects
- PEP 237: Unifying Long Integers and Integers
- PEP 289: Generator Expressions
- PEP 292: Simpler String Substitutions
- PEP 318: Decorators for Functions and Methods
- PEP 322: Reverse Iteration
- PEP 324: New subprocess Module
- PEP 327: Decimal Data Type
- PEP 328: Multi-line Imports
- PEP 331: Locale-Independent Float/String Conversions
- 其他語言特性修改
- New, Improved, and Deprecated Modules
- Build and C API Changes
- Porting to Python 2.4
- Acknowledgements
- What's New in Python 2.3
- PEP 218: A Standard Set Datatype
- PEP 255: Simple Generators
- PEP 263: Source Code Encodings
- PEP 273: Importing Modules from ZIP Archives
- PEP 277: Unicode file name support for Windows NT
- PEP 278: Universal Newline Support
- PEP 279: enumerate()
- PEP 282: The logging Package
- PEP 285: A Boolean Type
- PEP 293: Codec Error Handling Callbacks
- PEP 301: Package Index and Metadata for Distutils
- PEP 302: New Import Hooks
- PEP 305: Comma-separated Files
- PEP 307: Pickle Enhancements
- Extended Slices
- 其他語言特性修改
- New, Improved, and Deprecated Modules
- Pymalloc: A Specialized Object Allocator
- Build and C API Changes
- Other Changes and Fixes
- Porting to Python 2.3
- Acknowledgements
- What's New in Python 2.2
- 概述
- PEPs 252 and 253: Type and Class Changes
- PEP 234: Iterators
- PEP 255: Simple Generators
- PEP 237: Unifying Long Integers and Integers
- PEP 238: Changing the Division Operator
- Unicode Changes
- PEP 227: Nested Scopes
- New and Improved Modules
- Interpreter Changes and Fixes
- Other Changes and Fixes
- Acknowledgements
- What's New in Python 2.1
- 概述
- PEP 227: Nested Scopes
- PEP 236: future Directives
- PEP 207: Rich Comparisons
- PEP 230: Warning Framework
- PEP 229: New Build System
- PEP 205: Weak References
- PEP 232: Function Attributes
- PEP 235: Importing Modules on Case-Insensitive Platforms
- PEP 217: Interactive Display Hook
- PEP 208: New Coercion Model
- PEP 241: Metadata in Python Packages
- New and Improved Modules
- Other Changes and Fixes
- Acknowledgements
- What's New in Python 2.0
- 概述
- What About Python 1.6?
- New Development Process
- Unicode
- 列表推導式
- Augmented Assignment
- 字符串的方法
- Garbage Collection of Cycles
- Other Core Changes
- Porting to 2.0
- Extending/Embedding Changes
- Distutils: Making Modules Easy to Install
- XML Modules
- Module changes
- New modules
- IDLE Improvements
- Deleted and Deprecated Modules
- Acknowledgements
- 更新日志
- Python 下一版
- Python 3.7.3 最終版
- Python 3.7.3 發布候選版 1
- Python 3.7.2 最終版
- Python 3.7.2 發布候選版 1
- Python 3.7.1 最終版
- Python 3.7.1 RC 2版本
- Python 3.7.1 發布候選版 1
- Python 3.7.0 正式版
- Python 3.7.0 release candidate 1
- Python 3.7.0 beta 5
- Python 3.7.0 beta 4
- Python 3.7.0 beta 3
- Python 3.7.0 beta 2
- Python 3.7.0 beta 1
- Python 3.7.0 alpha 4
- Python 3.7.0 alpha 3
- Python 3.7.0 alpha 2
- Python 3.7.0 alpha 1
- Python 3.6.6 final
- Python 3.6.6 RC 1
- Python 3.6.5 final
- Python 3.6.5 release candidate 1
- Python 3.6.4 final
- Python 3.6.4 release candidate 1
- Python 3.6.3 final
- Python 3.6.3 release candidate 1
- Python 3.6.2 final
- Python 3.6.2 release candidate 2
- Python 3.6.2 release candidate 1
- Python 3.6.1 final
- Python 3.6.1 release candidate 1
- Python 3.6.0 final
- Python 3.6.0 release candidate 2
- Python 3.6.0 release candidate 1
- Python 3.6.0 beta 4
- Python 3.6.0 beta 3
- Python 3.6.0 beta 2
- Python 3.6.0 beta 1
- Python 3.6.0 alpha 4
- Python 3.6.0 alpha 3
- Python 3.6.0 alpha 2
- Python 3.6.0 alpha 1
- Python 3.5.5 final
- Python 3.5.5 release candidate 1
- Python 3.5.4 final
- Python 3.5.4 release candidate 1
- Python 3.5.3 final
- Python 3.5.3 release candidate 1
- Python 3.5.2 final
- Python 3.5.2 release candidate 1
- Python 3.5.1 final
- Python 3.5.1 release candidate 1
- Python 3.5.0 final
- Python 3.5.0 release candidate 4
- Python 3.5.0 release candidate 3
- Python 3.5.0 release candidate 2
- Python 3.5.0 release candidate 1
- Python 3.5.0 beta 4
- Python 3.5.0 beta 3
- Python 3.5.0 beta 2
- Python 3.5.0 beta 1
- Python 3.5.0 alpha 4
- Python 3.5.0 alpha 3
- Python 3.5.0 alpha 2
- Python 3.5.0 alpha 1
- Python 教程
- 課前甜點
- 使用 Python 解釋器
- 調用解釋器
- 解釋器的運行環境
- Python 的非正式介紹
- Python 作為計算器使用
- 走向編程的第一步
- 其他流程控制工具
- if 語句
- for 語句
- range() 函數
- break 和 continue 語句,以及循環中的 else 子句
- pass 語句
- 定義函數
- 函數定義的更多形式
- 小插曲:編碼風格
- 數據結構
- 列表的更多特性
- del 語句
- 元組和序列
- 集合
- 字典
- 循環的技巧
- 深入條件控制
- 序列和其它類型的比較
- 模塊
- 有關模塊的更多信息
- 標準模塊
- dir() 函數
- 包
- 輸入輸出
- 更漂亮的輸出格式
- 讀寫文件
- 錯誤和異常
- 語法錯誤
- 異常
- 處理異常
- 拋出異常
- 用戶自定義異常
- 定義清理操作
- 預定義的清理操作
- 類
- 名稱和對象
- Python 作用域和命名空間
- 初探類
- 補充說明
- 繼承
- 私有變量
- 雜項說明
- 迭代器
- 生成器
- 生成器表達式
- 標準庫簡介
- 操作系統接口
- 文件通配符
- 命令行參數
- 錯誤輸出重定向和程序終止
- 字符串模式匹配
- 數學
- 互聯網訪問
- 日期和時間
- 數據壓縮
- 性能測量
- 質量控制
- 自帶電池
- 標準庫簡介 —— 第二部分
- 格式化輸出
- 模板
- 使用二進制數據記錄格式
- 多線程
- 日志
- 弱引用
- 用于操作列表的工具
- 十進制浮點運算
- 虛擬環境和包
- 概述
- 創建虛擬環境
- 使用pip管理包
- 接下來?
- 交互式編輯和編輯歷史
- Tab 補全和編輯歷史
- 默認交互式解釋器的替代品
- 浮點算術:爭議和限制
- 表示性錯誤
- 附錄
- 交互模式
- 安裝和使用 Python
- 命令行與環境
- 命令行
- 環境變量
- 在Unix平臺中使用Python
- 獲取最新版本的Python
- 構建Python
- 與Python相關的路徑和文件
- 雜項
- 編輯器和集成開發環境
- 在Windows上使用 Python
- 完整安裝程序
- Microsoft Store包
- nuget.org 安裝包
- 可嵌入的包
- 替代捆綁包
- 配置Python
- 適用于Windows的Python啟動器
- 查找模塊
- 附加模塊
- 在Windows上編譯Python
- 其他平臺
- 在蘋果系統上使用 Python
- 獲取和安裝 MacPython
- IDE
- 安裝額外的 Python 包
- Mac 上的圖形界面編程
- 在 Mac 上分發 Python 應用程序
- 其他資源
- Python 語言參考
- 概述
- 其他實現
- 標注
- 詞法分析
- 行結構
- 其他形符
- 標識符和關鍵字
- 字面值
- 運算符
- 分隔符
- 數據模型
- 對象、值與類型
- 標準類型層級結構
- 特殊方法名稱
- 協程
- 執行模型
- 程序的結構
- 命名與綁定
- 異常
- 導入系統
- importlib
- 包
- 搜索
- 加載
- 基于路徑的查找器
- 替換標準導入系統
- Package Relative Imports
- 有關 main 的特殊事項
- 開放問題項
- 參考文獻
- 表達式
- 算術轉換
- 原子
- 原型
- await 表達式
- 冪運算符
- 一元算術和位運算
- 二元算術運算符
- 移位運算
- 二元位運算
- 比較運算
- 布爾運算
- 條件表達式
- lambda 表達式
- 表達式列表
- 求值順序
- 運算符優先級
- 簡單語句
- 表達式語句
- 賦值語句
- assert 語句
- pass 語句
- del 語句
- return 語句
- yield 語句
- raise 語句
- break 語句
- continue 語句
- import 語句
- global 語句
- nonlocal 語句
- 復合語句
- if 語句
- while 語句
- for 語句
- try 語句
- with 語句
- 函數定義
- 類定義
- 協程
- 最高層級組件
- 完整的 Python 程序
- 文件輸入
- 交互式輸入
- 表達式輸入
- 完整的語法規范
- Python 標準庫
- 概述
- 可用性注釋
- 內置函數
- 內置常量
- 由 site 模塊添加的常量
- 內置類型
- 邏輯值檢測
- 布爾運算 — and, or, not
- 比較
- 數字類型 — int, float, complex
- 迭代器類型
- 序列類型 — list, tuple, range
- 文本序列類型 — str
- 二進制序列類型 — bytes, bytearray, memoryview
- 集合類型 — set, frozenset
- 映射類型 — dict
- 上下文管理器類型
- 其他內置類型
- 特殊屬性
- 內置異常
- 基類
- 具體異常
- 警告
- 異常層次結構
- 文本處理服務
- string — 常見的字符串操作
- re — 正則表達式操作
- 模塊 difflib 是一個計算差異的助手
- textwrap — Text wrapping and filling
- unicodedata — Unicode 數據庫
- stringprep — Internet String Preparation
- readline — GNU readline interface
- rlcompleter — GNU readline的完成函數
- 二進制數據服務
- struct — Interpret bytes as packed binary data
- codecs — Codec registry and base classes
- 數據類型
- datetime — 基礎日期/時間數據類型
- calendar — General calendar-related functions
- collections — 容器數據類型
- collections.abc — 容器的抽象基類
- heapq — 堆隊列算法
- bisect — Array bisection algorithm
- array — Efficient arrays of numeric values
- weakref — 弱引用
- types — Dynamic type creation and names for built-in types
- copy — 淺層 (shallow) 和深層 (deep) 復制操作
- pprint — 數據美化輸出
- reprlib — Alternate repr() implementation
- enum — Support for enumerations
- 數字和數學模塊
- numbers — 數字的抽象基類
- math — 數學函數
- cmath — Mathematical functions for complex numbers
- decimal — 十進制定點和浮點運算
- fractions — 分數
- random — 生成偽隨機數
- statistics — Mathematical statistics functions
- 函數式編程模塊
- itertools — 為高效循環而創建迭代器的函數
- functools — 高階函數和可調用對象上的操作
- operator — 標準運算符替代函數
- 文件和目錄訪問
- pathlib — 面向對象的文件系統路徑
- os.path — 常見路徑操作
- fileinput — Iterate over lines from multiple input streams
- stat — Interpreting stat() results
- filecmp — File and Directory Comparisons
- tempfile — Generate temporary files and directories
- glob — Unix style pathname pattern expansion
- fnmatch — Unix filename pattern matching
- linecache — Random access to text lines
- shutil — High-level file operations
- macpath — Mac OS 9 路徑操作函數
- 數據持久化
- pickle —— Python 對象序列化
- copyreg — Register pickle support functions
- shelve — Python object persistence
- marshal — Internal Python object serialization
- dbm — Interfaces to Unix “databases”
- sqlite3 — SQLite 數據庫 DB-API 2.0 接口模塊
- 數據壓縮和存檔
- zlib — 與 gzip 兼容的壓縮
- gzip — 對 gzip 格式的支持
- bz2 — 對 bzip2 壓縮算法的支持
- lzma — 用 LZMA 算法壓縮
- zipfile — 在 ZIP 歸檔中工作
- tarfile — Read and write tar archive files
- 文件格式
- csv — CSV 文件讀寫
- configparser — Configuration file parser
- netrc — netrc file processing
- xdrlib — Encode and decode XDR data
- plistlib — Generate and parse Mac OS X .plist files
- 加密服務
- hashlib — 安全哈希與消息摘要
- hmac — 基于密鑰的消息驗證
- secrets — Generate secure random numbers for managing secrets
- 通用操作系統服務
- os — 操作系統接口模塊
- io — 處理流的核心工具
- time — 時間的訪問和轉換
- argparse — 命令行選項、參數和子命令解析器
- getopt — C-style parser for command line options
- 模塊 logging — Python 的日志記錄工具
- logging.config — 日志記錄配置
- logging.handlers — Logging handlers
- getpass — 便攜式密碼輸入工具
- curses — 終端字符單元顯示的處理
- curses.textpad — Text input widget for curses programs
- curses.ascii — Utilities for ASCII characters
- curses.panel — A panel stack extension for curses
- platform — Access to underlying platform's identifying data
- errno — Standard errno system symbols
- ctypes — Python 的外部函數庫
- 并發執行
- threading — 基于線程的并行
- multiprocessing — 基于進程的并行
- concurrent 包
- concurrent.futures — 啟動并行任務
- subprocess — 子進程管理
- sched — 事件調度器
- queue — 一個同步的隊列類
- _thread — 底層多線程 API
- _dummy_thread — _thread 的替代模塊
- dummy_threading — 可直接替代 threading 模塊。
- contextvars — Context Variables
- Context Variables
- Manual Context Management
- asyncio support
- 網絡和進程間通信
- asyncio — 異步 I/O
- socket — 底層網絡接口
- ssl — TLS/SSL wrapper for socket objects
- select — Waiting for I/O completion
- selectors — 高級 I/O 復用庫
- asyncore — 異步socket處理器
- asynchat — 異步 socket 指令/響應 處理器
- signal — Set handlers for asynchronous events
- mmap — Memory-mapped file support
- 互聯網數據處理
- email — 電子郵件與 MIME 處理包
- json — JSON 編碼和解碼器
- mailcap — Mailcap file handling
- mailbox — Manipulate mailboxes in various formats
- mimetypes — Map filenames to MIME types
- base64 — Base16, Base32, Base64, Base85 數據編碼
- binhex — 對binhex4文件進行編碼和解碼
- binascii — 二進制和 ASCII 碼互轉
- quopri — Encode and decode MIME quoted-printable data
- uu — Encode and decode uuencode files
- 結構化標記處理工具
- html — 超文本標記語言支持
- html.parser — 簡單的 HTML 和 XHTML 解析器
- html.entities — HTML 一般實體的定義
- XML處理模塊
- xml.etree.ElementTree — The ElementTree XML API
- xml.dom — The Document Object Model API
- xml.dom.minidom — Minimal DOM implementation
- xml.dom.pulldom — Support for building partial DOM trees
- xml.sax — Support for SAX2 parsers
- xml.sax.handler — Base classes for SAX handlers
- xml.sax.saxutils — SAX Utilities
- xml.sax.xmlreader — Interface for XML parsers
- xml.parsers.expat — Fast XML parsing using Expat
- 互聯網協議和支持
- webbrowser — 方便的Web瀏覽器控制器
- cgi — Common Gateway Interface support
- cgitb — Traceback manager for CGI scripts
- wsgiref — WSGI Utilities and Reference Implementation
- urllib — URL 處理模塊
- urllib.request — 用于打開 URL 的可擴展庫
- urllib.response — Response classes used by urllib
- urllib.parse — Parse URLs into components
- urllib.error — Exception classes raised by urllib.request
- urllib.robotparser — Parser for robots.txt
- http — HTTP 模塊
- http.client — HTTP協議客戶端
- ftplib — FTP protocol client
- poplib — POP3 protocol client
- imaplib — IMAP4 protocol client
- nntplib — NNTP protocol client
- smtplib —SMTP協議客戶端
- smtpd — SMTP Server
- telnetlib — Telnet client
- uuid — UUID objects according to RFC 4122
- socketserver — A framework for network servers
- http.server — HTTP 服務器
- http.cookies — HTTP state management
- http.cookiejar — Cookie handling for HTTP clients
- xmlrpc — XMLRPC 服務端與客戶端模塊
- xmlrpc.client — XML-RPC client access
- xmlrpc.server — Basic XML-RPC servers
- ipaddress — IPv4/IPv6 manipulation library
- 多媒體服務
- audioop — Manipulate raw audio data
- aifc — Read and write AIFF and AIFC files
- sunau — 讀寫 Sun AU 文件
- wave — 讀寫WAV格式文件
- chunk — Read IFF chunked data
- colorsys — Conversions between color systems
- imghdr — 推測圖像類型
- sndhdr — 推測聲音文件的類型
- ossaudiodev — Access to OSS-compatible audio devices
- 國際化
- gettext — 多語種國際化服務
- locale — 國際化服務
- 程序框架
- turtle — 海龜繪圖
- cmd — 支持面向行的命令解釋器
- shlex — Simple lexical analysis
- Tk圖形用戶界面(GUI)
- tkinter — Tcl/Tk的Python接口
- tkinter.ttk — Tk themed widgets
- tkinter.tix — Extension widgets for Tk
- tkinter.scrolledtext — 滾動文字控件
- IDLE
- 其他圖形用戶界面(GUI)包
- 開發工具
- typing — 類型標注支持
- pydoc — Documentation generator and online help system
- doctest — Test interactive Python examples
- unittest — 單元測試框架
- unittest.mock — mock object library
- unittest.mock 上手指南
- 2to3 - 自動將 Python 2 代碼轉為 Python 3 代碼
- test — Regression tests package for Python
- test.support — Utilities for the Python test suite
- test.support.script_helper — Utilities for the Python execution tests
- 調試和分析
- bdb — Debugger framework
- faulthandler — Dump the Python traceback
- pdb — The Python Debugger
- The Python Profilers
- timeit — 測量小代碼片段的執行時間
- trace — Trace or track Python statement execution
- tracemalloc — Trace memory allocations
- 軟件打包和分發
- distutils — 構建和安裝 Python 模塊
- ensurepip — Bootstrapping the pip installer
- venv — 創建虛擬環境
- zipapp — Manage executable Python zip archives
- Python運行時服務
- sys — 系統相關的參數和函數
- sysconfig — Provide access to Python's configuration information
- builtins — 內建對象
- main — 頂層腳本環境
- warnings — Warning control
- dataclasses — 數據類
- contextlib — Utilities for with-statement contexts
- abc — 抽象基類
- atexit — 退出處理器
- traceback — Print or retrieve a stack traceback
- future — Future 語句定義
- gc — 垃圾回收器接口
- inspect — 檢查對象
- site — Site-specific configuration hook
- 自定義 Python 解釋器
- code — Interpreter base classes
- codeop — Compile Python code
- 導入模塊
- zipimport — Import modules from Zip archives
- pkgutil — Package extension utility
- modulefinder — 查找腳本使用的模塊
- runpy — Locating and executing Python modules
- importlib — The implementation of import
- Python 語言服務
- parser — Access Python parse trees
- ast — 抽象語法樹
- symtable — Access to the compiler's symbol tables
- symbol — 與 Python 解析樹一起使用的常量
- token — 與Python解析樹一起使用的常量
- keyword — 檢驗Python關鍵字
- tokenize — Tokenizer for Python source
- tabnanny — 模糊縮進檢測
- pyclbr — Python class browser support
- py_compile — Compile Python source files
- compileall — Byte-compile Python libraries
- dis — Python 字節碼反匯編器
- pickletools — Tools for pickle developers
- 雜項服務
- formatter — Generic output formatting
- Windows系統相關模塊
- msilib — Read and write Microsoft Installer files
- msvcrt — Useful routines from the MS VC++ runtime
- winreg — Windows 注冊表訪問
- winsound — Sound-playing interface for Windows
- Unix 專有服務
- posix — The most common POSIX system calls
- pwd — 用戶密碼數據庫
- spwd — The shadow password database
- grp — The group database
- crypt — Function to check Unix passwords
- termios — POSIX style tty control
- tty — 終端控制功能
- pty — Pseudo-terminal utilities
- fcntl — The fcntl and ioctl system calls
- pipes — Interface to shell pipelines
- resource — Resource usage information
- nis — Interface to Sun's NIS (Yellow Pages)
- Unix syslog 庫例程
- 被取代的模塊
- optparse — Parser for command line options
- imp — Access the import internals
- 未創建文檔的模塊
- 平臺特定模塊
- 擴展和嵌入 Python 解釋器
- 推薦的第三方工具
- 不使用第三方工具創建擴展
- 使用 C 或 C++ 擴展 Python
- 自定義擴展類型:教程
- 定義擴展類型:已分類主題
- 構建C/C++擴展
- 在Windows平臺編譯C和C++擴展
- 在更大的應用程序中嵌入 CPython 運行時
- Embedding Python in Another Application
- Python/C API 參考手冊
- 概述
- 代碼標準
- 包含文件
- 有用的宏
- 對象、類型和引用計數
- 異常
- 嵌入Python
- 調試構建
- 穩定的應用程序二進制接口
- The Very High Level Layer
- Reference Counting
- 異常處理
- Printing and clearing
- 拋出異常
- Issuing warnings
- Querying the error indicator
- Signal Handling
- Exception Classes
- Exception Objects
- Unicode Exception Objects
- Recursion Control
- 標準異常
- 標準警告類別
- 工具
- 操作系統實用程序
- 系統功能
- 過程控制
- 導入模塊
- Data marshalling support
- 語句解釋及變量編譯
- 字符串轉換與格式化
- 反射
- 編解碼器注冊與支持功能
- 抽象對象層
- Object Protocol
- 數字協議
- Sequence Protocol
- Mapping Protocol
- 迭代器協議
- 緩沖協議
- Old Buffer Protocol
- 具體的對象層
- 基本對象
- 數值對象
- 序列對象
- 容器對象
- 函數對象
- 其他對象
- Initialization, Finalization, and Threads
- 在Python初始化之前
- 全局配置變量
- Initializing and finalizing the interpreter
- Process-wide parameters
- Thread State and the Global Interpreter Lock
- Sub-interpreter support
- Asynchronous Notifications
- Profiling and Tracing
- Advanced Debugger Support
- Thread Local Storage Support
- 內存管理
- 概述
- 原始內存接口
- Memory Interface
- 對象分配器
- 默認內存分配器
- Customize Memory Allocators
- The pymalloc allocator
- tracemalloc C API
- 示例
- 對象實現支持
- 在堆中分配對象
- Common Object Structures
- Type 對象
- Number Object Structures
- Mapping Object Structures
- Sequence Object Structures
- Buffer Object Structures
- Async Object Structures
- 使對象類型支持循環垃圾回收
- API 和 ABI 版本管理
- 分發 Python 模塊
- 關鍵術語
- 開源許可與協作
- 安裝工具
- 閱讀指南
- 我該如何...?
- ...為我的項目選擇一個名字?
- ...創建和分發二進制擴展?
- 安裝 Python 模塊
- 關鍵術語
- 基本使用
- 我應如何 ...?
- ... 在 Python 3.4 之前的 Python 版本中安裝 pip ?
- ... 只為當前用戶安裝軟件包?
- ... 安裝科學計算類 Python 軟件包?
- ... 使用并行安裝的多個 Python 版本?
- 常見的安裝問題
- 在 Linux 的系統 Python 版本上安裝
- 未安裝 pip
- 安裝二進制編譯擴展
- Python 常用指引
- 將 Python 2 代碼遷移到 Python 3
- 簡要說明
- 詳情
- 將擴展模塊移植到 Python 3
- 條件編譯
- 對象API的更改
- 模塊初始化和狀態
- CObject 替換為 Capsule
- 其他選項
- Curses Programming with Python
- What is curses?
- Starting and ending a curses application
- Windows and Pads
- Displaying Text
- User Input
- For More Information
- 實現描述器
- 摘要
- 定義和簡介
- 描述器協議
- 發起調用描述符
- 描述符示例
- Properties
- 函數和方法
- Static Methods and Class Methods
- 函數式編程指引
- 概述
- 迭代器
- 生成器表達式和列表推導式
- 生成器
- 內置函數
- itertools 模塊
- The functools module
- Small functions and the lambda expression
- Revision History and Acknowledgements
- 引用文獻
- 日志 HOWTO
- 日志基礎教程
- 進階日志教程
- 日志級別
- 有用的處理程序
- 記錄日志中引發的異常
- 使用任意對象作為消息
- 優化
- 日志操作手冊
- 在多個模塊中使用日志
- 在多線程中使用日志
- 使用多個日志處理器和多種格式化
- 在多個地方記錄日志
- 日志服務器配置示例
- 處理日志處理器的阻塞
- Sending and receiving logging events across a network
- Adding contextual information to your logging output
- Logging to a single file from multiple processes
- Using file rotation
- Use of alternative formatting styles
- Customizing LogRecord
- Subclassing QueueHandler - a ZeroMQ example
- Subclassing QueueListener - a ZeroMQ example
- An example dictionary-based configuration
- Using a rotator and namer to customize log rotation processing
- A more elaborate multiprocessing example
- Inserting a BOM into messages sent to a SysLogHandler
- Implementing structured logging
- Customizing handlers with dictConfig()
- Using particular formatting styles throughout your application
- Configuring filters with dictConfig()
- Customized exception formatting
- Speaking logging messages
- Buffering logging messages and outputting them conditionally
- Formatting times using UTC (GMT) via configuration
- Using a context manager for selective logging
- 正則表達式HOWTO
- 概述
- 簡單模式
- 使用正則表達式
- 更多模式能力
- 修改字符串
- 常見問題
- 反饋
- 套接字編程指南
- 套接字
- 創建套接字
- 使用一個套接字
- 斷開連接
- 非阻塞的套接字
- 排序指南
- 基本排序
- 關鍵函數
- Operator 模塊函數
- 升序和降序
- 排序穩定性和排序復雜度
- 使用裝飾-排序-去裝飾的舊方法
- 使用 cmp 參數的舊方法
- 其它
- Unicode 指南
- Unicode 概述
- Python's Unicode Support
- Reading and Writing Unicode Data
- Acknowledgements
- 如何使用urllib包獲取網絡資源
- 概述
- Fetching URLs
- 處理異常
- info and geturl
- Openers and Handlers
- Basic Authentication
- Proxies
- Sockets and Layers
- 腳注
- Argparse 教程
- 概念
- 基礎
- 位置參數介紹
- Introducing Optional arguments
- Combining Positional and Optional arguments
- Getting a little more advanced
- Conclusion
- ipaddress模塊介紹
- 創建 Address/Network/Interface 對象
- 審查 Address/Network/Interface 對象
- Network 作為 Address 列表
- 比較
- 將IP地址與其他模塊一起使用
- 實例創建失敗時獲取更多詳細信息
- Argument Clinic How-To
- The Goals Of Argument Clinic
- Basic Concepts And Usage
- Converting Your First Function
- Advanced Topics
- 使用 DTrace 和 SystemTap 檢測CPython
- Enabling the static markers
- Static DTrace probes
- Static SystemTap markers
- Available static markers
- SystemTap Tapsets
- 示例
- Python 常見問題
- Python常見問題
- 一般信息
- 現實世界中的 Python
- 編程常見問題
- 一般問題
- 核心語言
- 數字和字符串
- 性能
- 序列(元組/列表)
- 對象
- 模塊
- 設計和歷史常見問題
- 為什么Python使用縮進來分組語句?
- 為什么簡單的算術運算得到奇怪的結果?
- 為什么浮點計算不準確?
- 為什么Python字符串是不可變的?
- 為什么必須在方法定義和調用中顯式使用“self”?
- 為什么不能在表達式中賦值?
- 為什么Python對某些功能(例如list.index())使用方法來實現,而其他功能(例如len(List))使用函數實現?
- 為什么 join()是一個字符串方法而不是列表或元組方法?
- 異常有多快?
- 為什么Python中沒有switch或case語句?
- 難道不能在解釋器中模擬線程,而非得依賴特定于操作系統的線程實現嗎?
- 為什么lambda表達式不能包含語句?
- 可以將Python編譯為機器代碼,C或其他語言嗎?
- Python如何管理內存?
- 為什么CPython不使用更傳統的垃圾回收方案?
- CPython退出時為什么不釋放所有內存?
- 為什么有單獨的元組和列表數據類型?
- 列表是如何在CPython中實現的?
- 字典是如何在CPython中實現的?
- 為什么字典key必須是不可變的?
- 為什么 list.sort() 沒有返回排序列表?
- 如何在Python中指定和實施接口規范?
- 為什么沒有goto?
- 為什么原始字符串(r-strings)不能以反斜杠結尾?
- 為什么Python沒有屬性賦值的“with”語句?
- 為什么 if/while/def/class語句需要冒號?
- 為什么Python在列表和元組的末尾允許使用逗號?
- 代碼庫和插件 FAQ
- 通用的代碼庫問題
- 通用任務
- 線程相關
- 輸入輸出
- 網絡 / Internet 編程
- 數據庫
- 數學和數字
- 擴展/嵌入常見問題
- 可以使用C語言中創建自己的函數嗎?
- 可以使用C++語言中創建自己的函數嗎?
- C很難寫,有沒有其他選擇?
- 如何從C執行任意Python語句?
- 如何從C中評估任意Python表達式?
- 如何從Python對象中提取C的值?
- 如何使用Py_BuildValue()創建任意長度的元組?
- 如何從C調用對象的方法?
- 如何捕獲PyErr_Print()(或打印到stdout / stderr的任何內容)的輸出?
- 如何從C訪問用Python編寫的模塊?
- 如何從Python接口到C ++對象?
- 我使用Setup文件添加了一個模塊,為什么make失敗了?
- 如何調試擴展?
- 我想在Linux系統上編譯一個Python模塊,但是缺少一些文件。為什么?
- 如何區分“輸入不完整”和“輸入無效”?
- 如何找到未定義的g++符號__builtin_new或__pure_virtual?
- 能否創建一個對象類,其中部分方法在C中實現,而其他方法在Python中實現(例如通過繼承)?
- Python在Windows上的常見問題
- 我怎樣在Windows下運行一個Python程序?
- 我怎么讓 Python 腳本可執行?
- 為什么有時候 Python 程序會啟動緩慢?
- 我怎樣使用Python腳本制作可執行文件?
- *.pyd 文件和DLL文件相同嗎?
- 我怎樣將Python嵌入一個Windows程序?
- 如何讓編輯器不要在我的 Python 源代碼中插入 tab ?
- 如何在不阻塞的情況下檢查按鍵?
- 圖形用戶界面(GUI)常見問題
- 圖形界面常見問題
- Python 是否有平臺無關的圖形界面工具包?
- 有哪些Python的GUI工具是某個平臺專用的?
- 有關Tkinter的問題
- “為什么我的電腦上安裝了 Python ?”
- 什么是Python?
- 為什么我的電腦上安裝了 Python ?
- 我能刪除 Python 嗎?
- 術語對照表
- 文檔說明
- Python 文檔貢獻者
- 解決 Bug
- 文檔錯誤
- 使用 Python 的錯誤追蹤系統
- 開始為 Python 貢獻您的知識
- 版權
- 歷史和許可證
- 軟件歷史
- 訪問Python或以其他方式使用Python的條款和條件
- Python 3.7.3 的 PSF 許可協議
- Python 2.0 的 BeOpen.com 許可協議
- Python 1.6.1 的 CNRI 許可協議
- Python 0.9.0 至 1.2 的 CWI 許可協議
- 集成軟件的許可和認可
- Mersenne Twister
- 套接字
- Asynchronous socket services
- Cookie management
- Execution tracing
- UUencode and UUdecode functions
- XML Remote Procedure Calls
- test_epoll
- Select kqueue
- SipHash24
- strtod and dtoa
- OpenSSL
- expat
- libffi
- zlib
- cfuhash
- libmpdec