“Python/docs/3.9/library/argparse”的版本间差异

来自菜鸟教程
Python/docs/3.9/library/argparse
跳转至:导航、​搜索
(autoload)
 
(Page commit)
 
第1行: 第1行:
 +
{{DISPLAYTITLE:argparse — 命令行选项、参数和子命令的解析器 — Python 文档}}
 
<div id="module-argparse" class="section">
 
<div id="module-argparse" class="section">
  
 
<span id="argparse-parser-for-command-line-options-arguments-and-sub-commands"></span>
 
<span id="argparse-parser-for-command-line-options-arguments-and-sub-commands"></span>
= [[#module-argparse|<code>argparse</code>]] --- Parser for command-line options, arguments and sub-commands =
+
= argparse — 命令行选项、参数和子命令的解析器 =
  
 
<div class="versionadded">
 
<div class="versionadded">
  
<span class="versionmodified added">3.2 新版功能.</span>
+
<span class="versionmodified added">3.2 版中的新功能。</span>
  
  
 
</div>
 
</div>
'''Source code:''' [https://github.com/python/cpython/tree/3.9/Lib/argparse.py Lib/argparse.py]
+
'''源代码:''' [[#id1|<span id="id2" class="problematic">:source:`Lib/argparse.py`</span>]]
  
<div class="sidebar">
 
  
Tutorial
+
-----
  
This page contains the API reference information. For a more gentle
+
教程
introduction to Python command-line parsing, have a look at the
 
[[../../howto/argparse#id1|<span class="std std-ref">argparse tutorial</span>]].
 
  
 +
此页面包含 API 参考信息。 有关 Python 命令行解析的更温和的介绍,请查看 [[../../howto/argparse#id1|argparse 教程]] 。
  
</div>
+
[[#module-argparse|argparse]] 模块使编写用户友好的命令行界面变得容易。 该程序定义了它需要哪些参数,[[#module-argparse|argparse]] 将找出如何从 [[../sys#sys|sys.argv]] 中解析出这些参数。 [[#module-argparse|argparse]] 模块还自动生成帮助和使用消息,并在用户给程序提供无效参数时发出错误。
The [[#module-argparse|<code>argparse</code>]] module makes it easy to write user-friendly command-line
 
interfaces. The program defines what arguments it requires, and [[#module-argparse|<code>argparse</code>]]
 
will figure out how to parse those out of [[../sys#sys|<code>sys.argv</code>]]. The [[#module-argparse|<code>argparse</code>]]
 
module also automatically generates help and usage messages and issues errors
 
when users give the program invalid arguments.
 
  
 
<div id="example" class="section">
 
<div id="example" class="section">
  
== Example ==
+
== 例子 ==
  
The following code is a Python program that takes a list of integers and
+
下面的代码是一个 Python 程序,它接受一个整数列表并产生总和或最大值:
produces either the sum or the max:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第39行: 第32行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>import argparse
+
<syntaxhighlight lang="python3">import argparse
  
 
parser = argparse.ArgumentParser(description='Process some integers.')
 
parser = argparse.ArgumentParser(description='Process some integers.')
第49行: 第42行:
  
 
args = parser.parse_args()
 
args = parser.parse_args()
print(args.accumulate(args.integers))</pre>
+
print(args.accumulate(args.integers))</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
Assuming the Python code above is saved into a file called <code>prog.py</code>, it can
+
假设上面的 Python 代码保存在一个名为 <code>prog.py</code> 的文件中,它可以在命令行运行并提供有用的帮助信息:
be run at the command line and provides useful help messages:
 
  
 
<div class="highlight-shell-session notranslate">
 
<div class="highlight-shell-session notranslate">
第61行: 第53行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>$ python prog.py -h
+
<pre class="session">$ python prog.py -h
 
usage: prog.py [-h] [--sum] N [N ...]
 
usage: prog.py [-h] [--sum] N [N ...]
  
第76行: 第68行:
  
 
</div>
 
</div>
When run with the appropriate arguments, it prints either the sum or the max of
+
当使用适当的参数运行时,它会打印命令行整数的总和或最大值:
the command-line integers:
 
  
 
<div class="highlight-shell-session notranslate">
 
<div class="highlight-shell-session notranslate">
第83行: 第74行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>$ python prog.py 1 2 3 4
+
<pre class="session">$ python prog.py 1 2 3 4
 
4
 
4
  
第92行: 第83行:
  
 
</div>
 
</div>
If invalid arguments are passed in, it will issue an error:
+
如果传入无效参数,则会报错:
  
 
<div class="highlight-shell-session notranslate">
 
<div class="highlight-shell-session notranslate">
第98行: 第89行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>$ python prog.py a b c
+
<pre class="session">$ python prog.py a b c
 
usage: prog.py [-h] [--sum] N [N ...]
 
usage: prog.py [-h] [--sum] N [N ...]
 
prog.py: error: argument N: invalid int value: 'a'</pre>
 
prog.py: error: argument N: invalid int value: 'a'</pre>
第105行: 第96行:
  
 
</div>
 
</div>
The following sections walk you through this example.
+
以下部分将引导您完成此示例。
  
 
<div id="creating-a-parser" class="section">
 
<div id="creating-a-parser" class="section">
  
=== Creating a parser ===
+
=== 创建解析器 ===
  
The first step in using the [[#module-argparse|<code>argparse</code>]] is creating an
+
使用 [[#module-argparse|argparse]] 的第一步是创建一个 [[#argparse.ArgumentParser|ArgumentParser]] 对象:
[[#argparse.ArgumentParser|<code>ArgumentParser</code>]] object:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第118行: 第108行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; parser = argparse.ArgumentParser(description='Process some integers.')</pre>
+
<syntaxhighlight lang="python3">>>> parser = argparse.ArgumentParser(description='Process some integers.')</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
The [[#argparse.ArgumentParser|<code>ArgumentParser</code>]] object will hold all the information necessary to
+
[[#argparse.ArgumentParser|ArgumentParser]] 对象将保存将命令行解析为 Python 数据类型所需的所有信息。
parse the command line into Python data types.
 
  
  
第130行: 第119行:
 
<div id="adding-arguments" class="section">
 
<div id="adding-arguments" class="section">
  
=== Adding arguments ===
+
=== 添加参数 ===
  
Filling an [[#argparse.ArgumentParser|<code>ArgumentParser</code>]] with information about program arguments is
+
用有关程序参数的信息填充 [[#argparse.ArgumentParser|ArgumentParser]] 是通过调用 [[#argparse.ArgumentParser.add_argument|add_argument()]] 方法来完成的。 通常,这些调用会告诉 [[#argparse.ArgumentParser|ArgumentParser]] 如何获取命令行上的字符串并将它们转换为对象。 当调用 [[#argparse.ArgumentParser.parse_args|parse_args()]] 时,会存储和使用此信息。 例如:
done by making calls to the [[#argparse.ArgumentParser.add_argument|<code>add_argument()</code>]] method.
 
Generally, these calls tell the [[#argparse.ArgumentParser|<code>ArgumentParser</code>]] how to take the strings
 
on the command line and turn them into objects. This information is stored and
 
used when [[#argparse.ArgumentParser.parse_args|<code>parse_args()</code>]] is called. For example:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第142行: 第127行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; parser.add_argument('integers', metavar='N', type=int, nargs='+',
+
<syntaxhighlight lang="python3">>>> parser.add_argument('integers', metavar='N', type=int, nargs='+',
 
...                    help='an integer for the accumulator')
 
...                    help='an integer for the accumulator')
&gt;&gt;&gt; parser.add_argument('--sum', dest='accumulate', action='store_const',
+
>>> parser.add_argument('--sum', dest='accumulate', action='store_const',
 
...                    const=sum, default=max,
 
...                    const=sum, default=max,
...                    help='sum the integers (default: find the max)')</pre>
+
...                    help='sum the integers (default: find the max)')</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
Later, calling [[#argparse.ArgumentParser.parse_args|<code>parse_args()</code>]] will return an object with
+
稍后,调用 [[#argparse.ArgumentParser.parse_args|parse_args()]] 将返回一个具有两个属性的对象,<code>integers</code> <code>accumulate</code><code>integers</code> 属性将是一个或多个整数的列表,<code>accumulate</code> 属性将是 [[../functions#sum|sum()]] 函数,如果 <code>--sum</code> 是在命令行中指定,如果不是,则在 [[../functions#max|max()]] 函数中指定。
two attributes, <code>integers</code> and <code>accumulate</code>. The <code>integers</code> attribute
 
will be a list of one or more ints, and the <code>accumulate</code> attribute will be
 
either the [[../functions#sum|<code>sum()</code>]] function, if <code>--sum</code> was specified at the command line,
 
or the [[../functions#max|<code>max()</code>]] function if it was not.
 
  
  
第161行: 第142行:
 
<div id="parsing-arguments" class="section">
 
<div id="parsing-arguments" class="section">
  
=== Parsing arguments ===
+
=== 解析参数 ===
  
[[#argparse.ArgumentParser|<code>ArgumentParser</code>]] parses arguments through the
+
[[#argparse.ArgumentParser|ArgumentParser]] 通过 [[#argparse.ArgumentParser.parse_args|parse_args()]] 方法解析参数。 这将检查命令行,将每个参数转换为适当的类型,然后调用适当的操作。 在大多数情况下,这意味着一个简单的 [[#argparse.Namespace|Namespace]] 对象将从命令行解析出的属性构建:
[[#argparse.ArgumentParser.parse_args|<code>parse_args()</code>]] method. This will inspect the command line,
 
convert each argument to the appropriate type and then invoke the appropriate action.
 
In most cases, this means a simple [[#argparse.Namespace|<code>Namespace</code>]] object will be built up from
 
attributes parsed out of the command line:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第173行: 第150行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; parser.parse_args(['--sum', '7', '-1', '42'])
+
<syntaxhighlight lang="python3">>>> parser.parse_args(['--sum', '7', '-1', '42'])
Namespace(accumulate=&lt;built-in function sum&gt;, integers=[7, -1, 42])</pre>
+
Namespace(accumulate=<built-in function sum>, integers=[7, -1, 42])</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
In a script, [[#argparse.ArgumentParser.parse_args|<code>parse_args()</code>]] will typically be called with no
+
在脚本中,[[#argparse.ArgumentParser.parse_args|parse_args()]] 通常不带参数调用,而 [[#argparse.ArgumentParser|ArgumentParser]] 将自动确定来自 [[../sys#sys|sys.argv]] 的命令行参数。
arguments, and the [[#argparse.ArgumentParser|<code>ArgumentParser</code>]] will automatically determine the
 
command-line arguments from [[../sys#sys|<code>sys.argv</code>]].
 
  
  
第189行: 第164行:
 
<div id="argumentparser-objects" class="section">
 
<div id="argumentparser-objects" class="section">
  
== ArgumentParser objects ==
+
== ArgumentParser 对象 ==
  
 
<dl>
 
<dl>
<dt>''class'' <code>argparse.</code><code>ArgumentParser</code><span class="sig-paren">(</span>''<span class="n">prog</span><span class="o">=</span><span class="default_value">None</span>'', ''<span class="n">usage</span><span class="o">=</span><span class="default_value">None</span>'', ''<span class="n">description</span><span class="o">=</span><span class="default_value">None</span>'', ''<span class="n">epilog</span><span class="o">=</span><span class="default_value">None</span>'', ''<span class="n">parents</span><span class="o">=</span><span class="default_value">[]</span>'', ''<span class="n">formatter_class</span><span class="o">=</span><span class="default_value">argparse.HelpFormatter</span>'', ''<span class="n">prefix_chars</span><span class="o">=</span><span class="default_value">'-'</span>'', ''<span class="n">fromfile_prefix_chars</span><span class="o">=</span><span class="default_value">None</span>'', ''<span class="n">argument_default</span><span class="o">=</span><span class="default_value">None</span>'', ''<span class="n">conflict_handler</span><span class="o">=</span><span class="default_value">'error'</span>'', ''<span class="n">add_help</span><span class="o">=</span><span class="default_value">True</span>'', ''<span class="n">allow_abbrev</span><span class="o">=</span><span class="default_value">True</span>'', ''<span class="n">exit_on_error</span><span class="o">=</span><span class="default_value">True</span>''<span class="sig-paren">)</span></dt>
+
<dt>''<span class="pre">class</span>'' <span class="sig-prename descclassname"><span class="pre">argparse.</span></span><span class="sig-name descname"><span class="pre">ArgumentParser</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">prog</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>'', ''<span class="n"><span class="pre">usage</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>'', ''<span class="n"><span class="pre">description</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>'', ''<span class="n"><span class="pre">epilog</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>'', ''<span class="n"><span class="pre">parents</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">[]</span></span>'', ''<span class="n"><span class="pre">formatter_class</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">argparse.HelpFormatter</span></span>'', ''<span class="n"><span class="pre">prefix_chars</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">'-'</span></span>'', ''<span class="n"><span class="pre">fromfile_prefix_chars</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>'', ''<span class="n"><span class="pre">argument_default</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>'', ''<span class="n"><span class="pre">conflict_handler</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">'error'</span></span>'', ''<span class="n"><span class="pre">add_help</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">True</span></span>'', ''<span class="n"><span class="pre">allow_abbrev</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">True</span></span>'', ''<span class="n"><span class="pre">exit_on_error</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">True</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Create a new [[#argparse.ArgumentParser|<code>ArgumentParser</code>]] object. All parameters should be passed
+
<dd><p>创建一个新的 [[#argparse.ArgumentParser|ArgumentParser]] 对象。 所有参数都应作为关键字参数传递。 每个参数在下面都有更详细的描述,但简而言之,它们是:</p>
as keyword arguments. Each parameter has its own more detailed description
 
below, but in short they are:</p>
 
 
<ul>
 
<ul>
<li><p>[[#prog|prog]] - The name of the program (default: <code>sys.argv[0]</code>)</p></li>
+
<li><p>[[#prog|prog]] - 程序名称(默认:<code>sys.argv[0]</code></p></li>
<li><p>[[#usage|usage]] - The string describing the program usage (default: generated from
+
<li><p>[[#usage|usage]] - 描述程序使用的字符串(默认:从添加到解析器的参数生成)</p></li>
arguments added to parser)</p></li>
+
<li><p>[[#description|description]] - 在参数帮助之前显示的文本(默认值:无)</p></li>
<li><p>[[#description|description]] - Text to display before the argument help (default: none)</p></li>
+
<li><p>[[#epilog|epilog]] - 参数帮助后显示的文本(默认值:无)</p></li>
<li><p>[[#epilog|epilog]] - Text to display after the argument help (default: none)</p></li>
+
<li><p>[[#parents|parents]] - [[#argparse.ArgumentParser|ArgumentParser]] 对象的列表,其参数也应包括在内</p></li>
<li><p>[[#parents|parents]] - A list of [[#argparse.ArgumentParser|<code>ArgumentParser</code>]] objects whose arguments should
+
<li><p>[[#formatter-class|formatter_class]] - 自定义帮助输出的类</p></li>
also be included</p></li>
+
<li><p>[[#prefix-chars|prefix_chars]] - 可选参数的前缀字符集(默认值:'-'</p></li>
<li><p>[[#formatter-class|formatter_class]] - A class for customizing the help output</p></li>
+
<li><p>[[#fromfile-prefix-chars|fromfile_prefix_chars]] - 应该从中读取附加参数的文件前缀字符集(默认值:<code>None</code></p></li>
<li><p>[[#prefix-chars|prefix_chars]] - The set of characters that prefix optional arguments
+
<li><p>[[#argument-default|argument_default]] - 参数的全局默认值(默认值:<code>None</code></p></li>
(default: '-')</p></li>
+
<li><p>[[#conflict-handler|conflict_handler]] - 解决冲突选项的策略(通常是不必要的)</p></li>
<li><p>[[#fromfile-prefix-chars|fromfile_prefix_chars]] - The set of characters that prefix files from
+
<li><p>[[#add-help|add_help]] - 向解析器添加 <code>-h/--help</code> 选项(默认:<code>True</code></p></li>
which additional arguments should be read (default: <code>None</code>)</p></li>
+
<li><p>[[#allow-abbrev|allow_abbrev]] - 如果缩写是明确的,则允许缩写长选项。 (默认:<code>True</code></p></li>
<li><p>[[#argument-default|argument_default]] - The global default value for arguments
+
<li><p>[[#exit-on-error|exit_on_error]] - 确定发生错误时 ArgumentParser 是否退出并显示错误信息。 (默认:<code>True</code></p></li></ul>
(default: <code>None</code>)</p></li>
 
<li><p>[[#conflict-handler|conflict_handler]] - The strategy for resolving conflicting optionals
 
(usually unnecessary)</p></li>
 
<li><p>[[#add-help|add_help]] - Add a <code>-h/--help</code> option to the parser (default: <code>True</code>)</p></li>
 
<li><p>[[#allow-abbrev|allow_abbrev]] - Allows long options to be abbreviated if the
 
abbreviation is unambiguous. (default: <code>True</code>)</p></li>
 
<li><p>[[#exit-on-error|exit_on_error]] - Determines whether or not ArgumentParser exits with
 
error info when an error occurs. (default: <code>True</code>)</p></li></ul>
 
  
 
<div class="versionchanged">
 
<div class="versionchanged">
  
<p><span class="versionmodified changed">3.5 版更改: </span>''allow_abbrev'' parameter was added.</p>
+
<p><span class="versionmodified changed"> 3.5 版更改:添加了 </span>''allow_abbrev'' 参数。</p>
  
 
</div>
 
</div>
 
<div class="versionchanged">
 
<div class="versionchanged">
  
<p><span class="versionmodified changed">3.8 版更改: </span>In previous versions, ''allow_abbrev'' also disabled grouping of short
+
<p><span class="versionmodified changed"> 3.8 版更改: </span> 在之前的版本中,''allow_abbrev'' 还禁用了对诸如 <code>-vv</code> 之类的短标志分组以表示 <code>-v -v</code></p>
flags such as <code>-vv</code> to mean <code>-v -v</code>.</p>
 
  
 
</div>
 
</div>
 
<div class="versionchanged">
 
<div class="versionchanged">
  
<p><span class="versionmodified changed">3.9 版更改: </span>''exit_on_error'' parameter was added.</p>
+
<p><span class="versionmodified changed"> 3.9 版更改:添加了 </span>''exit_on_error'' 参数。</p>
  
 
</div></dd></dl>
 
</div></dd></dl>
  
The following sections describe how each of these are used.
+
以下各节描述了如何使用它们中的每一个。
  
 
<div id="prog" class="section">
 
<div id="prog" class="section">
  
=== prog ===
+
=== ===
  
By default, [[#argparse.ArgumentParser|<code>ArgumentParser</code>]] objects use <code>sys.argv[0]</code> to determine
+
默认情况下,[[#argparse.ArgumentParser|ArgumentParser]] 对象使用 <code>sys.argv[0]</code> 来确定如何在帮助消息中显示程序的名称。 此默认值几乎总是可取的,因为它会使帮助消息与在命令行上调用程序的方式相匹配。 例如,考虑一个名为 <code>myprogram.py</code> 的文件,其代码如下:
how to display the name of the program in help messages. This default is almost
 
always desirable because it will make the help messages match how the program was
 
invoked on the command line. For example, consider a file named
 
<code>myprogram.py</code> with the following code:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第252行: 第212行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>import argparse
+
<syntaxhighlight lang="python3">import argparse
 
parser = argparse.ArgumentParser()
 
parser = argparse.ArgumentParser()
 
parser.add_argument('--foo', help='foo help')
 
parser.add_argument('--foo', help='foo help')
args = parser.parse_args()</pre>
+
args = parser.parse_args()</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
The help for this program will display <code>myprogram.py</code> as the program name
+
该程序的帮助将显示 <code>myprogram.py</code> 作为程序名称(无论从何处调用该程序):
(regardless of where the program was invoked from):
 
  
 
<div class="highlight-shell-session notranslate">
 
<div class="highlight-shell-session notranslate">
第267行: 第226行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>$ python myprogram.py --help
+
<pre class="session">$ python myprogram.py --help
 
usage: myprogram.py [-h] [--foo FOO]
 
usage: myprogram.py [-h] [--foo FOO]
  
第284行: 第243行:
  
 
</div>
 
</div>
To change this default behavior, another value can be supplied using the
+
要更改此默认行为,可以使用 [[#argparse.ArgumentParser|ArgumentParser]] 的 <code>prog=</code> 参数提供另一个值:
<code>prog=</code> argument to [[#argparse.ArgumentParser|<code>ArgumentParser</code>]]:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第291行: 第249行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; parser = argparse.ArgumentParser(prog='myprogram')
+
<syntaxhighlight lang="python3">>>> parser = argparse.ArgumentParser(prog='myprogram')
&gt;&gt;&gt; parser.print_help()
+
>>> parser.print_help()
 
usage: myprogram [-h]
 
usage: myprogram [-h]
  
 
optional arguments:
 
optional arguments:
  -h, --help  show this help message and exit</pre>
+
  -h, --help  show this help message and exit</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
Note that the program name, whether determined from <code>sys.argv[0]</code> or from the
+
请注意,无论是从 <code>sys.argv[0]</code> 还是从 <code>prog=</code> 参数确定的程序名称,都可用于使用 <code>%(prog)s</code> 格式说明符的帮助消息。
<code>prog=</code> argument, is available to help messages using the <code>%(prog)s</code> format
 
specifier.
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第309行: 第265行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; parser = argparse.ArgumentParser(prog='myprogram')
+
<syntaxhighlight lang="python3">>>> parser = argparse.ArgumentParser(prog='myprogram')
&gt;&gt;&gt; parser.add_argument('--foo', help='foo of the %(prog)s program')
+
>>> parser.add_argument('--foo', help='foo of the %(prog)s program')
&gt;&gt;&gt; parser.print_help()
+
>>> parser.print_help()
 
usage: myprogram [-h] [--foo FOO]
 
usage: myprogram [-h] [--foo FOO]
  
 
optional arguments:
 
optional arguments:
 
  -h, --help  show this help message and exit
 
  -h, --help  show this help message and exit
  --foo FOO  foo of the myprogram program</pre>
+
  --foo FOO  foo of the myprogram program</syntaxhighlight>
  
 
</div>
 
</div>
第325行: 第281行:
 
<div id="usage" class="section">
 
<div id="usage" class="section">
  
=== usage ===
+
=== 用法 ===
  
By default, [[#argparse.ArgumentParser|<code>ArgumentParser</code>]] calculates the usage message from the
+
默认情况下,[[#argparse.ArgumentParser|ArgumentParser]] 根据它包含的参数计算用法消息:
arguments it contains:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第334行: 第289行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; parser = argparse.ArgumentParser(prog='PROG')
+
<syntaxhighlight lang="python3">>>> parser = argparse.ArgumentParser(prog='PROG')
&gt;&gt;&gt; parser.add_argument('--foo', nargs='?', help='foo help')
+
>>> parser.add_argument('--foo', nargs='?', help='foo help')
&gt;&gt;&gt; parser.add_argument('bar', nargs='+', help='bar help')
+
>>> parser.add_argument('bar', nargs='+', help='bar help')
&gt;&gt;&gt; parser.print_help()
+
>>> parser.print_help()
 
usage: PROG [-h] [--foo [FOO]] bar [bar ...]
 
usage: PROG [-h] [--foo [FOO]] bar [bar ...]
  
第345行: 第300行:
 
optional arguments:
 
optional arguments:
 
  -h, --help  show this help message and exit
 
  -h, --help  show this help message and exit
  --foo [FOO]  foo help</pre>
+
  --foo [FOO]  foo help</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
The default message can be overridden with the <code>usage=</code> keyword argument:
+
默认消息可以用 <code>usage=</code> 关键字参数覆盖:
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第356行: 第311行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; parser = argparse.ArgumentParser(prog='PROG', usage='%(prog)s [options]')
+
<syntaxhighlight lang="python3">>>> parser = argparse.ArgumentParser(prog='PROG', usage='%(prog)s [options]')
&gt;&gt;&gt; parser.add_argument('--foo', nargs='?', help='foo help')
+
>>> parser.add_argument('--foo', nargs='?', help='foo help')
&gt;&gt;&gt; parser.add_argument('bar', nargs='+', help='bar help')
+
>>> parser.add_argument('bar', nargs='+', help='bar help')
&gt;&gt;&gt; parser.print_help()
+
>>> parser.print_help()
 
usage: PROG [options]
 
usage: PROG [options]
  
第367行: 第322行:
 
optional arguments:
 
optional arguments:
 
  -h, --help  show this help message and exit
 
  -h, --help  show this help message and exit
  --foo [FOO]  foo help</pre>
+
  --foo [FOO]  foo help</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
The <code>%(prog)s</code> format specifier is available to fill in the program name in
+
<code>%(prog)s</code> 格式说明符可用于在您的使用消息中填写程序名称。
your usage messages.
 
  
  
第379行: 第333行:
 
<div id="description" class="section">
 
<div id="description" class="section">
  
=== description ===
+
=== 描述 ===
  
Most calls to the [[#argparse.ArgumentParser|<code>ArgumentParser</code>]] constructor will use the
+
大多数对 [[#argparse.ArgumentParser|ArgumentParser]] 构造函数的调用将使用 <code>description=</code> 关键字参数。 该参数简要描述了程序的作用和工作方式。 在帮助消息中,描述显示在命令行用法字符串和各种参数的帮助消息之间:
<code>description=</code> keyword argument. This argument gives a brief description of
 
what the program does and how it works. In help messages, the description is
 
displayed between the command-line usage string and the help messages for the
 
various arguments:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第391行: 第341行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; parser = argparse.ArgumentParser(description='A foo that bars')
+
<syntaxhighlight lang="python3">>>> parser = argparse.ArgumentParser(description='A foo that bars')
&gt;&gt;&gt; parser.print_help()
+
>>> parser.print_help()
 
usage: argparse.py [-h]
 
usage: argparse.py [-h]
  
第398行: 第348行:
  
 
optional arguments:
 
optional arguments:
  -h, --help  show this help message and exit</pre>
+
  -h, --help  show this help message and exit</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
By default, the description will be line-wrapped so that it fits within the
+
默认情况下,描述将被换行以适应给定的空间。 要更改此行为,请参阅 [[#formatter-class|formatter_class]] 参数。
given space. To change this behavior, see the [[#formatter-class|formatter_class]] argument.
 
  
  
第410行: 第359行:
 
<div id="epilog" class="section">
 
<div id="epilog" class="section">
  
=== epilog ===
+
=== 结语 ===
  
Some programs like to display additional description of the program after the
+
一些程序喜欢在参数描述之后显示程序的附加描述。 可以使用 [[#argparse.ArgumentParser|ArgumentParser]] 的 <code>epilog=</code> 参数指定此类文本:
description of the arguments. Such text can be specified using the <code>epilog=</code>
 
argument to [[#argparse.ArgumentParser|<code>ArgumentParser</code>]]:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第420行: 第367行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; parser = argparse.ArgumentParser(
+
<syntaxhighlight lang="python3">>>> parser = argparse.ArgumentParser(
 
...    description='A foo that bars',
 
...    description='A foo that bars',
...    epilog=&quot;And that's how you'd foo a bar&quot;)
+
...    epilog="And that's how you'd foo a bar")
&gt;&gt;&gt; parser.print_help()
+
>>> parser.print_help()
 
usage: argparse.py [-h]
 
usage: argparse.py [-h]
  
第431行: 第378行:
 
  -h, --help  show this help message and exit
 
  -h, --help  show this help message and exit
  
And that's how you'd foo a bar</pre>
+
And that's how you'd foo a bar</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
As with the [[#description|description]] argument, the <code>epilog=</code> text is by default
+
[[#description|description]] 参数一样,<code>epilog=</code> 文本默认为换行,但可以使用 [[#formatter-class|formatter_class]] 参数调整 [[#argparse.ArgumentParser|ArgumentParser]] ]。
line-wrapped, but this behavior can be adjusted with the [[#formatter-class|formatter_class]]
 
argument to [[#argparse.ArgumentParser|<code>ArgumentParser</code>]].
 
  
  
第444行: 第389行:
 
<div id="parents" class="section">
 
<div id="parents" class="section">
  
=== parents ===
+
=== 父母 ===
  
Sometimes, several parsers share a common set of arguments. Rather than
+
有时,多个解析器共享一组公共参数。 不是重复这些参数的定义,而是可以使用具有所有共享参数并传递给 <code>parents=</code> 参数到 [[#argparse.ArgumentParser|ArgumentParser]] 的单个解析器。 <code>parents=</code> 参数采用 [[#argparse.ArgumentParser|ArgumentParser]] 对象列表,从中收集所有位置和可选操作,并将这些操作添加到正在构造的 [[#argparse.ArgumentParser|ArgumentParser]] 对象中:
repeating the definitions of these arguments, a single parser with all the
 
shared arguments and passed to <code>parents=</code> argument to [[#argparse.ArgumentParser|<code>ArgumentParser</code>]]
 
can be used. The <code>parents=</code> argument takes a list of [[#argparse.ArgumentParser|<code>ArgumentParser</code>]]
 
objects, collects all the positional and optional actions from them, and adds
 
these actions to the [[#argparse.ArgumentParser|<code>ArgumentParser</code>]] object being constructed:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第457行: 第397行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; parent_parser = argparse.ArgumentParser(add_help=False)
+
<syntaxhighlight lang="python3">>>> parent_parser = argparse.ArgumentParser(add_help=False)
&gt;&gt;&gt; parent_parser.add_argument('--parent', type=int)
+
>>> parent_parser.add_argument('--parent', type=int)
  
&gt;&gt;&gt; foo_parser = argparse.ArgumentParser(parents=[parent_parser])
+
>>> foo_parser = argparse.ArgumentParser(parents=[parent_parser])
&gt;&gt;&gt; foo_parser.add_argument('foo')
+
>>> foo_parser.add_argument('foo')
&gt;&gt;&gt; foo_parser.parse_args(['--parent', '2', 'XXX'])
+
>>> foo_parser.parse_args(['--parent', '2', 'XXX'])
 
Namespace(foo='XXX', parent=2)
 
Namespace(foo='XXX', parent=2)
  
&gt;&gt;&gt; bar_parser = argparse.ArgumentParser(parents=[parent_parser])
+
>>> bar_parser = argparse.ArgumentParser(parents=[parent_parser])
&gt;&gt;&gt; bar_parser.add_argument('--bar')
+
>>> bar_parser.add_argument('--bar')
&gt;&gt;&gt; bar_parser.parse_args(['--bar', 'YYY'])
+
>>> bar_parser.parse_args(['--bar', 'YYY'])
Namespace(bar='YYY', parent=None)</pre>
+
Namespace(bar='YYY', parent=None)</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
Note that most parent parsers will specify <code>add_help=False</code>. Otherwise, the
+
请注意,大多数父解析器将指定 <code>add_help=False</code>。 否则, [[#argparse.ArgumentParser|ArgumentParser]] 将看到两个 <code>-h/--help</code> 选项(一个在父级中,一个在子级中)并引发错误。
[[#argparse.ArgumentParser|<code>ArgumentParser</code>]] will see two <code>-h/--help</code> options (one in the parent
 
and one in the child) and raise an error.
 
  
 
<div class="admonition note">
 
<div class="admonition note">
  
注解
+
笔记
  
You must fully initialize the parsers before passing them via <code>parents=</code>.
+
在通过 <code>parents=</code> 传递解析器之前,您必须完全初始化它们。 如果在子解析器之后更改父解析器,这些更改将不会反映在子解析器中。
If you change the parent parsers after the child parser, those changes will
 
not be reflected in the child.
 
  
  
第491行: 第427行:
 
<div id="formatter-class" class="section">
 
<div id="formatter-class" class="section">
  
=== formatter_class ===
+
=== 格式化程序类 ===
  
[[#argparse.ArgumentParser|<code>ArgumentParser</code>]] objects allow the help formatting to be customized by
+
[[#argparse.ArgumentParser|ArgumentParser]] 对象允许通过指定替代格式类来自定义帮助格式。 目前,有四个这样的类:
specifying an alternate formatting class. Currently, there are four such
 
classes:
 
  
; ''class'' <code>argparse.</code><code>RawDescriptionHelpFormatter</code><br />
+
; ''<span class="pre">class</span>'' <span class="sig-prename descclassname"><span class="pre">argparse.</span></span><span class="sig-name descname"><span class="pre">RawDescriptionHelpFormatter</span></span><br />
''class'' <code>argparse.</code><code>RawTextHelpFormatter</code><br />
+
''<span class="pre">class</span>'' <span class="sig-prename descclassname"><span class="pre">argparse.</span></span><span class="sig-name descname"><span class="pre">RawTextHelpFormatter</span></span><br />
''class'' <code>argparse.</code><code>ArgumentDefaultsHelpFormatter</code><br />
+
''<span class="pre">class</span>'' <span class="sig-prename descclassname"><span class="pre">argparse.</span></span><span class="sig-name descname"><span class="pre">ArgumentDefaultsHelpFormatter</span></span><br />
''class'' <code>argparse.</code><code>MetavarTypeHelpFormatter</code>
+
''<span class="pre">class</span>'' <span class="sig-prename descclassname"><span class="pre">argparse.</span></span><span class="sig-name descname"><span class="pre">MetavarTypeHelpFormatter</span></span>
 
:  
 
:  
  
[[#argparse.RawDescriptionHelpFormatter|<code>RawDescriptionHelpFormatter</code>]] and [[#argparse.RawTextHelpFormatter|<code>RawTextHelpFormatter</code>]] give
+
[[#argparse.RawDescriptionHelpFormatter|RawDescriptionHelpFormatter]] [[#argparse.RawTextHelpFormatter|RawTextHelpFormatter]] 可以更好地控制文本描述的显示方式。 默认情况下,[[#argparse.ArgumentParser|ArgumentParser]] 对象对命令行帮助消息中的 [[#description|description]] [[#epilog|epilog]] 文本进行换行:
more control over how textual descriptions are displayed.
 
By default, [[#argparse.ArgumentParser|<code>ArgumentParser</code>]] objects line-wrap the [[#description|description]] and
 
[[#epilog|epilog]] texts in command-line help messages:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第512行: 第443行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; parser = argparse.ArgumentParser(
+
<syntaxhighlight lang="python3">>>> parser = argparse.ArgumentParser(
 
...    prog='PROG',
 
...    prog='PROG',
 
...    description='''this description
 
...    description='''this description
第521行: 第452行:
 
...        be cleaned up and whose words will be wrapped
 
...        be cleaned up and whose words will be wrapped
 
...        across a couple lines''')
 
...        across a couple lines''')
&gt;&gt;&gt; parser.print_help()
+
>>> parser.print_help()
 
usage: PROG [-h]
 
usage: PROG [-h]
  
第530行: 第461行:
  
 
likewise for this epilog whose whitespace will be cleaned up and whose words
 
likewise for this epilog whose whitespace will be cleaned up and whose words
will be wrapped across a couple lines</pre>
+
will be wrapped across a couple lines</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
Passing [[#argparse.RawDescriptionHelpFormatter|<code>RawDescriptionHelpFormatter</code>]] as <code>formatter_class=</code>
+
[[#argparse.RawDescriptionHelpFormatter|RawDescriptionHelpFormatter]] 作为 <code>formatter_class=</code> 传递表示 [[#description|description]] [[#epilog|epilog]] 已正确格式化,不应换行:
indicates that [[#description|description]] and [[#epilog|epilog]] are already correctly formatted and
 
should not be line-wrapped:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第543行: 第472行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; parser = argparse.ArgumentParser(
+
<syntaxhighlight lang="python3">>>> parser = argparse.ArgumentParser(
 
...    prog='PROG',
 
...    prog='PROG',
 
...    formatter_class=argparse.RawDescriptionHelpFormatter,
 
...    formatter_class=argparse.RawDescriptionHelpFormatter,
第553行: 第482行:
 
...            I want it
 
...            I want it
 
...        '''))
 
...        '''))
&gt;&gt;&gt; parser.print_help()
+
>>> parser.print_help()
 
usage: PROG [-h]
 
usage: PROG [-h]
  
第563行: 第492行:
  
 
optional arguments:
 
optional arguments:
  -h, --help  show this help message and exit</pre>
+
  -h, --help  show this help message and exit</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
[[#argparse.RawTextHelpFormatter|<code>RawTextHelpFormatter</code>]] maintains whitespace for all sorts of help text,
+
[[#argparse.RawTextHelpFormatter|RawTextHelpFormatter]] 为各种帮助文本保留空格,包括参数描述。 但是,多个新行被替换为一个。 如果您希望保留多个空行,请在换行符之间添加空格。
including argument descriptions. However, multiple new lines are replaced with
 
one. If you wish to preserve multiple blank lines, add spaces between the
 
newlines.
 
  
[[#argparse.ArgumentDefaultsHelpFormatter|<code>ArgumentDefaultsHelpFormatter</code>]] automatically adds information about
+
[[#argparse.ArgumentDefaultsHelpFormatter|ArgumentDefaultsHelpFormatter]] 自动将有关默认值的信息添加到每个参数帮助消息中:
default values to each of the argument help messages:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第580行: 第505行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; parser = argparse.ArgumentParser(
+
<syntaxhighlight lang="python3">>>> parser = argparse.ArgumentParser(
 
...    prog='PROG',
 
...    prog='PROG',
 
...    formatter_class=argparse.ArgumentDefaultsHelpFormatter)
 
...    formatter_class=argparse.ArgumentDefaultsHelpFormatter)
&gt;&gt;&gt; parser.add_argument('--foo', type=int, default=42, help='FOO!')
+
>>> parser.add_argument('--foo', type=int, default=42, help='FOO!')
&gt;&gt;&gt; parser.add_argument('bar', nargs='*', default=[1, 2, 3], help='BAR!')
+
>>> parser.add_argument('bar', nargs='*', default=[1, 2, 3], help='BAR!')
&gt;&gt;&gt; parser.print_help()
+
>>> parser.print_help()
 
usage: PROG [-h] [--foo FOO] [bar ...]
 
usage: PROG [-h] [--foo FOO] [bar ...]
  
第593行: 第518行:
 
optional arguments:
 
optional arguments:
 
  -h, --help  show this help message and exit
 
  -h, --help  show this help message and exit
  --foo FOO  FOO! (default: 42)</pre>
+
  --foo FOO  FOO! (default: 42)</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
[[#argparse.MetavarTypeHelpFormatter|<code>MetavarTypeHelpFormatter</code>]] uses the name of the [[#type|type]] argument for each
+
[[#argparse.MetavarTypeHelpFormatter|MetavarTypeHelpFormatter]] 使用每个参数的 [[#type|type]] 参数的名称作为其值的显示名称(而不是像常规格式化程序那样使用 [[#dest|dest]]):
argument as the display name for its values (rather than using the [[#dest|dest]]
 
as the regular formatter does):
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第606行: 第529行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; parser = argparse.ArgumentParser(
+
<syntaxhighlight lang="python3">>>> parser = argparse.ArgumentParser(
 
...    prog='PROG',
 
...    prog='PROG',
 
...    formatter_class=argparse.MetavarTypeHelpFormatter)
 
...    formatter_class=argparse.MetavarTypeHelpFormatter)
&gt;&gt;&gt; parser.add_argument('--foo', type=int)
+
>>> parser.add_argument('--foo', type=int)
&gt;&gt;&gt; parser.add_argument('bar', type=float)
+
>>> parser.add_argument('bar', type=float)
&gt;&gt;&gt; parser.print_help()
+
>>> parser.print_help()
 
usage: PROG [-h] [--foo int] float
 
usage: PROG [-h] [--foo int] float
  
第619行: 第542行:
 
optional arguments:
 
optional arguments:
 
   -h, --help  show this help message and exit
 
   -h, --help  show this help message and exit
   --foo int</pre>
+
   --foo int</syntaxhighlight>
  
 
</div>
 
</div>
第628行: 第551行:
 
<div id="prefix-chars" class="section">
 
<div id="prefix-chars" class="section">
  
=== prefix_chars ===
+
=== 前缀字符 ===
  
Most command-line options will use <code>-</code> as the prefix, e.g. <code>-f/--foo</code>.
+
大多数命令行选项将使用 <code>-</code> 作为前缀,例如 <code>-f/--foo</code>。 需要支持不同或额外前缀字符的解析器,例如 对于 <code>+f</code> <code>/foo</code> 之类的选项,可以使用 <code>prefix_chars=</code> 参数给 ArgumentParser 构造函数指定它们:
Parsers that need to support different or additional prefix
 
characters, e.g. for options
 
like <code>+f</code> or <code>/foo</code>, may specify them using the <code>prefix_chars=</code> argument
 
to the ArgumentParser constructor:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第640行: 第559行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; parser = argparse.ArgumentParser(prog='PROG', prefix_chars='-+')
+
<syntaxhighlight lang="python3">>>> parser = argparse.ArgumentParser(prog='PROG', prefix_chars='-+')
&gt;&gt;&gt; parser.add_argument('+f')
+
>>> parser.add_argument('+f')
&gt;&gt;&gt; parser.add_argument('++bar')
+
>>> parser.add_argument('++bar')
&gt;&gt;&gt; parser.parse_args('+f X ++bar Y'.split())
+
>>> parser.parse_args('+f X ++bar Y'.split())
Namespace(bar='Y', f='X')</pre>
+
Namespace(bar='Y', f='X')</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
The <code>prefix_chars=</code> argument defaults to <code>'-'</code>. Supplying a set of
+
<code>prefix_chars=</code> 参数默认为 <code>'-'</code>。 提供一组不包括 <code>-</code> 的字符将导致 <code>-f/--foo</code> 选项被禁止。
characters that does not include <code>-</code> will cause <code>-f/--foo</code> options to be
 
disallowed.
 
  
  
第659行: 第576行:
 
=== fromfile_prefix_chars ===
 
=== fromfile_prefix_chars ===
  
Sometimes, for example when dealing with a particularly long argument lists, it
+
有时,例如在处理特别长的参数列表时,将参数列表保存在文件中而不是在命令行中输入可能更有意义。 如果将 <code>fromfile_prefix_chars=</code> 参数提供给 [[#argparse.ArgumentParser|ArgumentParser]] 构造函数,则以任何指定字符开头的参数将被视为文件,并将被它们包含的参数替换。 例如:
may make sense to keep the list of arguments in a file rather than typing it out
 
at the command line. If the <code>fromfile_prefix_chars=</code> argument is given to the
 
[[#argparse.ArgumentParser|<code>ArgumentParser</code>]] constructor, then arguments that start with any of the
 
specified characters will be treated as files, and will be replaced by the
 
arguments they contain. For example:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第670行: 第582行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; with open('args.txt', 'w') as fp:
+
<syntaxhighlight lang="python3">>>> with open('args.txt', 'w') as fp:
 
...    fp.write('-f\nbar')
 
...    fp.write('-f\nbar')
&gt;&gt;&gt; parser = argparse.ArgumentParser(fromfile_prefix_chars='@')
+
>>> parser = argparse.ArgumentParser(fromfile_prefix_chars='@')
&gt;&gt;&gt; parser.add_argument('-f')
+
>>> parser.add_argument('-f')
&gt;&gt;&gt; parser.parse_args(['-f', 'foo', '@args.txt'])
+
>>> parser.parse_args(['-f', 'foo', '@args.txt'])
Namespace(f='bar')</pre>
+
Namespace(f='bar')</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
Arguments read from a file must by default be one per line (but see also
+
默认情况下,从文件读取的参数必须每行一个(但另请参见 [[#argparse.ArgumentParser.convert_arg_line_to_args|convert_arg_line_to_args()]]),并被视为与原始文件引用参数在命令行上的位置相同。 所以在上面的例子中,表达式 <code>['-f', 'foo', '@args.txt']</code> 被认为等价于表达式 <code>['-f', 'foo', '-f', 'bar']</code>
[[#argparse.ArgumentParser.convert_arg_line_to_args|<code>convert_arg_line_to_args()</code>]]) and are treated as if they
 
were in the same place as the original file referencing argument on the command
 
line. So in the example above, the expression <code>['-f', 'foo', '@args.txt']</code>
 
is considered equivalent to the expression <code>['-f', 'foo', '-f', 'bar']</code>.
 
  
The <code>fromfile_prefix_chars=</code> argument defaults to <code>None</code>, meaning that
+
<code>fromfile_prefix_chars=</code> 参数默认为 <code>None</code>,这意味着参数永远不会被视为文件引用。
arguments will never be treated as file references.
 
  
  
第693行: 第600行:
 
<div id="argument-default" class="section">
 
<div id="argument-default" class="section">
  
=== argument_default ===
+
=== 参数_默认值 ===
  
Generally, argument defaults are specified either by passing a default to
+
通常,通过将默认值传递给 [[#argparse.ArgumentParser.add_argument|add_argument()]] 或通过使用一组特定的名称-值对调用 [[#argparse.ArgumentParser.set_defaults|set_defaults()]] 方法来指定参数默认值。 然而,有时为参数指定单个解析器范围的默认值可能很有用。 这可以通过将 <code>argument_default=</code> 关键字参数传递给 [[#argparse.ArgumentParser|ArgumentParser]] 来实现。 例如,为了全局禁止在 [[#argparse.ArgumentParser.parse_args|parse_args()]] 调用上创建属性,我们提供 <code>argument_default=SUPPRESS</code>
[[#argparse.ArgumentParser.add_argument|<code>add_argument()</code>]] or by calling the
 
[[#argparse.ArgumentParser.set_defaults|<code>set_defaults()</code>]] methods with a specific set of name-value
 
pairs. Sometimes however, it may be useful to specify a single parser-wide
 
default for arguments. This can be accomplished by passing the
 
<code>argument_default=</code> keyword argument to [[#argparse.ArgumentParser|<code>ArgumentParser</code>]]. For example,
 
to globally suppress attribute creation on [[#argparse.ArgumentParser.parse_args|<code>parse_args()</code>]]
 
calls, we supply <code>argument_default=SUPPRESS</code>:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第708行: 第608行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; parser = argparse.ArgumentParser(argument_default=argparse.SUPPRESS)
+
<syntaxhighlight lang="python3">>>> parser = argparse.ArgumentParser(argument_default=argparse.SUPPRESS)
&gt;&gt;&gt; parser.add_argument('--foo')
+
>>> parser.add_argument('--foo')
&gt;&gt;&gt; parser.add_argument('bar', nargs='?')
+
>>> parser.add_argument('bar', nargs='?')
&gt;&gt;&gt; parser.parse_args(['--foo', '1', 'BAR'])
+
>>> parser.parse_args(['--foo', '1', 'BAR'])
 
Namespace(bar='BAR', foo='1')
 
Namespace(bar='BAR', foo='1')
&gt;&gt;&gt; parser.parse_args([])
+
>>> parser.parse_args([])
Namespace()</pre>
+
Namespace()</syntaxhighlight>
  
 
</div>
 
</div>
第723行: 第623行:
 
<div id="allow-abbrev" class="section">
 
<div id="allow-abbrev" class="section">
  
<span id="id1"></span>
+
<span id="id3"></span>
 
=== allow_abbrev ===
 
=== allow_abbrev ===
  
Normally, when you pass an argument list to the
+
通常,当您将参数列表传递给 [[#argparse.ArgumentParser|ArgumentParser]] [[#argparse.ArgumentParser.parse_args|parse_args()]] 方法时,它 [[#prefix-matching|识别长选项的缩写]]
[[#argparse.ArgumentParser.parse_args|<code>parse_args()</code>]] method of an [[#argparse.ArgumentParser|<code>ArgumentParser</code>]],
 
it [[#prefix-matching|<span class="std std-ref">recognizes abbreviations</span>]] of long options.
 
  
This feature can be disabled by setting <code>allow_abbrev</code> to <code>False</code>:
+
可以通过将 <code>allow_abbrev</code> 设置为 <code>False</code> 来禁用此功能:
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第736行: 第634行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; parser = argparse.ArgumentParser(prog='PROG', allow_abbrev=False)
+
<syntaxhighlight lang="python3">>>> parser = argparse.ArgumentParser(prog='PROG', allow_abbrev=False)
&gt;&gt;&gt; parser.add_argument('--foobar', action='store_true')
+
>>> parser.add_argument('--foobar', action='store_true')
&gt;&gt;&gt; parser.add_argument('--foonley', action='store_false')
+
>>> parser.add_argument('--foonley', action='store_false')
&gt;&gt;&gt; parser.parse_args(['--foon'])
+
>>> parser.parse_args(['--foon'])
 
usage: PROG [-h] [--foobar] [--foonley]
 
usage: PROG [-h] [--foobar] [--foonley]
PROG: error: unrecognized arguments: --foon</pre>
+
PROG: error: unrecognized arguments: --foon</syntaxhighlight>
  
 
</div>
 
</div>
第748行: 第646行:
 
<div class="versionadded">
 
<div class="versionadded">
  
<span class="versionmodified added">3.5 新版功能.</span>
+
<span class="versionmodified added">3.5 版中的新功能。</span>
  
  
第756行: 第654行:
 
<div id="conflict-handler" class="section">
 
<div id="conflict-handler" class="section">
  
=== conflict_handler ===
+
=== 冲突处理程序 ===
  
[[#argparse.ArgumentParser|<code>ArgumentParser</code>]] objects do not allow two actions with the same option
+
[[#argparse.ArgumentParser|ArgumentParser]] 对象不允许具有相同选项字符串的两个操作。 默认情况下,[[#argparse.ArgumentParser|ArgumentParser]] 对象在尝试使用已在使用的选项字符串创建参数时引发异常:
string. By default, [[#argparse.ArgumentParser|<code>ArgumentParser</code>]] objects raise an exception if an
 
attempt is made to create an argument with an option string that is already in
 
use:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第767行: 第662行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; parser = argparse.ArgumentParser(prog='PROG')
+
<syntaxhighlight lang="python3">>>> parser = argparse.ArgumentParser(prog='PROG')
&gt;&gt;&gt; parser.add_argument('-f', '--foo', help='old foo help')
+
>>> parser.add_argument('-f', '--foo', help='old foo help')
&gt;&gt;&gt; parser.add_argument('--foo', help='new foo help')
+
>>> parser.add_argument('--foo', help='new foo help')
 
Traceback (most recent call last):
 
Traceback (most recent call last):
 
  ..
 
  ..
ArgumentError: argument --foo: conflicting option string(s): --foo</pre>
+
ArgumentError: argument --foo: conflicting option string(s): --foo</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
Sometimes (e.g. when using [[#parents|parents]]) it may be useful to simply override any
+
有时(例如 当使用 [[#parents|parents]]) 时,用相同的选项字符串简单地覆盖任何旧参数可能很有用。 要获得此行为,可以将值 <code>'resolve'</code> 提供给 [[#argparse.ArgumentParser|ArgumentParser]] 的 <code>conflict_handler=</code> 参数:
older arguments with the same option string. To get this behavior, the value
 
<code>'resolve'</code> can be supplied to the <code>conflict_handler=</code> argument of
 
[[#argparse.ArgumentParser|<code>ArgumentParser</code>]]:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第786行: 第678行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; parser = argparse.ArgumentParser(prog='PROG', conflict_handler='resolve')
+
<syntaxhighlight lang="python3">>>> parser = argparse.ArgumentParser(prog='PROG', conflict_handler='resolve')
&gt;&gt;&gt; parser.add_argument('-f', '--foo', help='old foo help')
+
>>> parser.add_argument('-f', '--foo', help='old foo help')
&gt;&gt;&gt; parser.add_argument('--foo', help='new foo help')
+
>>> parser.add_argument('--foo', help='new foo help')
&gt;&gt;&gt; parser.print_help()
+
>>> parser.print_help()
 
usage: PROG [-h] [-f FOO] [--foo FOO]
 
usage: PROG [-h] [-f FOO] [--foo FOO]
  
第795行: 第687行:
 
  -h, --help  show this help message and exit
 
  -h, --help  show this help message and exit
 
  -f FOO      old foo help
 
  -f FOO      old foo help
  --foo FOO  new foo help</pre>
+
  --foo FOO  new foo help</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
Note that [[#argparse.ArgumentParser|<code>ArgumentParser</code>]] objects only remove an action if all of its
+
请注意, [[#argparse.ArgumentParser|ArgumentParser]] 对象仅在其所有选项字符串都被覆盖时删除操作。 因此,在上面的示例中,旧的 <code>-f/--foo</code> 操作保留为 <code>-f</code> 操作,因为只有 <code>--foo</code> 选项字符串被覆盖。
option strings are overridden. So, in the example above, the old <code>-f/--foo</code>
 
action is retained as the <code>-f</code> action, because only the <code>--foo</code> option
 
string was overridden.
 
  
  
第809行: 第698行:
 
<div id="add-help" class="section">
 
<div id="add-help" class="section">
  
=== add_help ===
+
=== 添加帮助 ===
  
By default, ArgumentParser objects add an option which simply displays
+
默认情况下, ArgumentParser 对象添加一个选项,该选项仅显示解析器的帮助消息。 例如,考虑一个名为 <code>myprogram.py</code> 的文件,其中包含以下代码:
the parser's help message. For example, consider a file named
 
<code>myprogram.py</code> containing the following code:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第819行: 第706行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>import argparse
+
<syntaxhighlight lang="python3">import argparse
 
parser = argparse.ArgumentParser()
 
parser = argparse.ArgumentParser()
 
parser.add_argument('--foo', help='foo help')
 
parser.add_argument('--foo', help='foo help')
args = parser.parse_args()</pre>
+
args = parser.parse_args()</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
If <code>-h</code> or <code>--help</code> is supplied at the command line, the ArgumentParser
+
如果在命令行提供 <code>-h</code> <code>--help</code>,将打印 ArgumentParser 帮助:
help will be printed:
 
  
 
<div class="highlight-shell-session notranslate">
 
<div class="highlight-shell-session notranslate">
第834行: 第720行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>$ python myprogram.py --help
+
<pre class="session">$ python myprogram.py --help
 
usage: myprogram.py [-h] [--foo FOO]
 
usage: myprogram.py [-h] [--foo FOO]
  
第844行: 第730行:
  
 
</div>
 
</div>
Occasionally, it may be useful to disable the addition of this help option.
+
有时,禁用此帮助选项的添加可能会很有用。 这可以通过将 <code>False</code> 作为 <code>add_help=</code> 参数传递给 [[#argparse.ArgumentParser|ArgumentParser]] 来实现:
This can be achieved by passing <code>False</code> as the <code>add_help=</code> argument to
 
[[#argparse.ArgumentParser|<code>ArgumentParser</code>]]:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第852行: 第736行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; parser = argparse.ArgumentParser(prog='PROG', add_help=False)
+
<syntaxhighlight lang="python3">>>> parser = argparse.ArgumentParser(prog='PROG', add_help=False)
&gt;&gt;&gt; parser.add_argument('--foo', help='foo help')
+
>>> parser.add_argument('--foo', help='foo help')
&gt;&gt;&gt; parser.print_help()
+
>>> parser.print_help()
 
usage: PROG [--foo FOO]
 
usage: PROG [--foo FOO]
  
 
optional arguments:
 
optional arguments:
  --foo FOO  foo help</pre>
+
  --foo FOO  foo help</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
The help option is typically <code>-h/--help</code>. The exception to this is
+
帮助选项通常是 <code>-h/--help</code>。 例外情况是,如果指定了 <code>prefix_chars=</code> 并且不包括 <code>-</code>,在这种情况下 <code>-h</code> <code>--help</code> 不是有效选项。 在这种情况下,<code>prefix_chars</code> 中的第一个字符用于作为帮助选项的前缀:
if the <code>prefix_chars=</code> is specified and does not include <code>-</code>, in
 
which case <code>-h</code> and <code>--help</code> are not valid options. In
 
this case, the first character in <code>prefix_chars</code> is used to prefix
 
the help options:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第873行: 第753行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; parser = argparse.ArgumentParser(prog='PROG', prefix_chars='+/')
+
<syntaxhighlight lang="python3">>>> parser = argparse.ArgumentParser(prog='PROG', prefix_chars='+/')
&gt;&gt;&gt; parser.print_help()
+
>>> parser.print_help()
 
usage: PROG [+h]
 
usage: PROG [+h]
  
 
optional arguments:
 
optional arguments:
   +h, ++help  show this help message and exit</pre>
+
   +h, ++help  show this help message and exit</syntaxhighlight>
  
 
</div>
 
</div>
第889行: 第769行:
 
=== exit_on_error ===
 
=== exit_on_error ===
  
Normally, when you pass an invalid argument list to the [[#argparse.ArgumentParser.parse_args|<code>parse_args()</code>]]
+
通常,当您将无效参数列表传递给 [[#argparse.ArgumentParser|ArgumentParser]] [[#argparse.ArgumentParser.parse_args|parse_args()]] 方法时,它将退出并显示错误信息。
method of an [[#argparse.ArgumentParser|<code>ArgumentParser</code>]], it will exit with error info.
 
  
If the user would like catch errors manually, the feature can be enable by setting
+
如果用户想手动捕获错误,可以通过将 <code>exit_on_error</code> 设置为 <code>False</code> 来启用该功能:
<code>exit_on_error</code> to <code>False</code>:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第899行: 第777行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; parser = argparse.ArgumentParser(exit_on_error=False)
+
<syntaxhighlight lang="python3">>>> parser = argparse.ArgumentParser(exit_on_error=False)
&gt;&gt;&gt; parser.add_argument('--integers', type=int)
+
>>> parser.add_argument('--integers', type=int)
_StoreAction(option_strings=['--integers'], dest='integers', nargs=None, const=None, default=None, type=&lt;class 'int'&gt;, choices=None, help=None, metavar=None)
+
_StoreAction(option_strings=['--integers'], dest='integers', nargs=None, const=None, default=None, type=<class 'int'>, choices=None, help=None, metavar=None)
&gt;&gt;&gt; try:
+
>>> try:
 
...    parser.parse_args('--integers a'.split())
 
...    parser.parse_args('--integers a'.split())
 
... except argparse.ArgumentError:
 
... except argparse.ArgumentError:
 
...    print('Catching an argumentError')
 
...    print('Catching an argumentError')
 
...
 
...
Catching an argumentError</pre>
+
Catching an argumentError</syntaxhighlight>
  
 
</div>
 
</div>
第914行: 第792行:
 
<div class="versionadded">
 
<div class="versionadded">
  
<span class="versionmodified added">3.9 新版功能.</span>
+
<span class="versionmodified added">3.9 版中的新功能。</span>
  
  
第924行: 第802行:
 
<div id="the-add-argument-method" class="section">
 
<div id="the-add-argument-method" class="section">
  
== The add_argument() method ==
+
== add_argument() 方法 ==
  
; <code>ArgumentParser.</code><code>add_argument</code><span class="sig-paren">(</span>''name or flags...''<span class="optional">[</span>, ''action''<span class="optional">]</span><span class="optional">[</span>, ''nargs''<span class="optional">]</span><span class="optional">[</span>, ''const''<span class="optional">]</span><span class="optional">[</span>, ''default''<span class="optional">]</span><span class="optional">[</span>, ''type''<span class="optional">]</span><span class="optional">[</span>, ''choices''<span class="optional">]</span><span class="optional">[</span>, ''required''<span class="optional">]</span><span class="optional">[</span>, ''help''<span class="optional">]</span><span class="optional">[</span>, ''metavar''<span class="optional">]</span><span class="optional">[</span>, ''dest''<span class="optional">]</span><span class="sig-paren">)</span>
+
; <span class="sig-prename descclassname"><span class="pre">ArgumentParser.</span></span><span class="sig-name descname"><span class="pre">add_argument</span></span><span class="sig-paren">(</span>''<span class="pre">name</span> <span class="pre">or</span> <span class="pre">flags...</span>''<span class="optional">[</span>, ''<span class="pre">action</span>''<span class="optional">]</span><span class="optional">[</span>, ''<span class="pre">nargs</span>''<span class="optional">]</span><span class="optional">[</span>, ''<span class="pre">const</span>''<span class="optional">]</span><span class="optional">[</span>, ''<span class="pre">default</span>''<span class="optional">]</span><span class="optional">[</span>, ''<span class="pre">type</span>''<span class="optional">]</span><span class="optional">[</span>, ''<span class="pre">choices</span>''<span class="optional">]</span><span class="optional">[</span>, ''<span class="pre">required</span>''<span class="optional">]</span><span class="optional">[</span>, ''<span class="pre">help</span>''<span class="optional">]</span><span class="optional">[</span>, ''<span class="pre">metavar</span>''<span class="optional">]</span><span class="optional">[</span>, ''<span class="pre">dest</span>''<span class="optional">]</span><span class="sig-paren">)</span>
: Define how a single command-line argument should be parsed. Each parameter has its own more detailed description below, but in short they are:
+
: 定义应如何解析单个命令行参数。 每个参数在下面都有更详细的描述,但简而言之,它们是:
;* [[#name-or-flags|name or flags]] - Either a name or a list of option strings, e.g. <code>foo</code> or <code>-f, --foo</code>.
+
;* [[#name-or-flags|name flags]] - 名称或选项字符串列表,例如 <code>foo</code> <code>-f, --foo</code>
;* [[#action|action]] - The basic type of action to be taken when this argument is encountered at the command line.
+
;* [[#action|action]] - 在命令行遇到此参数时要采取的基本操作类型。
;* [[#nargs|nargs]] - The number of command-line arguments that should be consumed.
+
;* [[#nargs|nargs]] - 应该使用的命令行参数的数量。
;* [[#const|const]] - A constant value required by some [[#action|action]] and [[#nargs|nargs]] selections.
+
;* [[#const|const]] - 某些 [[#action|action]] [[#nargs|nargs]] 选择所需的常量值。
;* [[#default|default]] - The value produced if the argument is absent from the command line.
+
;* [[#default|default]] - 命令行中不存在参数并且命名空间对象中不存在时产生的值。
;* [[#type|type]] - The type to which the command-line argument should be converted.
+
;* [[#type|type]] - 命令行参数应转换为的类型。
;* [[#choices|choices]] - A container of the allowable values for the argument.
+
;* [[#choices|choices]] - 参数允许值的容器。
;* [[#required|required]] - Whether or not the command-line option may be omitted (optionals only).
+
;* [[#required|required]] - 是否可以省略命令行选项(仅限可选)。
;* [[#help|help]] - A brief description of what the argument does.
+
;* [[#help|help]] - 对参数作用的简要描述。
;* [[#metavar|metavar]] - A name for the argument in usage messages.
+
;* [[#metavar|metavar]] - 使用消息中参数的名称。
;* [[#dest|dest]] - The name of the attribute to be added to the object returned by [[#argparse.ArgumentParser.parse_args|<code>parse_args()</code>]].
+
;* [[#dest|dest]] - 要添加到 [[#argparse.ArgumentParser.parse_args|parse_args()]] 返回的对象的属性名称。
  
The following sections describe how each of these are used.
+
以下各节描述了如何使用它们中的每一个。
  
 
<div id="name-or-flags" class="section">
 
<div id="name-or-flags" class="section">
  
=== name or flags ===
+
=== 名称或标志 ===
  
The [[#argparse.ArgumentParser.add_argument|<code>add_argument()</code>]] method must know whether an optional
+
[[#argparse.ArgumentParser.add_argument|add_argument()]] 方法必须知道是否需要可选参数(如 <code>-f</code> <code>--foo</code>)或位置参数(如文件名列表)。 因此,传递给 [[#argparse.ArgumentParser.add_argument|add_argument()]] 的第一个参数必须是一系列标志或一个简单的参数名称。 例如,可以创建一个可选参数,如:
argument, like <code>-f</code> or <code>--foo</code>, or a positional argument, like a list of
 
filenames, is expected. The first arguments passed to
 
[[#argparse.ArgumentParser.add_argument|<code>add_argument()</code>]] must therefore be either a series of
 
flags, or a simple argument name. For example, an optional argument could
 
be created like:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第957行: 第830行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; parser.add_argument('-f', '--foo')</pre>
+
<syntaxhighlight lang="python3">>>> parser.add_argument('-f', '--foo')</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
while a positional argument could be created like:
+
虽然可以创建位置参数,例如:
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第968行: 第841行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; parser.add_argument('bar')</pre>
+
<syntaxhighlight lang="python3">>>> parser.add_argument('bar')</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
When [[#argparse.ArgumentParser.parse_args|<code>parse_args()</code>]] is called, optional arguments will be
+
[[#argparse.ArgumentParser.parse_args|parse_args()]] 被调用时,可选参数将由 <code>-</code> 前缀标识,其余参数将被假定为位置参数:
identified by the <code>-</code> prefix, and the remaining arguments will be assumed to
 
be positional:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第981行: 第852行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; parser = argparse.ArgumentParser(prog='PROG')
+
<syntaxhighlight lang="python3">>>> parser = argparse.ArgumentParser(prog='PROG')
&gt;&gt;&gt; parser.add_argument('-f', '--foo')
+
>>> parser.add_argument('-f', '--foo')
&gt;&gt;&gt; parser.add_argument('bar')
+
>>> parser.add_argument('bar')
&gt;&gt;&gt; parser.parse_args(['BAR'])
+
>>> parser.parse_args(['BAR'])
 
Namespace(bar='BAR', foo=None)
 
Namespace(bar='BAR', foo=None)
&gt;&gt;&gt; parser.parse_args(['BAR', '--foo', 'FOO'])
+
>>> parser.parse_args(['BAR', '--foo', 'FOO'])
 
Namespace(bar='BAR', foo='FOO')
 
Namespace(bar='BAR', foo='FOO')
&gt;&gt;&gt; parser.parse_args(['--foo', 'FOO'])
+
>>> parser.parse_args(['--foo', 'FOO'])
 
usage: PROG [-h] [-f FOO] bar
 
usage: PROG [-h] [-f FOO] bar
PROG: error: the following arguments are required: bar</pre>
+
PROG: error: the following arguments are required: bar</syntaxhighlight>
  
 
</div>
 
</div>
第999行: 第870行:
 
<div id="action" class="section">
 
<div id="action" class="section">
  
=== action ===
+
=== 行动 ===
  
[[#argparse.ArgumentParser|<code>ArgumentParser</code>]] objects associate command-line arguments with actions. These
+
[[#argparse.ArgumentParser|ArgumentParser]] 对象将命令行参数与操作相关联。 这些操作几乎可以使用与其关联的命令行参数执行任何操作,尽管大多数操作只是向 [[#argparse.ArgumentParser.parse_args|parse_args()]] 返回的对象添加一个属性。 <code>action</code> 关键字参数指定应如何处理命令行参数。 提供的操作是:
actions can do just about anything with the command-line arguments associated with
 
them, though most actions simply add an attribute to the object returned by
 
[[#argparse.ArgumentParser.parse_args|<code>parse_args()</code>]]. The <code>action</code> keyword argument specifies
 
how the command-line arguments should be handled. The supplied actions are:
 
  
 
<ul>
 
<ul>
<li><p><code>'store'</code> - This just stores the argument's value. This is the default
+
<li><p><code>'store'</code> - 这只是存储参数的值。 这是默认操作。 例如:</p>
action. For example:</p>
 
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
  
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; parser = argparse.ArgumentParser()
+
<syntaxhighlight lang="python3">>>> parser = argparse.ArgumentParser()
&gt;&gt;&gt; parser.add_argument('--foo')
+
>>> parser.add_argument('--foo')
&gt;&gt;&gt; parser.parse_args('--foo 1'.split())
+
>>> parser.parse_args('--foo 1'.split())
Namespace(foo='1')</pre>
+
Namespace(foo='1')</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div></li>
 
</div></li>
<li><p><code>'store_const'</code> - This stores the value specified by the [[#const|const]] keyword
+
<li><p><code>'store_const'</code> - 存储由 [[#const|const]] 关键字参数指定的值。 <code>'store_const'</code> 操作最常与指定某种标志的可选参数一起使用。 例如:</p>
argument. The <code>'store_const'</code> action is most commonly used with
 
optional arguments that specify some sort of flag. For example:</p>
 
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
  
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; parser = argparse.ArgumentParser()
+
<syntaxhighlight lang="python3">>>> parser = argparse.ArgumentParser()
&gt;&gt;&gt; parser.add_argument('--foo', action='store_const', const=42)
+
>>> parser.add_argument('--foo', action='store_const', const=42)
&gt;&gt;&gt; parser.parse_args(['--foo'])
+
>>> parser.parse_args(['--foo'])
Namespace(foo=42)</pre>
+
Namespace(foo=42)</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div></li>
 
</div></li>
<li><p><code>'store_true'</code> and <code>'store_false'</code> - These are special cases of
+
<li><p><code>'store_true'</code> <code>'store_false'</code> - 这些是 <code>'store_const'</code> 的特例,分别用于存储值 <code>True</code> <code>False</code>。 此外,它们分别创建 <code>False</code> <code>True</code> 的默认值。 例如:</p>
<code>'store_const'</code> used for storing the values <code>True</code> and <code>False</code>
 
respectively. In addition, they create default values of <code>False</code> and
 
<code>True</code> respectively. For example:</p>
 
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
  
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; parser = argparse.ArgumentParser()
+
<syntaxhighlight lang="python3">>>> parser = argparse.ArgumentParser()
&gt;&gt;&gt; parser.add_argument('--foo', action='store_true')
+
>>> parser.add_argument('--foo', action='store_true')
&gt;&gt;&gt; parser.add_argument('--bar', action='store_false')
+
>>> parser.add_argument('--bar', action='store_false')
&gt;&gt;&gt; parser.add_argument('--baz', action='store_false')
+
>>> parser.add_argument('--baz', action='store_false')
&gt;&gt;&gt; parser.parse_args('--foo --bar'.split())
+
>>> parser.parse_args('--foo --bar'.split())
Namespace(foo=True, bar=False, baz=True)</pre>
+
Namespace(foo=True, bar=False, baz=True)</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div></li>
 
</div></li>
<li><p><code>'append'</code> - This stores a list, and appends each argument value to the
+
<li><p><code>'append'</code> - 存储一个列表,并将每个参数值附加到列表中。 这对于允许多次指定一个选项很有用。 用法示例:</p>
list. This is useful to allow an option to be specified multiple times.
 
Example usage:</p>
 
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
  
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; parser = argparse.ArgumentParser()
+
<syntaxhighlight lang="python3">>>> parser = argparse.ArgumentParser()
&gt;&gt;&gt; parser.add_argument('--foo', action='append')
+
>>> parser.add_argument('--foo', action='append')
&gt;&gt;&gt; parser.parse_args('--foo 1 --foo 2'.split())
+
>>> parser.parse_args('--foo 1 --foo 2'.split())
Namespace(foo=['1', '2'])</pre>
+
Namespace(foo=['1', '2'])</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div></li>
 
</div></li>
<li><p><code>'append_const'</code> - This stores a list, and appends the value specified by
+
<li><p><code>'append_const'</code> - 存储一个列表,并将 [[#const|const]] 关键字参数指定的值附加到列表中。 (请注意,[[#const|const]] 关键字参数默认为 <code>None</code>。)当多个参数需要将常量存储到同一列表时,<code>'append_const'</code> 操作通常很有用。 例如:</p>
the [[#const|const]] keyword argument to the list. (Note that the [[#const|const]] keyword
 
argument defaults to <code>None</code>.) The <code>'append_const'</code> action is typically
 
useful when multiple arguments need to store constants to the same list. For
 
example:</p>
 
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
  
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; parser = argparse.ArgumentParser()
+
<syntaxhighlight lang="python3">>>> parser = argparse.ArgumentParser()
&gt;&gt;&gt; parser.add_argument('--str', dest='types', action='append_const', const=str)
+
>>> parser.add_argument('--str', dest='types', action='append_const', const=str)
&gt;&gt;&gt; parser.add_argument('--int', dest='types', action='append_const', const=int)
+
>>> parser.add_argument('--int', dest='types', action='append_const', const=int)
&gt;&gt;&gt; parser.parse_args('--str --int'.split())
+
>>> parser.parse_args('--str --int'.split())
Namespace(types=[&lt;class 'str'&gt;, &lt;class 'int'&gt;])</pre>
+
Namespace(types=[<class 'str'>, <class 'int'>])</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div></li>
 
</div></li>
<li><p><code>'count'</code> - This counts the number of times a keyword argument occurs. For
+
<li><p><code>'count'</code> - 计算关键字参数出现的次数。 例如,这对于提高详细级别很有用:</p>
example, this is useful for increasing verbosity levels:</p>
 
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
  
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; parser = argparse.ArgumentParser()
+
<syntaxhighlight lang="python3">>>> parser = argparse.ArgumentParser()
&gt;&gt;&gt; parser.add_argument('--verbose', '-v', action='count', default=0)
+
>>> parser.add_argument('--verbose', '-v', action='count', default=0)
&gt;&gt;&gt; parser.parse_args(['-vvv'])
+
>>> parser.parse_args(['-vvv'])
Namespace(verbose=3)</pre>
+
Namespace(verbose=3)</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
<p>Note, the ''default'' will be <code>None</code> unless explicitly set to ''0''.</p></li>
+
<p>请注意,除非明确设置为 ''0'',否则 ''默认'' 将为 <code>None</code></p></li>
<li><p><code>'help'</code> - This prints a complete help message for all the options in the
+
<li><p><code>'help'</code> - 这会打印当前解析器中所有选项的完整帮助消息,然后退出。 默认情况下,帮助操作会自动添加到解析器中。 有关如何创建输出的详细信息,请参阅 [[#argparse.ArgumentParser|ArgumentParser]]</p></li>
current parser and then exits. By default a help action is automatically
+
<li><p><code>'version'</code> - 这需要 [[#argparse.ArgumentParser.add_argument|add_argument()]] 调用中的 <code>version=</code> 关键字参数,并在调用时打印版本信息并退出:</p>
added to the parser. See [[#argparse.ArgumentParser|<code>ArgumentParser</code>]] for details of how the
 
output is created.</p></li>
 
<li><p><code>'version'</code> - This expects a <code>version=</code> keyword argument in the
 
[[#argparse.ArgumentParser.add_argument|<code>add_argument()</code>]] call, and prints version information
 
and exits when invoked:</p>
 
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
  
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; import argparse
+
<syntaxhighlight lang="python3">>>> import argparse
&gt;&gt;&gt; parser = argparse.ArgumentParser(prog='PROG')
+
>>> parser = argparse.ArgumentParser(prog='PROG')
&gt;&gt;&gt; parser.add_argument('--version', action='version', version='%(prog)s 2.0')
+
>>> parser.add_argument('--version', action='version', version='%(prog)s 2.0')
&gt;&gt;&gt; parser.parse_args(['--version'])
+
>>> parser.parse_args(['--version'])
PROG 2.0</pre>
+
PROG 2.0</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div></li>
 
</div></li>
<li><p><code>'extend'</code> - This stores a list, and extends each argument value to the
+
<li><p><code>'extend'</code> - 这存储一个列表,并将每个参数值扩展到列表。 用法示例:</p>
list.
 
Example usage:</p>
 
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
  
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; parser = argparse.ArgumentParser()
+
<syntaxhighlight lang="python3">>>> parser = argparse.ArgumentParser()
&gt;&gt;&gt; parser.add_argument(&quot;--foo&quot;, action=&quot;extend&quot;, nargs=&quot;+&quot;, type=str)
+
>>> parser.add_argument("--foo", action="extend", nargs="+", type=str)
&gt;&gt;&gt; parser.parse_args([&quot;--foo&quot;, &quot;f1&quot;, &quot;--foo&quot;, &quot;f2&quot;, &quot;f3&quot;, &quot;f4&quot;])
+
>>> parser.parse_args(["--foo", "f1", "--foo", "f2", "f3", "f4"])
Namespace(foo=['f1', 'f2', 'f3', 'f4'])</pre>
+
Namespace(foo=['f1', 'f2', 'f3', 'f4'])</syntaxhighlight>
  
 
</div>
 
</div>
第1,140行: 第987行:
 
<div class="versionadded">
 
<div class="versionadded">
  
<p><span class="versionmodified added">3.8 新版功能.</span></p>
+
<p><span class="versionmodified added">3.8 版中的新功能。</span></p>
  
 
</div></li></ul>
 
</div></li></ul>
  
You may also specify an arbitrary action by passing an Action subclass or
+
您还可以通过传递实现相同接口的 Action 子类或其他对象来指定任意操作。 <code>BooleanOptionalAction</code> <code>argparse</code> 中可用,并添加了对布尔操作的支持,例如 <code>--foo</code> <code>--no-foo</code>
other object that implements the same interface. The <code>BooleanOptionalAction</code>
 
is available in <code>argparse</code> and adds support for boolean actions such as
 
<code>--foo</code> and <code>--no-foo</code>:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第1,153行: 第997行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; import argparse
+
<syntaxhighlight lang="python3">>>> import argparse
&gt;&gt;&gt; parser = argparse.ArgumentParser()
+
>>> parser = argparse.ArgumentParser()
&gt;&gt;&gt; parser.add_argument('--foo', action=argparse.BooleanOptionalAction)
+
>>> parser.add_argument('--foo', action=argparse.BooleanOptionalAction)
&gt;&gt;&gt; parser.parse_args(['--no-foo'])
+
>>> parser.parse_args(['--no-foo'])
Namespace(foo=False)</pre>
+
Namespace(foo=False)</syntaxhighlight>
 +
 
 +
</div>
  
 
</div>
 
</div>
 +
<div class="versionadded">
 +
 +
<span class="versionmodified added">3.9 版中的新功能。</span>
 +
  
 
</div>
 
</div>
The recommended way to create a custom action is to extend [[#argparse.Action|<code>Action</code>]],
+
创建自定义操作的推荐方法是扩展 [[#argparse.Action|Action]],覆盖 <code>__call__</code> 方法和可选的 <code>__init__</code> <code>format_usage</code> 方法。
overriding the <code>__call__</code> method and optionally the <code>__init__</code> and
 
<code>format_usage</code> methods.
 
  
An example of a custom action:
+
自定义操作的示例:
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第1,172行: 第1,020行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; class FooAction(argparse.Action):
+
<syntaxhighlight lang="python3">>>> class FooAction(argparse.Action):
 
...    def __init__(self, option_strings, dest, nargs=None, **kwargs):
 
...    def __init__(self, option_strings, dest, nargs=None, **kwargs):
 
...        if nargs is not None:
 
...        if nargs is not None:
...            raise ValueError(&quot;nargs not allowed&quot;)
+
...            raise ValueError("nargs not allowed")
...        super(FooAction, self).__init__(option_strings, dest, **kwargs)
+
...        super().__init__(option_strings, dest, **kwargs)
 
...    def __call__(self, parser, namespace, values, option_string=None):
 
...    def __call__(self, parser, namespace, values, option_string=None):
 
...        print('%r %r %r' % (namespace, values, option_string))
 
...        print('%r %r %r' % (namespace, values, option_string))
 
...        setattr(namespace, self.dest, values)
 
...        setattr(namespace, self.dest, values)
 
...
 
...
&gt;&gt;&gt; parser = argparse.ArgumentParser()
+
>>> parser = argparse.ArgumentParser()
&gt;&gt;&gt; parser.add_argument('--foo', action=FooAction)
+
>>> parser.add_argument('--foo', action=FooAction)
&gt;&gt;&gt; parser.add_argument('bar', action=FooAction)
+
>>> parser.add_argument('bar', action=FooAction)
&gt;&gt;&gt; args = parser.parse_args('1 --foo 2'.split())
+
>>> args = parser.parse_args('1 --foo 2'.split())
 
Namespace(bar=None, foo=None) '1' None
 
Namespace(bar=None, foo=None) '1' None
 
Namespace(bar='1', foo=None) '2' '--foo'
 
Namespace(bar='1', foo=None) '2' '--foo'
&gt;&gt;&gt; args
+
>>> args
Namespace(bar='1', foo='2')</pre>
+
Namespace(bar='1', foo='2')</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
For more details, see [[#argparse.Action|<code>Action</code>]].
+
详情请参见[[#argparse.Action|动作]]
  
  
第1,201行: 第1,049行:
 
=== nargs ===
 
=== nargs ===
  
ArgumentParser objects usually associate a single command-line argument with a
+
ArgumentParser 对象通常将单个命令行参数与要采取的单个操作相关联。 <code>nargs</code> 关键字参数将不同数量的命令行参数与单个操作相关联。 支持的值为:
single action to be taken. The <code>nargs</code> keyword argument associates a
 
different number of command-line arguments with a single action. The supported
 
values are:
 
  
 
<ul>
 
<ul>
<li><p><code>N</code> (an integer). <code>N</code> arguments from the command line will be gathered
+
<li><p><code>N</code>(整数)。 来自命令行的 <code>N</code> 参数将被收集到一个列表中。 例如:</p>
together into a list. For example:</p>
 
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
  
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; parser = argparse.ArgumentParser()
+
<syntaxhighlight lang="python3">>>> parser = argparse.ArgumentParser()
&gt;&gt;&gt; parser.add_argument('--foo', nargs=2)
+
>>> parser.add_argument('--foo', nargs=2)
&gt;&gt;&gt; parser.add_argument('bar', nargs=1)
+
>>> parser.add_argument('bar', nargs=1)
&gt;&gt;&gt; parser.parse_args('c --foo a b'.split())
+
>>> parser.parse_args('c --foo a b'.split())
Namespace(bar=['c'], foo=['a', 'b'])</pre>
+
Namespace(bar=['c'], foo=['a', 'b'])</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
<p>Note that <code>nargs=1</code> produces a list of one item. This is different from
+
<p>请注意, <code>nargs=1</code> 生成一个包含一项的列表。 这与默认情况下不同,默认情况下项目是由自己生产的。</p></li></ul>
the default, in which the item is produced by itself.</p></li></ul>
 
  
 
<ul>
 
<ul>
<li><p><code>'?'</code>. One argument will be consumed from the command line if possible, and
+
<li><p><code>'?'</code>。 如果可能,将从命令行使用一个参数,并作为单个项目生成。 如果不存在命令行参数,则将生成 [[#default|default]] 中的值。 请注意,对于可选参数,还有一种情况 - 选项字符串存在但后面没有命令行参数。 在这种情况下,将产生来自 [[#const|const]] 的值。 一些例子来说明这一点:</p>
produced as a single item. If no command-line argument is present, the value from
 
[[#default|default]] will be produced. Note that for optional arguments, there is an
 
additional case - the option string is present but not followed by a
 
command-line argument. In this case the value from [[#const|const]] will be produced. Some
 
examples to illustrate this:</p>
 
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
  
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; parser = argparse.ArgumentParser()
+
<syntaxhighlight lang="python3">>>> parser = argparse.ArgumentParser()
&gt;&gt;&gt; parser.add_argument('--foo', nargs='?', const='c', default='d')
+
>>> parser.add_argument('--foo', nargs='?', const='c', default='d')
&gt;&gt;&gt; parser.add_argument('bar', nargs='?', default='d')
+
>>> parser.add_argument('bar', nargs='?', default='d')
&gt;&gt;&gt; parser.parse_args(['XX', '--foo', 'YY'])
+
>>> parser.parse_args(['XX', '--foo', 'YY'])
 
Namespace(bar='XX', foo='YY')
 
Namespace(bar='XX', foo='YY')
&gt;&gt;&gt; parser.parse_args(['XX', '--foo'])
+
>>> parser.parse_args(['XX', '--foo'])
 
Namespace(bar='XX', foo='c')
 
Namespace(bar='XX', foo='c')
&gt;&gt;&gt; parser.parse_args([])
+
>>> parser.parse_args([])
Namespace(bar='d', foo='d')</pre>
+
Namespace(bar='d', foo='d')</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
<p>One of the more common uses of <code>nargs='?'</code> is to allow optional input and
+
<p><code>nargs='?'</code> 更常见的用途之一是允许可选的输入和输出文件:</p>
output files:</p>
 
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
  
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; parser = argparse.ArgumentParser()
+
<syntaxhighlight lang="python3">>>> parser = argparse.ArgumentParser()
&gt;&gt;&gt; parser.add_argument('infile', nargs='?', type=argparse.FileType('r'),
+
>>> parser.add_argument('infile', nargs='?', type=argparse.FileType('r'),
 
...                    default=sys.stdin)
 
...                    default=sys.stdin)
&gt;&gt;&gt; parser.add_argument('outfile', nargs='?', type=argparse.FileType('w'),
+
>>> parser.add_argument('outfile', nargs='?', type=argparse.FileType('w'),
 
...                    default=sys.stdout)
 
...                    default=sys.stdout)
&gt;&gt;&gt; parser.parse_args(['input.txt', 'output.txt'])
+
>>> parser.parse_args(['input.txt', 'output.txt'])
Namespace(infile=&lt;_io.TextIOWrapper name='input.txt' encoding='UTF-8'&gt;,
+
Namespace(infile=<_io.TextIOWrapper name='input.txt' encoding='UTF-8'>,
           outfile=&lt;_io.TextIOWrapper name='output.txt' encoding='UTF-8'&gt;)
+
           outfile=<_io.TextIOWrapper name='output.txt' encoding='UTF-8'>)
&gt;&gt;&gt; parser.parse_args([])
+
>>> parser.parse_args([])
Namespace(infile=&lt;_io.TextIOWrapper name='&lt;stdin&gt;' encoding='UTF-8'&gt;,
+
Namespace(infile=<_io.TextIOWrapper name='<stdin>' encoding='UTF-8'>,
           outfile=&lt;_io.TextIOWrapper name='&lt;stdout&gt;' encoding='UTF-8'&gt;)</pre>
+
           outfile=<_io.TextIOWrapper name='<stdout>' encoding='UTF-8'>)</syntaxhighlight>
  
 
</div>
 
</div>
第1,272行: 第1,109行:
  
 
<ul>
 
<ul>
<li><p><code>'*'</code>. All command-line arguments present are gathered into a list. Note that
+
<li><p><code>'*'</code>。 存在的所有命令行参数都被收集到一个列表中。 请注意,使用 <code>nargs='*'</code> 拥有多个位置参数通常没有多大意义,但使用 <code>nargs='*'</code> 的多个可选参数是可能的。 例如:</p>
it generally doesn't make much sense to have more than one positional argument
 
with <code>nargs='*'</code>, but multiple optional arguments with <code>nargs='*'</code> is
 
possible. For example:</p>
 
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
  
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; parser = argparse.ArgumentParser()
+
<syntaxhighlight lang="python3">>>> parser = argparse.ArgumentParser()
&gt;&gt;&gt; parser.add_argument('--foo', nargs='*')
+
>>> parser.add_argument('--foo', nargs='*')
&gt;&gt;&gt; parser.add_argument('--bar', nargs='*')
+
>>> parser.add_argument('--bar', nargs='*')
&gt;&gt;&gt; parser.add_argument('baz', nargs='*')
+
>>> parser.add_argument('baz', nargs='*')
&gt;&gt;&gt; parser.parse_args('a b --foo x y --bar 1 2'.split())
+
>>> parser.parse_args('a b --foo x y --bar 1 2'.split())
Namespace(bar=['1', '2'], baz=['a', 'b'], foo=['x', 'y'])</pre>
+
Namespace(bar=['1', '2'], baz=['a', 'b'], foo=['x', 'y'])</syntaxhighlight>
  
 
</div>
 
</div>
第1,292行: 第1,126行:
  
 
<ul>
 
<ul>
<li><p><code>'+'</code>. Just like <code>'*'</code>, all command-line args present are gathered into a
+
<li><p><code>'+'</code>。 就像 <code>'*'</code> 一样,所有存在的命令行参数都被收集到一个列表中。 此外,如果不存在至少一个命令行参数,则会生成一条错误消息。 例如:</p>
list. Additionally, an error message will be generated if there wasn't at
 
least one command-line argument present. For example:</p>
 
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
  
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; parser = argparse.ArgumentParser(prog='PROG')
+
<syntaxhighlight lang="python3">>>> parser = argparse.ArgumentParser(prog='PROG')
&gt;&gt;&gt; parser.add_argument('foo', nargs='+')
+
>>> parser.add_argument('foo', nargs='+')
&gt;&gt;&gt; parser.parse_args(['a', 'b'])
+
>>> parser.parse_args(['a', 'b'])
 
Namespace(foo=['a', 'b'])
 
Namespace(foo=['a', 'b'])
&gt;&gt;&gt; parser.parse_args([])
+
>>> parser.parse_args([])
 
usage: PROG [-h] foo [foo ...]
 
usage: PROG [-h] foo [foo ...]
PROG: error: the following arguments are required: foo</pre>
+
PROG: error: the following arguments are required: foo</syntaxhighlight>
  
 
</div>
 
</div>
第1,311行: 第1,143行:
 
</div></li></ul>
 
</div></li></ul>
  
If the <code>nargs</code> keyword argument is not provided, the number of arguments consumed
+
如果未提供 <code>nargs</code> 关键字参数,则消耗的参数数量由 [[#action|action]] 决定。 通常这意味着将使用单个命令行参数并生成单个项目(不是列表)。
is determined by the [[#action|action]]. Generally this means a single command-line argument
 
will be consumed and a single item (not a list) will be produced.
 
  
  
第1,319行: 第1,149行:
 
<div id="const" class="section">
 
<div id="const" class="section">
  
=== const ===
+
=== 常量 ===
  
The <code>const</code> argument of [[#argparse.ArgumentParser.add_argument|<code>add_argument()</code>]] is used to hold
+
[[#argparse.ArgumentParser.add_argument|add_argument()]] 的 <code>const</code> 参数用于保存不是从命令行读取但各种 [[#argparse.ArgumentParser|ArgumentParser]] 操作所需的常量值。 它的两个最常见用途是:
constant values that are not read from the command line but are required for
 
the various [[#argparse.ArgumentParser|<code>ArgumentParser</code>]] actions. The two most common uses of it are:
 
  
* When [[#argparse.ArgumentParser.add_argument|<code>add_argument()</code>]] is called with <code>action='store_const'</code> or <code>action='append_const'</code>. These actions add the <code>const</code> value to one of the attributes of the object returned by [[#argparse.ArgumentParser.parse_args|<code>parse_args()</code>]]. See the [[#action|action]] description for examples.
+
* 当使用 <code>action='store_const'</code> <code>action='append_const'</code> 调用 [[#argparse.ArgumentParser.add_argument|add_argument()]] 时。 这些操作将 <code>const</code> 值添加到 [[#argparse.ArgumentParser.parse_args|parse_args()]] 返回的对象属性之一。 有关示例,请参阅 [[#action|action]] 说明。
* When [[#argparse.ArgumentParser.add_argument|<code>add_argument()</code>]] is called with option strings (like <code>-f</code> or <code>--foo</code>) and <code>nargs='?'</code>. This creates an optional argument that can be followed by zero or one command-line arguments. When parsing the command line, if the option string is encountered with no command-line argument following it, the value of <code>const</code> will be assumed instead. See the [[#nargs|nargs]] description for examples.
+
* 当使用选项字符串(如 <code>-f</code> <code>--foo</code>)和 <code>nargs='?'</code> 调用 [[#argparse.ArgumentParser.add_argument|add_argument()]] 时。 这将创建一个可选参数,其后可以跟零个或一个命令行参数。 解析命令行时,如果遇到选项字符串后面没有命令行参数,则将假定 <code>const</code> 的值。 有关示例,请参阅 [[#nargs|nargs]] 说明。
  
With the <code>'store_const'</code> and <code>'append_const'</code> actions, the <code>const</code>
+
对于 <code>'store_const'</code> <code>'append_const'</code> 操作,必须给出 <code>const</code> 关键字参数。 其他动作默认为<code>None</code>
keyword argument must be given. For other actions, it defaults to <code>None</code>.
 
  
  
第1,335行: 第1,162行:
 
<div id="default" class="section">
 
<div id="default" class="section">
  
=== default ===
+
=== 默认 ===
  
All optional arguments and some positional arguments may be omitted at the
+
在命令行中可以省略所有可选参数和一些位置参数。 [[#argparse.ArgumentParser.add_argument|add_argument()]] 的 <code>default</code> 关键字参数,其值默认为 <code>None</code>,指定在命令行参数不存在时应使用的值。 对于可选参数,当命令行中不存在选项字符串时,将使用 <code>default</code> 值:
command line. The <code>default</code> keyword argument of
 
[[#argparse.ArgumentParser.add_argument|<code>add_argument()</code>]], whose value defaults to <code>None</code>,
 
specifies what value should be used if the command-line argument is not present.
 
For optional arguments, the <code>default</code> value is used when the option string
 
was not present at the command line:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第1,348行: 第1,170行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; parser = argparse.ArgumentParser()
+
<syntaxhighlight lang="python3">>>> parser = argparse.ArgumentParser()
&gt;&gt;&gt; parser.add_argument('--foo', default=42)
+
>>> parser.add_argument('--foo', default=42)
&gt;&gt;&gt; parser.parse_args(['--foo', '2'])
+
>>> parser.parse_args(['--foo', '2'])
 
Namespace(foo='2')
 
Namespace(foo='2')
&gt;&gt;&gt; parser.parse_args([])
+
>>> parser.parse_args([])
Namespace(foo=42)</pre>
+
Namespace(foo=42)</syntaxhighlight>
 +
 
 +
</div>
 +
 
 +
</div>
 +
如果目标命名空间已经有一个属性集,动作 ''default'' 不会覆盖它:
 +
 
 +
<div class="highlight-python3 notranslate">
 +
 
 +
<div class="highlight">
 +
 
 +
<syntaxhighlight lang="python3">>>> parser = argparse.ArgumentParser()
 +
>>> parser.add_argument('--foo', default=42)
 +
>>> parser.parse_args([], namespace=argparse.Namespace(foo=101))
 +
Namespace(foo=101)</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
If the <code>default</code> value is a string, the parser parses the value as if it
+
如果 <code>default</code> 值是一个字符串,解析器将解析该值,就好像它是一个命令行参数一样。 特别是,解析器在设置 [[#argparse.Namespace|Namespace]] 返回值的属性之前应用任何 [[#type|type]] 转换参数(如果提供)。 否则,解析器按原样使用该值:
were a command-line argument. In particular, the parser applies any [[#type|type]]
 
conversion argument, if provided, before setting the attribute on the
 
[[#argparse.Namespace|<code>Namespace</code>]] return value. Otherwise, the parser uses the value as is:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第1,367行: 第1,200行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; parser = argparse.ArgumentParser()
+
<syntaxhighlight lang="python3">>>> parser = argparse.ArgumentParser()
&gt;&gt;&gt; parser.add_argument('--length', default='10', type=int)
+
>>> parser.add_argument('--length', default='10', type=int)
&gt;&gt;&gt; parser.add_argument('--width', default=10.5, type=int)
+
>>> parser.add_argument('--width', default=10.5, type=int)
&gt;&gt;&gt; parser.parse_args()
+
>>> parser.parse_args()
Namespace(length=10, width=10.5)</pre>
+
Namespace(length=10, width=10.5)</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
For positional arguments with [[#nargs|nargs]] equal to <code>?</code> or <code>*</code>, the <code>default</code> value
+
对于 [[#nargs|nargs]] 等于 <code>?</code> <code>*</code> 的位置参数,当不存在命令行参数时使用 <code>default</code> 值:
is used when no command-line argument was present:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第1,383行: 第1,215行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; parser = argparse.ArgumentParser()
+
<syntaxhighlight lang="python3">>>> parser = argparse.ArgumentParser()
&gt;&gt;&gt; parser.add_argument('foo', nargs='?', default=42)
+
>>> parser.add_argument('foo', nargs='?', default=42)
&gt;&gt;&gt; parser.parse_args(['a'])
+
>>> parser.parse_args(['a'])
 
Namespace(foo='a')
 
Namespace(foo='a')
&gt;&gt;&gt; parser.parse_args([])
+
>>> parser.parse_args([])
Namespace(foo=42)</pre>
+
Namespace(foo=42)</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
Providing <code>default=argparse.SUPPRESS</code> causes no attribute to be added if the
+
如果命令行参数不存在,则提供 <code>default=argparse.SUPPRESS</code> 会导致不添加任何属性:
command-line argument was not present:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第1,400行: 第1,231行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; parser = argparse.ArgumentParser()
+
<syntaxhighlight lang="python3">>>> parser = argparse.ArgumentParser()
&gt;&gt;&gt; parser.add_argument('--foo', default=argparse.SUPPRESS)
+
>>> parser.add_argument('--foo', default=argparse.SUPPRESS)
&gt;&gt;&gt; parser.parse_args([])
+
>>> parser.parse_args([])
 
Namespace()
 
Namespace()
&gt;&gt;&gt; parser.parse_args(['--foo', '1'])
+
>>> parser.parse_args(['--foo', '1'])
Namespace(foo='1')</pre>
+
Namespace(foo='1')</syntaxhighlight>
  
 
</div>
 
</div>
第1,414行: 第1,245行:
 
<div id="type" class="section">
 
<div id="type" class="section">
  
=== type ===
+
=== 类型 ===
 
 
By default, [[#argparse.ArgumentParser|<code>ArgumentParser</code>]] 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 [[../functions#float|<code>float</code>]] or [[../functions#int|<code>int</code>]]. The
 
<code>type</code> keyword argument of [[#argparse.ArgumentParser.add_argument|<code>add_argument()</code>]] 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 <code>type</code> argument:
 
 
 
<div class="highlight-python3 notranslate">
 
 
 
<div class="highlight">
 
  
<pre>&gt;&gt;&gt; parser = argparse.ArgumentParser()
+
默认情况下,解析器以简单字符串的形式读取命令行参数。 但是,命令行字符串通常应该被解释为另一种类型,例如 [[../functions#float|float]] 或 [[../functions#int|int]]。 [[#argparse.ArgumentParser.add_argument|add_argument()]] 的 <code>type</code> 关键字允许执行任何必要的类型检查和类型转换。
&gt;&gt;&gt; parser.add_argument('foo', type=int)
 
&gt;&gt;&gt; parser.add_argument('bar', type=open)
 
&gt;&gt;&gt; parser.parse_args('2 temp.txt'.split())
 
Namespace(bar=&lt;_io.TextIOWrapper name='temp.txt' encoding='UTF-8'&gt;, foo=2)</pre>
 
  
</div>
+
如果 [[#type|type]] 关键字与 [[#default|default]] 关键字一起使用,则仅当默认值为字符串时才应用类型转换器。
  
</div>
+
<code>type</code> 的参数可以是任何接受单个字符串的可调用对象。 如果函数引发 <code>ArgumentTypeError</code>、[[../exceptions#TypeError|TypeError]] 或 [[../exceptions#ValueError|ValueError]],则会捕获异常并显示格式良好的错误消息。 不处理其他异常类型。
See the section on the [[#default|default]] keyword argument for information on when the
 
<code>type</code> 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 <code>mode=</code>, <code>bufsize=</code>, <code>encoding=</code> and
 
<code>errors=</code> arguments of the [[../functions#open|<code>open()</code>]] function. For example,
 
<code>FileType('w')</code> can be used to create a writable file:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第1,448行: 第1,259行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; parser = argparse.ArgumentParser()
+
<syntaxhighlight lang="python3">import argparse
&gt;&gt;&gt; parser.add_argument('bar', type=argparse.FileType('w'))
+
import pathlib
&gt;&gt;&gt; parser.parse_args(['out.txt'])
+
 
Namespace(bar=&lt;_io.TextIOWrapper name='out.txt' encoding='UTF-8'&gt;)</pre>
+
parser = argparse.ArgumentParser()
 +
parser.add_argument('count', type=int)
 +
parser.add_argument('distance', type=float)
 +
parser.add_argument('street', type=ascii)
 +
parser.add_argument('code_point', type=ord)
 +
parser.add_argument('source_file', type=open)
 +
parser.add_argument('dest_file', type=argparse.FileType('w', encoding='latin-1'))
 +
parser.add_argument('datapath', type=pathlib.Path)</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
<code>type=</code> can take any callable that takes a single string argument and returns
+
也可以使用用户定义的函数:
the converted value:
 
  
<div class="highlight-python3 notranslate">
+
<div class="highlight-pycon3 notranslate">
  
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; def perfect_square(string):
+
<pre class="pycon3">&gt;&gt;&gt; def hyphenated(string):
...    value = int(string)
+
...    return '-'.join([word[:4] for word in string.casefold().split()])
...    sqrt = math.sqrt(value)
 
...     if sqrt != int(sqrt):
 
...        msg = &quot;%r is not a perfect square&quot; % string
 
...        raise argparse.ArgumentTypeError(msg)
 
...    return value
 
 
...
 
...
&gt;&gt;&gt; parser = argparse.ArgumentParser(prog='PROG')
+
&gt;&gt;&gt; parser = argparse.ArgumentParser()
&gt;&gt;&gt; parser.add_argument('foo', type=perfect_square)
+
&gt;&gt;&gt; _ = parser.add_argument('short_title', type=hyphenated)
&gt;&gt;&gt; parser.parse_args(['9'])
+
&gt;&gt;&gt; parser.parse_args(['&quot;The Tale of Two Cities&quot;'])
Namespace(foo=9)
+
Namespace(short_title='&quot;the-tale-of-two-citi')</pre>
&gt;&gt;&gt; parser.parse_args(['7'])
 
usage: PROG [-h] foo
 
PROG: error: argument foo: '7' is not a perfect square</pre>
 
  
 
</div>
 
</div>
  
 
</div>
 
</div>
The [[#choices|choices]] keyword argument may be more convenient for type checkers that
+
[[../functions#bool|bool()]] 函数不推荐作为类型转换器。 它所做的只是将空字符串转换为 <code>False</code>,将非空字符串转换为 <code>True</code>。 这通常不是所希望的。
simply check against a range of values:
 
 
 
<div class="highlight-python3 notranslate">
 
  
<div class="highlight">
+
通常,<code>type</code> 关键字是一种便利,应该仅用于只能引发三种受支持异常之一的简单转换。 在解析参数后,任何更有趣的错误处理或资源管理都应该在下游完成。
  
<pre>&gt;&gt;&gt; parser = argparse.ArgumentParser(prog='PROG')
+
例如,JSON 或 YAML 转换具有复杂的错误情况,需要比 <code>type</code> 关键字提供更好的报告。 [[../json#json|JSONDecodeError]] 的格式不会很好,并且根本不会处理 <code>FileNotFound</code> 异常。
&gt;&gt;&gt; parser.add_argument('foo', type=int, choices=range(5, 10))
 
&gt;&gt;&gt; parser.parse_args(['7'])
 
Namespace(foo=7)
 
&gt;&gt;&gt; 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)</pre>
 
  
</div>
+
甚至 [[#argparse.FileType|FileType]] 也有其与 <code>type</code> 关键字一起使用的限制。 如果一个参数使用 ''FileType'' 并且随后的参数失败,则会报告错误但不会自动关闭文件。 在这种情况下,最好等到解析器运行后,然后使用 [[../../reference/compound_stmts#with|with]] 语句来管理文件。
  
</div>
+
对于仅针对一组固定值进行检查的类型检查器,请考虑改用 [[#choices|choices]] 关键字。
See the [[#choices|choices]] section for more details.
 
  
  
第1,506行: 第1,305行:
 
<div id="choices" class="section">
 
<div id="choices" class="section">
  
=== choices ===
+
=== 选择 ===
  
Some command-line arguments should be selected from a restricted set of values.
+
一些命令行参数应该从一组受限制的值中选择。 这些可以通过将容器对象作为 ''choices'' 关键字参数传递给 [[#argparse.ArgumentParser.add_argument|add_argument()]] 来处理。 解析命令行时,将检查参数值,如果参数不是可接受的值之一,则会显示错误消息:
These can be handled by passing a container object as the ''choices'' keyword
 
argument to [[#argparse.ArgumentParser.add_argument|<code>add_argument()</code>]]. 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:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第1,518行: 第1,313行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; parser = argparse.ArgumentParser(prog='game.py')
+
<syntaxhighlight lang="python3">>>> parser = argparse.ArgumentParser(prog='game.py')
&gt;&gt;&gt; parser.add_argument('move', choices=['rock', 'paper', 'scissors'])
+
>>> parser.add_argument('move', choices=['rock', 'paper', 'scissors'])
&gt;&gt;&gt; parser.parse_args(['rock'])
+
>>> parser.parse_args(['rock'])
 
Namespace(move='rock')
 
Namespace(move='rock')
&gt;&gt;&gt; parser.parse_args(['fire'])
+
>>> parser.parse_args(['fire'])
 
usage: game.py [-h] {rock,paper,scissors}
 
usage: game.py [-h] {rock,paper,scissors}
 
game.py: error: argument move: invalid choice: 'fire' (choose from 'rock',
 
game.py: error: argument move: invalid choice: 'fire' (choose from 'rock',
'paper', 'scissors')</pre>
+
'paper', 'scissors')</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
Note that inclusion in the ''choices'' container is checked after any [[#type|type]]
+
请注意,在执行任何 [[#type|type]] 转换后检查是否包含在 ''choices'' 容器中,因此 ''choices'' 容器中的对象类型应与 [[#type|匹配]type]] 指定:
conversions have been performed, so the type of the objects in the ''choices''
 
container should match the [[#type|type]] specified:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第1,538行: 第1,331行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; parser = argparse.ArgumentParser(prog='doors.py')
+
<syntaxhighlight lang="python3">>>> parser = argparse.ArgumentParser(prog='doors.py')
&gt;&gt;&gt; parser.add_argument('door', type=int, choices=range(1, 4))
+
>>> parser.add_argument('door', type=int, choices=range(1, 4))
&gt;&gt;&gt; print(parser.parse_args(['3']))
+
>>> print(parser.parse_args(['3']))
 
Namespace(door=3)
 
Namespace(door=3)
&gt;&gt;&gt; parser.parse_args(['4'])
+
>>> parser.parse_args(['4'])
 
usage: doors.py [-h] {1,2,3}
 
usage: doors.py [-h] {1,2,3}
doors.py: error: argument door: invalid choice: 4 (choose from 1, 2, 3)</pre>
+
doors.py: error: argument door: invalid choice: 4 (choose from 1, 2, 3)</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
Any container can be passed as the ''choices'' value, so [[../stdtypes#list|<code>list</code>]] objects,
+
任何容器都可以作为 ''choices'' 值传递,所以 [[../stdtypes#list|list]] 对象、[[../stdtypes#set|set]] 对象和自定义容器都被支持。
[[../stdtypes#set|<code>set</code>]] objects, and custom containers are all supported.
 
  
Use of [[../enum#enum|<code>enum.Enum</code>]] is not recommended because it is difficult to
+
不推荐使用 [[../enum#enum|enum.Enum]],因为它很难控制它在使用、帮助和错误消息中的外观。
control its appearance in usage, help, and error messages.
+
 
 +
格式化选项会覆盖默认的 ''metavar'',它通常派生自 ''dest''。 这通常是您想要的,因为用户永远不会看到 ''dest'' 参数。 如果这种显示不是可取的(可能是因为有很多选择),只需指定一个明确的 [[#metavar|metavar]]。
  
  
第1,559行: 第1,352行:
 
<div id="required" class="section">
 
<div id="required" class="section">
  
=== required ===
+
=== 必需的 ===
  
In general, the [[#module-argparse|<code>argparse</code>]] module assumes that flags like <code>-f</code> and <code>--bar</code>
+
通常,[[#module-argparse|argparse]] 模块假设像 <code>-f</code> <code>--bar</code> 表示 ''optional'' 参数,这些参数在命令行中总是可以省略的。 要使选项 ''required'',可以为 [[#argparse.ArgumentParser.add_argument|add_argument()]] 的 <code>required=</code> 关键字参数指定 <code>True</code>
indicate ''optional'' arguments, which can always be omitted at the command line.
 
To make an option ''required'', <code>True</code> can be specified for the <code>required=</code>
 
keyword argument to [[#argparse.ArgumentParser.add_argument|<code>add_argument()</code>]]:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第1,570行: 第1,360行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; parser = argparse.ArgumentParser()
+
<syntaxhighlight lang="python3">>>> parser = argparse.ArgumentParser()
&gt;&gt;&gt; parser.add_argument('--foo', required=True)
+
>>> parser.add_argument('--foo', required=True)
&gt;&gt;&gt; parser.parse_args(['--foo', 'BAR'])
+
>>> parser.parse_args(['--foo', 'BAR'])
 
Namespace(foo='BAR')
 
Namespace(foo='BAR')
&gt;&gt;&gt; parser.parse_args([])
+
>>> parser.parse_args([])
 
usage: [-h] --foo FOO
 
usage: [-h] --foo FOO
: error: the following arguments are required: --foo</pre>
+
: error: the following arguments are required: --foo</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
As the example shows, if an option is marked as <code>required</code>,
+
如示例所示,如果一个选项被标记为 <code>required</code>,如果命令行中不存在该选项,则 [[#argparse.ArgumentParser.parse_args|parse_args()]] 将报告错误。
[[#argparse.ArgumentParser.parse_args|<code>parse_args()</code>]] will report an error if that option is not
 
present at the command line.
 
  
 
<div class="admonition note">
 
<div class="admonition note">
  
注解
+
笔记
  
Required options are generally considered bad form because users expect
+
必需的选项通常被认为是不好的形式,因为用户希望 ''options'' ''optional'',因此应该尽可能避免它们。
''options'' to be ''optional'', and thus they should be avoided when possible.
 
  
  
第1,598行: 第1,385行:
 
<div id="help" class="section">
 
<div id="help" class="section">
  
=== help ===
+
=== 帮助 ===
  
The <code>help</code> value is a string containing a brief description of the argument.
+
<code>help</code> 值是一个包含参数简要描述的字符串。 当用户请求帮助时(通常通过在命令行使用 <code>-h</code> <code>--help</code>),这些 <code>help</code> 描述将与每个参数一起显示:
When a user requests help (usually by using <code>-h</code> or <code>--help</code> at the
 
command line), these <code>help</code> descriptions will be displayed with each
 
argument:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第1,609行: 第1,393行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; parser = argparse.ArgumentParser(prog='frobble')
+
<syntaxhighlight lang="python3">>>> parser = argparse.ArgumentParser(prog='frobble')
&gt;&gt;&gt; parser.add_argument('--foo', action='store_true',
+
>>> parser.add_argument('--foo', action='store_true',
 
...                    help='foo the bars before frobbling')
 
...                    help='foo the bars before frobbling')
&gt;&gt;&gt; parser.add_argument('bar', nargs='+',
+
>>> parser.add_argument('bar', nargs='+',
 
...                    help='one of the bars to be frobbled')
 
...                    help='one of the bars to be frobbled')
&gt;&gt;&gt; parser.parse_args(['-h'])
+
>>> parser.parse_args(['-h'])
 
usage: frobble [-h] [--foo] bar [bar ...]
 
usage: frobble [-h] [--foo] bar [bar ...]
  
第1,622行: 第1,406行:
 
optional arguments:
 
optional arguments:
 
  -h, --help  show this help message and exit
 
  -h, --help  show this help message and exit
  --foo  foo the bars before frobbling</pre>
+
  --foo  foo the bars before frobbling</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
The <code>help</code> strings can include various format specifiers to avoid repetition
+
<code>help</code> 字符串可以包含各种格式说明符,以避免重复诸如程序名称或参数 [[#default|default]] 之类的内容。 可用的说明符包括程序名称、<code>%(prog)s</code> [[#argparse.ArgumentParser.add_argument|add_argument()]] 的大多数关键字参数,例如 <code>%(default)s</code><code>%(type)s</code> 等:
of things like the program name or the argument [[#default|default]]. The available
 
specifiers include the program name, <code>%(prog)s</code> and most keyword arguments to
 
[[#argparse.ArgumentParser.add_argument|<code>add_argument()</code>]], e.g. <code>%(default)s</code>, <code>%(type)s</code>, etc.:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第1,636行: 第1,417行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; parser = argparse.ArgumentParser(prog='frobble')
+
<syntaxhighlight lang="python3">>>> parser = argparse.ArgumentParser(prog='frobble')
&gt;&gt;&gt; parser.add_argument('bar', nargs='?', type=int, default=42,
+
>>> parser.add_argument('bar', nargs='?', type=int, default=42,
 
...                    help='the bar to %(prog)s (default: %(default)s)')
 
...                    help='the bar to %(prog)s (default: %(default)s)')
&gt;&gt;&gt; parser.print_help()
+
>>> parser.print_help()
 
usage: frobble [-h] [bar]
 
usage: frobble [-h] [bar]
  
第1,646行: 第1,427行:
  
 
optional arguments:
 
optional arguments:
  -h, --help  show this help message and exit</pre>
+
  -h, --help  show this help message and exit</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
As the help string supports %-formatting, if you want a literal <code>%</code> to appear
+
由于帮助字符串支持 %-f 格式,如果您希望文字 <code>%</code> 出现在帮助字符串中,则必须将其转义为 <code>%%</code>
in the help string, you must escape it as <code>%%</code>.
 
  
[[#module-argparse|<code>argparse</code>]] supports silencing the help entry for certain options, by
+
[[#module-argparse|argparse]] 通过将 <code>help</code> 值设置为 <code>argparse.SUPPRESS</code> 来支持使某些选项的帮助条目静音:
setting the <code>help</code> value to <code>argparse.SUPPRESS</code>:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第1,661行: 第1,440行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; parser = argparse.ArgumentParser(prog='frobble')
+
<syntaxhighlight lang="python3">>>> parser = argparse.ArgumentParser(prog='frobble')
&gt;&gt;&gt; parser.add_argument('--foo', help=argparse.SUPPRESS)
+
>>> parser.add_argument('--foo', help=argparse.SUPPRESS)
&gt;&gt;&gt; parser.print_help()
+
>>> parser.print_help()
 
usage: frobble [-h]
 
usage: frobble [-h]
  
 
optional arguments:
 
optional arguments:
   -h, --help  show this help message and exit</pre>
+
   -h, --help  show this help message and exit</syntaxhighlight>
  
 
</div>
 
</div>
第1,676行: 第1,455行:
 
<div id="metavar" class="section">
 
<div id="metavar" class="section">
  
=== metavar ===
+
=== 元变量 ===
  
When [[#argparse.ArgumentParser|<code>ArgumentParser</code>]] generates help messages, it needs some way to refer
+
[[#argparse.ArgumentParser|ArgumentParser]] 生成帮助消息时,它需要某种方式来引用每个预期的参数。 默认情况下,ArgumentParser 对象使用 [[#dest|dest]] 值作为每个对象的“名称”。 默认情况下,对于位置参数动作,直接使用 [[#dest|dest]] 值,对于可选参数动作,[[#dest|dest]] 值是大写的。 因此,带有 <code>dest='bar'</code> 的单个位置参数将被称为 <code>bar</code>。 单个可选参数 <code>--foo</code> 后面应该跟一个命令行参数将被称为 <code>FOO</code>。 一个例子:
to each expected argument. By default, ArgumentParser objects use the [[#dest|dest]]
 
value as the &quot;name&quot; 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
 
<code>dest='bar'</code> will be referred to as <code>bar</code>. A single
 
optional argument <code>--foo</code> that should be followed by a single command-line argument
 
will be referred to as <code>FOO</code>. An example:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第1,691行: 第1,463行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; parser = argparse.ArgumentParser()
+
<syntaxhighlight lang="python3">>>> parser = argparse.ArgumentParser()
&gt;&gt;&gt; parser.add_argument('--foo')
+
>>> parser.add_argument('--foo')
&gt;&gt;&gt; parser.add_argument('bar')
+
>>> parser.add_argument('bar')
&gt;&gt;&gt; parser.parse_args('X --foo Y'.split())
+
>>> parser.parse_args('X --foo Y'.split())
 
Namespace(bar='X', foo='Y')
 
Namespace(bar='X', foo='Y')
&gt;&gt;&gt; parser.print_help()
+
>>> parser.print_help()
 
usage:  [-h] [--foo FOO] bar
 
usage:  [-h] [--foo FOO] bar
  
第1,704行: 第1,476行:
 
optional arguments:
 
optional arguments:
 
  -h, --help  show this help message and exit
 
  -h, --help  show this help message and exit
  --foo FOO</pre>
+
  --foo FOO</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
An alternative name can be specified with <code>metavar</code>:
+
可以使用 <code>metavar</code> 指定替代名称:
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第1,715行: 第1,487行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; parser = argparse.ArgumentParser()
+
<syntaxhighlight lang="python3">>>> parser = argparse.ArgumentParser()
&gt;&gt;&gt; parser.add_argument('--foo', metavar='YYY')
+
>>> parser.add_argument('--foo', metavar='YYY')
&gt;&gt;&gt; parser.add_argument('bar', metavar='XXX')
+
>>> parser.add_argument('bar', metavar='XXX')
&gt;&gt;&gt; parser.parse_args('X --foo Y'.split())
+
>>> parser.parse_args('X --foo Y'.split())
 
Namespace(bar='X', foo='Y')
 
Namespace(bar='X', foo='Y')
&gt;&gt;&gt; parser.print_help()
+
>>> parser.print_help()
 
usage:  [-h] [--foo YYY] XXX
 
usage:  [-h] [--foo YYY] XXX
  
第1,728行: 第1,500行:
 
optional arguments:
 
optional arguments:
 
  -h, --help  show this help message and exit
 
  -h, --help  show this help message and exit
  --foo YYY</pre>
+
  --foo YYY</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
Note that <code>metavar</code> only changes the ''displayed'' name - the name of the
+
请注意,<code>metavar</code> 仅更改 ''displayed'' 名称 - [[#argparse.ArgumentParser.parse_args|parse_args()]] 对象上的属性名称仍由 [[#dest|dest]] 值决定.
attribute on the [[#argparse.ArgumentParser.parse_args|<code>parse_args()</code>]] object is still determined
 
by the [[#dest|dest]] value.
 
  
Different values of <code>nargs</code> may cause the metavar to be used multiple times.
+
<code>nargs</code> 的不同值可能会导致元变量被多次使用。 为 <code>metavar</code> 提供一个元组为每个参数指定不同的显示:
Providing a tuple to <code>metavar</code> specifies a different display for each of the
 
arguments:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第1,745行: 第1,513行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; parser = argparse.ArgumentParser(prog='PROG')
+
<syntaxhighlight lang="python3">>>> parser = argparse.ArgumentParser(prog='PROG')
&gt;&gt;&gt; parser.add_argument('-x', nargs=2)
+
>>> parser.add_argument('-x', nargs=2)
&gt;&gt;&gt; parser.add_argument('--foo', nargs=2, metavar=('bar', 'baz'))
+
>>> parser.add_argument('--foo', nargs=2, metavar=('bar', 'baz'))
&gt;&gt;&gt; parser.print_help()
+
>>> parser.print_help()
 
usage: PROG [-h] [-x X X] [--foo bar baz]
 
usage: PROG [-h] [-x X X] [--foo bar baz]
  
第1,754行: 第1,522行:
 
  -h, --help    show this help message and exit
 
  -h, --help    show this help message and exit
 
  -x X X
 
  -x X X
  --foo bar baz</pre>
+
  --foo bar baz</syntaxhighlight>
  
 
</div>
 
</div>
第1,763行: 第1,531行:
 
<div id="dest" class="section">
 
<div id="dest" class="section">
  
=== dest ===
+
=== 目的地 ===
  
Most [[#argparse.ArgumentParser|<code>ArgumentParser</code>]] actions add some value as an attribute of the
+
大多数 [[#argparse.ArgumentParser|ArgumentParser]] 操作添加一些值作为 [[#argparse.ArgumentParser.parse_args|parse_args()]] 返回的对象的属性。 该属性的名称由 [[#argparse.ArgumentParser.add_argument|add_argument()]] 的 <code>dest</code> 关键字参数决定。 对于位置参数操作,<code>dest</code> 通常作为第一个参数提供给 [[#argparse.ArgumentParser.add_argument|add_argument()]]
object returned by [[#argparse.ArgumentParser.parse_args|<code>parse_args()</code>]]. The name of this
 
attribute is determined by the <code>dest</code> keyword argument of
 
[[#argparse.ArgumentParser.add_argument|<code>add_argument()</code>]]. For positional argument actions,
 
<code>dest</code> is normally supplied as the first argument to
 
[[#argparse.ArgumentParser.add_argument|<code>add_argument()</code>]]:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第1,776行: 第1,539行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; parser = argparse.ArgumentParser()
+
<syntaxhighlight lang="python3">>>> parser = argparse.ArgumentParser()
&gt;&gt;&gt; parser.add_argument('bar')
+
>>> parser.add_argument('bar')
&gt;&gt;&gt; parser.parse_args(['XXX'])
+
>>> parser.parse_args(['XXX'])
Namespace(bar='XXX')</pre>
+
Namespace(bar='XXX')</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
For optional argument actions, the value of <code>dest</code> is normally inferred from
+
对于可选参数操作,<code>dest</code> 的值通常是从选项字符串中推断出来的。 [[#argparse.ArgumentParser|ArgumentParser]] 通过取第一个长选项字符串并剥离初始 <code>--</code> 字符串来生成 <code>dest</code> 的值。 如果未提供长选项字符串,则 <code>dest</code> 将通过剥离初始 <code>-</code> 字符从第一个短选项字符串派生。 任何内部 <code>-</code> 字符都将转换为 <code>_</code> 字符以确保字符串是有效的属性名称。 下面的示例说明了这种行为:
the option strings. [[#argparse.ArgumentParser|<code>ArgumentParser</code>]] generates the value of <code>dest</code> by
 
taking the first long option string and stripping away the initial <code>--</code>
 
string. If no long option strings were supplied, <code>dest</code> will be derived from
 
the first short option string by stripping the initial <code>-</code> character. Any
 
internal <code>-</code> characters will be converted to <code>_</code> characters to make sure
 
the string is a valid attribute name. The examples below illustrate this
 
behavior:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第1,797行: 第1,553行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; parser = argparse.ArgumentParser()
+
<syntaxhighlight lang="python3">>>> parser = argparse.ArgumentParser()
&gt;&gt;&gt; parser.add_argument('-f', '--foo-bar', '--foo')
+
>>> parser.add_argument('-f', '--foo-bar', '--foo')
&gt;&gt;&gt; parser.add_argument('-x', '-y')
+
>>> parser.add_argument('-x', '-y')
&gt;&gt;&gt; parser.parse_args('-f 1 -x 2'.split())
+
>>> parser.parse_args('-f 1 -x 2'.split())
 
Namespace(foo_bar='1', x='2')
 
Namespace(foo_bar='1', x='2')
&gt;&gt;&gt; parser.parse_args('--foo 1 -y 2'.split())
+
>>> parser.parse_args('--foo 1 -y 2'.split())
Namespace(foo_bar='1', x='2')</pre>
+
Namespace(foo_bar='1', x='2')</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
<code>dest</code> allows a custom attribute name to be provided:
+
<code>dest</code> 允许提供自定义属性名称:
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第1,814行: 第1,570行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; parser = argparse.ArgumentParser()
+
<syntaxhighlight lang="python3">>>> parser = argparse.ArgumentParser()
&gt;&gt;&gt; parser.add_argument('--foo', dest='bar')
+
>>> parser.add_argument('--foo', dest='bar')
&gt;&gt;&gt; parser.parse_args('--foo XXX'.split())
+
>>> parser.parse_args('--foo XXX'.split())
Namespace(bar='XXX')</pre>
+
Namespace(bar='XXX')</syntaxhighlight>
  
 
</div>
 
</div>
第1,826行: 第1,582行:
 
<div id="action-classes" class="section">
 
<div id="action-classes" class="section">
  
=== Action classes ===
+
=== 动作类 ===
  
Action classes implement the Action API, a callable which returns a callable
+
Action 类实现了 Action API,这是一个可调用的,它返回一个可调用的,它处理来自命令行的参数。 任何遵循此 API 的对象都可以作为 <code>action</code> 参数传递给 <code>add_argument()</code>
which processes arguments from the command-line. Any object which follows
 
this API may be passed as the <code>action</code> parameter to
 
<code>add_argument()</code>.
 
  
; ''class'' <code>argparse.</code><code>Action</code><span class="sig-paren">(</span>''<span class="n">option_strings</span>'', ''<span class="n">dest</span>'', ''<span class="n">nargs</span><span class="o">=</span><span class="default_value">None</span>'', ''<span class="n">const</span><span class="o">=</span><span class="default_value">None</span>'', ''<span class="n">default</span><span class="o">=</span><span class="default_value">None</span>'', ''<span class="n">type</span><span class="o">=</span><span class="default_value">None</span>'', ''<span class="n">choices</span><span class="o">=</span><span class="default_value">None</span>'', ''<span class="n">required</span><span class="o">=</span><span class="default_value">False</span>'', ''<span class="n">help</span><span class="o">=</span><span class="default_value">None</span>'', ''<span class="n">metavar</span><span class="o">=</span><span class="default_value">None</span>''<span class="sig-paren">)</span>
+
; ''<span class="pre">class</span>'' <span class="sig-prename descclassname"><span class="pre">argparse.</span></span><span class="sig-name descname"><span class="pre">Action</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">option_strings</span></span>'', ''<span class="n"><span class="pre">dest</span></span>'', ''<span class="n"><span class="pre">nargs</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>'', ''<span class="n"><span class="pre">const</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>'', ''<span class="n"><span class="pre">default</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>'', ''<span class="n"><span class="pre">type</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>'', ''<span class="n"><span class="pre">choices</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>'', ''<span class="n"><span class="pre">required</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">False</span></span>'', ''<span class="n"><span class="pre">help</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>'', ''<span class="n"><span class="pre">metavar</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>''<span class="sig-paren">)</span>
 
:  
 
:  
  
Action objects are used by an ArgumentParser to represent the information
+
ArgumentParser 使用 Action 对象来表示从命令行中的一个或多个字符串解析单个参数所需的信息。 Action 类必须接受两个位置参数以及传递给 [[#argparse.ArgumentParser.add_argument|ArgumentParser.add_argument()]] 的任何关键字参数,除了 <code>action</code> 本身。
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 [[#argparse.ArgumentParser.add_argument|<code>ArgumentParser.add_argument()</code>]]
 
except for the <code>action</code> itself.
 
  
Instances of Action (or return value of any callable to the <code>action</code>
+
Action 实例(或任何可调用 <code>action</code> 参数的返回值)应具有属性“dest”、“option_strings”、“default”、“type”、“required”、“help”等。 定义。 确保定义这些属性的最简单方法是调用 <code>Action.__init__</code>
parameter) should have attributes &quot;dest&quot;, &quot;option_strings&quot;, &quot;default&quot;, &quot;type&quot;,
 
&quot;required&quot;, &quot;help&quot;, etc. defined. The easiest way to ensure these attributes
 
are defined is to call <code>Action.__init__</code>.
 
  
Action instances should be callable, so subclasses must override the
+
Action 实例应该是可调用的,因此子类必须覆盖 <code>__call__</code> 方法,该方法应该接受四个参数:
<code>__call__</code> method, which should accept four parameters:
 
  
* <code>parser</code> - The ArgumentParser object which contains this action.
+
* <code>parser</code> - 包含此操作的 ArgumentParser 对象。
* <code>namespace</code> - The [[#argparse.Namespace|<code>Namespace</code>]] object that will be returned by [[#argparse.ArgumentParser.parse_args|<code>parse_args()</code>]]. Most actions add an attribute to this object using [[../functions#setattr|<code>setattr()</code>]].
+
* <code>namespace</code> - [[#argparse.ArgumentParser.parse_args|parse_args()]] 将返回的 [[#argparse.Namespace|Namespace]] 对象。 大多数操作使用 [[../functions#setattr|setattr()]] 向该对象添加属性。
* <code>values</code> - The associated command-line arguments, with any type conversions applied. Type conversions are specified with the [[#type|type]] keyword argument to [[#argparse.ArgumentParser.add_argument|<code>add_argument()</code>]].
+
* <code>values</code> - 关联的命令行参数,应用了任何类型转换。 类型转换使用 [[#argparse.ArgumentParser.add_argument|add_argument()]] 的 [[#type|type]] 关键字参数指定。
* <code>option_string</code> - The option string that was used to invoke this action. The <code>option_string</code> argument is optional, and will be absent if the action is associated with a positional argument.
+
* <code>option_string</code> - 用于调用此操作的选项字符串。 <code>option_string</code> 参数是可选的,如果操作与位置参数相关联,则该参数将不存在。
  
The <code>__call__</code> method may perform arbitrary actions, but will typically set
+
<code>__call__</code> 方法可以执行任意操作,但通常会根据 <code>dest</code> <code>values</code> <code>namespace</code> 上设置属性。
attributes on the <code>namespace</code> based on <code>dest</code> and <code>values</code>.
 
  
Action subclasses can define a <code>format_usage</code> method that takes no argument
+
Action 子类可以定义一个 <code>format_usage</code> 方法,该方法不带参数并返回一个字符串,该字符串将在打印程序的用法时使用。 如果未提供此类方法,则将使用合理的默认值。
and return a string which will be used when printing the usage of the program.
 
If such method is not provided, a sensible default will be used.
 
  
  
第1,868行: 第1,610行:
 
<div id="the-parse-args-method" class="section">
 
<div id="the-parse-args-method" class="section">
  
== The parse_args() method ==
+
== parse_args() 方法 ==
  
 
<dl>
 
<dl>
<dt><code>ArgumentParser.</code><code>parse_args</code><span class="sig-paren">(</span>''<span class="n">args</span><span class="o">=</span><span class="default_value">None</span>'', ''<span class="n">namespace</span><span class="o">=</span><span class="default_value">None</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-prename descclassname"><span class="pre">ArgumentParser.</span></span><span class="sig-name descname"><span class="pre">parse_args</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">args</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>'', ''<span class="n"><span class="pre">namespace</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Convert argument strings to objects and assign them as attributes of the
+
<dd><p>将参数字符串转换为对象并将它们分配为命名空间的属性。 返回填充的命名空间。</p>
namespace. Return the populated namespace.</p>
+
<p>之前对 [[#argparse.ArgumentParser.add_argument|add_argument()]] 的调用确定了创建哪些对象以及如何分配它们。 有关详细信息,请参阅 [[#argparse.ArgumentParser.add_argument|add_argument()]] 的文档。</p>
<p>Previous calls to [[#argparse.ArgumentParser.add_argument|<code>add_argument()</code>]] determine exactly what objects are
 
created and how they are assigned. See the documentation for
 
[[#argparse.ArgumentParser.add_argument|<code>add_argument()</code>]] for details.</p>
 
 
<ul>
 
<ul>
<li><p>[[#args|args]] - List of strings to parse. The default is taken from
+
<li><p>[[#args|args]] - 要解析的字符串列表。 默认值取自 [[../sys#sys|sys.argv]]</p></li>
[[../sys#sys|<code>sys.argv</code>]].</p></li>
+
<li><p>[[#namespace|namespace]] - 获取属性的对象。 默认值是一个新的空 [[#argparse.Namespace|Namespace]] 对象。</p></li></ul>
<li><p>[[#namespace|namespace]] - An object to take the attributes. The default is a new empty
 
[[#argparse.Namespace|<code>Namespace</code>]] object.</p></li></ul>
 
 
</dd></dl>
 
</dd></dl>
  
 
<div id="option-value-syntax" class="section">
 
<div id="option-value-syntax" class="section">
  
=== Option value syntax ===
+
=== 选项值语法 ===
  
The [[#argparse.ArgumentParser.parse_args|<code>parse_args()</code>]] method supports several ways of
+
[[#argparse.ArgumentParser.parse_args|parse_args()]] 方法支持多种指定选项值的方法(如果需要的话)。 在最简单的情况下,选项及其值作为两个单独的参数传递:
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:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第1,896行: 第1,631行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; parser = argparse.ArgumentParser(prog='PROG')
+
<syntaxhighlight lang="python3">>>> parser = argparse.ArgumentParser(prog='PROG')
&gt;&gt;&gt; parser.add_argument('-x')
+
>>> parser.add_argument('-x')
&gt;&gt;&gt; parser.add_argument('--foo')
+
>>> parser.add_argument('--foo')
&gt;&gt;&gt; parser.parse_args(['-x', 'X'])
+
>>> parser.parse_args(['-x', 'X'])
 
Namespace(foo=None, x='X')
 
Namespace(foo=None, x='X')
&gt;&gt;&gt; parser.parse_args(['--foo', 'FOO'])
+
>>> parser.parse_args(['--foo', 'FOO'])
Namespace(foo='FOO', x=None)</pre>
+
Namespace(foo='FOO', x=None)</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
For long options (options with names longer than a single character), the option
+
对于长选项(名称长于单个字符的选项),选项和值也可以作为单个命令行参数传递,使用 <code>=</code> 将它们分开:
and value can also be passed as a single command-line argument, using <code>=</code> to
 
separate them:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第1,915行: 第1,648行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; parser.parse_args(['--foo=FOO'])
+
<syntaxhighlight lang="python3">>>> parser.parse_args(['--foo=FOO'])
Namespace(foo='FOO', x=None)</pre>
+
Namespace(foo='FOO', x=None)</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
For short options (options only one character long), the option and its value
+
对于短选项(选项只有一个字符长),可以连接选项及其值:
can be concatenated:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第1,928行: 第1,660行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; parser.parse_args(['-xX'])
+
<syntaxhighlight lang="python3">>>> parser.parse_args(['-xX'])
Namespace(foo=None, x='X')</pre>
+
Namespace(foo=None, x='X')</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
Several short options can be joined together, using only a single <code>-</code> prefix,
+
几个短选项可以连接在一起,只使用一个 <code>-</code> 前缀,只要最后一个选项(或没有一个)需要一个值:
as long as only the last option (or none of them) requires a value:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第1,941行: 第1,672行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; parser = argparse.ArgumentParser(prog='PROG')
+
<syntaxhighlight lang="python3">>>> parser = argparse.ArgumentParser(prog='PROG')
&gt;&gt;&gt; parser.add_argument('-x', action='store_true')
+
>>> parser.add_argument('-x', action='store_true')
&gt;&gt;&gt; parser.add_argument('-y', action='store_true')
+
>>> parser.add_argument('-y', action='store_true')
&gt;&gt;&gt; parser.add_argument('-z')
+
>>> parser.add_argument('-z')
&gt;&gt;&gt; parser.parse_args(['-xyzZ'])
+
>>> parser.parse_args(['-xyzZ'])
Namespace(x=True, y=True, z='Z')</pre>
+
Namespace(x=True, y=True, z='Z')</syntaxhighlight>
  
 
</div>
 
</div>
第1,955行: 第1,686行:
 
<div id="invalid-arguments" class="section">
 
<div id="invalid-arguments" class="section">
  
=== Invalid arguments ===
+
=== 无效参数 ===
  
While parsing the command line, [[#argparse.ArgumentParser.parse_args|<code>parse_args()</code>]] checks for a
+
在解析命令行时,[[#argparse.ArgumentParser.parse_args|parse_args()]] 会检查各种错误,包括歧义选项、无效类型、无效选项、位置参数数量错误等。 当它遇到这样的错误时,它会退出并打印错误以及使用信息:
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:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第1,966行: 第1,694行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; parser = argparse.ArgumentParser(prog='PROG')
+
<syntaxhighlight lang="python3">>>> parser = argparse.ArgumentParser(prog='PROG')
&gt;&gt;&gt; parser.add_argument('--foo', type=int)
+
>>> parser.add_argument('--foo', type=int)
&gt;&gt;&gt; parser.add_argument('bar', nargs='?')
+
>>> parser.add_argument('bar', nargs='?')
  
&gt;&gt;&gt; # invalid type
+
>>> # invalid type
&gt;&gt;&gt; parser.parse_args(['--foo', 'spam'])
+
>>> parser.parse_args(['--foo', 'spam'])
 
usage: PROG [-h] [--foo FOO] [bar]
 
usage: PROG [-h] [--foo FOO] [bar]
 
PROG: error: argument --foo: invalid int value: 'spam'
 
PROG: error: argument --foo: invalid int value: 'spam'
  
&gt;&gt;&gt; # invalid option
+
>>> # invalid option
&gt;&gt;&gt; parser.parse_args(['--bar'])
+
>>> parser.parse_args(['--bar'])
 
usage: PROG [-h] [--foo FOO] [bar]
 
usage: PROG [-h] [--foo FOO] [bar]
 
PROG: error: no such option: --bar
 
PROG: error: no such option: --bar
  
&gt;&gt;&gt; # wrong number of arguments
+
>>> # wrong number of arguments
&gt;&gt;&gt; parser.parse_args(['spam', 'badger'])
+
>>> parser.parse_args(['spam', 'badger'])
 
usage: PROG [-h] [--foo FOO] [bar]
 
usage: PROG [-h] [--foo FOO] [bar]
PROG: error: extra arguments found: badger</pre>
+
PROG: error: extra arguments found: badger</syntaxhighlight>
  
 
</div>
 
</div>
第1,992行: 第1,720行:
 
<div id="arguments-containing" class="section">
 
<div id="arguments-containing" class="section">
  
=== Arguments containing <code>-</code> ===
+
=== 包含 - 的参数 ===
  
The [[#argparse.ArgumentParser.parse_args|<code>parse_args()</code>]] method attempts to give errors whenever
+
[[#argparse.ArgumentParser.parse_args|parse_args()]] 方法试图在用户明显犯了错误时给出错误,但有些情况本质上是模棱两可的。 例如,命令行参数 <code>-1</code> 可能是尝试指定选项或尝试提供位置参数。 [[#argparse.ArgumentParser.parse_args|parse_args()]] 方法在这里是谨慎的:位置参数只能以 <code>-</code> 开头,如果它们看起来像负数并且解析器中没有看起来像负数的选项:
the user has clearly made a mistake, but some situations are inherently
 
ambiguous. For example, the command-line argument <code>-1</code> could either be an
 
attempt to specify an option or an attempt to provide a positional argument.
 
The [[#argparse.ArgumentParser.parse_args|<code>parse_args()</code>]] method is cautious here: positional
 
arguments may only begin with <code>-</code> if they look like negative numbers and
 
there are no options in the parser that look like negative numbers:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第2,006行: 第1,728行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; parser = argparse.ArgumentParser(prog='PROG')
+
<syntaxhighlight lang="python3">>>> parser = argparse.ArgumentParser(prog='PROG')
&gt;&gt;&gt; parser.add_argument('-x')
+
>>> parser.add_argument('-x')
&gt;&gt;&gt; parser.add_argument('foo', nargs='?')
+
>>> parser.add_argument('foo', nargs='?')
  
&gt;&gt;&gt; # no negative number options, so -1 is a positional argument
+
>>> # no negative number options, so -1 is a positional argument
&gt;&gt;&gt; parser.parse_args(['-x', '-1'])
+
>>> parser.parse_args(['-x', '-1'])
 
Namespace(foo=None, x='-1')
 
Namespace(foo=None, x='-1')
  
&gt;&gt;&gt; # no negative number options, so -1 and -5 are positional arguments
+
>>> # no negative number options, so -1 and -5 are positional arguments
&gt;&gt;&gt; parser.parse_args(['-x', '-1', '-5'])
+
>>> parser.parse_args(['-x', '-1', '-5'])
 
Namespace(foo='-5', x='-1')
 
Namespace(foo='-5', x='-1')
  
&gt;&gt;&gt; parser = argparse.ArgumentParser(prog='PROG')
+
>>> parser = argparse.ArgumentParser(prog='PROG')
&gt;&gt;&gt; parser.add_argument('-1', dest='one')
+
>>> parser.add_argument('-1', dest='one')
&gt;&gt;&gt; parser.add_argument('foo', nargs='?')
+
>>> parser.add_argument('foo', nargs='?')
  
&gt;&gt;&gt; # negative number options present, so -1 is an option
+
>>> # negative number options present, so -1 is an option
&gt;&gt;&gt; parser.parse_args(['-1', 'X'])
+
>>> parser.parse_args(['-1', 'X'])
 
Namespace(foo=None, one='X')
 
Namespace(foo=None, one='X')
  
&gt;&gt;&gt; # negative number options present, so -2 is an option
+
>>> # negative number options present, so -2 is an option
&gt;&gt;&gt; parser.parse_args(['-2'])
+
>>> parser.parse_args(['-2'])
 
usage: PROG [-h] [-1 ONE] [foo]
 
usage: PROG [-h] [-1 ONE] [foo]
 
PROG: error: no such option: -2
 
PROG: error: no such option: -2
  
&gt;&gt;&gt; # negative number options present, so both -1s are options
+
>>> # negative number options present, so both -1s are options
&gt;&gt;&gt; parser.parse_args(['-1', '-1'])
+
>>> parser.parse_args(['-1', '-1'])
 
usage: PROG [-h] [-1 ONE] [foo]
 
usage: PROG [-h] [-1 ONE] [foo]
PROG: error: argument -1: expected one argument</pre>
+
PROG: error: argument -1: expected one argument</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
If you have positional arguments that must begin with <code>-</code> and don't look
+
如果您的位置参数必须以 <code>-</code> 开头并且看起来不像负数,则可以插入伪参数 <code>'--'</code>,它告诉 [[#argparse.ArgumentParser.parse_args|parse_args()]]之后是位置参数:
like negative numbers, you can insert the pseudo-argument <code>'--'</code> which tells
 
[[#argparse.ArgumentParser.parse_args|<code>parse_args()</code>]] that everything after that is a positional
 
argument:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第2,048行: 第1,767行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; parser.parse_args(['--', '-f'])
+
<syntaxhighlight lang="python3">>>> parser.parse_args(['--', '-f'])
Namespace(foo='-f', one=None)</pre>
+
Namespace(foo='-f', one=None)</syntaxhighlight>
  
 
</div>
 
</div>
第2,059行: 第1,778行:
  
 
<span id="prefix-matching"></span>
 
<span id="prefix-matching"></span>
=== Argument abbreviations (prefix matching) ===
+
=== 参数缩写(前缀匹配) ===
  
The [[#argparse.ArgumentParser.parse_args|<code>parse_args()</code>]] method [[#allow-abbrev|<span class="std std-ref">by default</span>]]
+
[[#argparse.ArgumentParser.parse_args|parse_args()]] 方法 [[#allow-abbrev|默认情况下]] 允许将长选项缩写为前缀,如果缩写是明确的(前缀匹配唯一选项):
allows long options to be abbreviated to a prefix, if the abbreviation is
 
unambiguous (the prefix matches a unique option):
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第2,069行: 第1,786行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; parser = argparse.ArgumentParser(prog='PROG')
+
<syntaxhighlight lang="python3">>>> parser = argparse.ArgumentParser(prog='PROG')
&gt;&gt;&gt; parser.add_argument('-bacon')
+
>>> parser.add_argument('-bacon')
&gt;&gt;&gt; parser.add_argument('-badger')
+
>>> parser.add_argument('-badger')
&gt;&gt;&gt; parser.parse_args('-bac MMM'.split())
+
>>> parser.parse_args('-bac MMM'.split())
 
Namespace(bacon='MMM', badger=None)
 
Namespace(bacon='MMM', badger=None)
&gt;&gt;&gt; parser.parse_args('-bad WOOD'.split())
+
>>> parser.parse_args('-bad WOOD'.split())
 
Namespace(bacon=None, badger='WOOD')
 
Namespace(bacon=None, badger='WOOD')
&gt;&gt;&gt; parser.parse_args('-ba BA'.split())
+
>>> parser.parse_args('-ba BA'.split())
 
usage: PROG [-h] [-bacon BACON] [-badger BADGER]
 
usage: PROG [-h] [-bacon BACON] [-badger BADGER]
PROG: error: ambiguous option: -ba could match -badger, -bacon</pre>
+
PROG: error: ambiguous option: -ba could match -badger, -bacon</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
An error is produced for arguments that could produce more than one options.
+
产生多个选项的参数会产生错误。 可以通过将 [[#allow-abbrev|allow_abbrev]] 设置为 <code>False</code> 来禁用此功能。
This feature can be disabled by setting [[#allow-abbrev|<span class="std std-ref">allow_abbrev</span>]] to <code>False</code>.
 
  
  
第2,091行: 第1,807行:
  
 
<span id="args"></span>
 
<span id="args"></span>
=== Beyond <code>sys.argv</code> ===
+
=== 超越sys.argv ===
  
Sometimes it may be useful to have an ArgumentParser parse arguments other than those
+
有时,让 ArgumentParser 解析除 [[../sys#sys|sys.argv]] 之外的参数可能会很有用。 这可以通过将字符串列表传递给 [[#argparse.ArgumentParser.parse_args|parse_args()]] 来完成。 这对于在交互式提示下进行测试很有用:
of [[../sys#sys|<code>sys.argv</code>]]. This can be accomplished by passing a list of strings to
 
[[#argparse.ArgumentParser.parse_args|<code>parse_args()</code>]]. This is useful for testing at the
 
interactive prompt:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第2,102行: 第1,815行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; parser = argparse.ArgumentParser()
+
<syntaxhighlight lang="python3">>>> parser = argparse.ArgumentParser()
&gt;&gt;&gt; parser.add_argument(
+
>>> parser.add_argument(
 
...    'integers', metavar='int', type=int, choices=range(10),
 
...    'integers', metavar='int', type=int, choices=range(10),
 
...    nargs='+', help='an integer in the range 0..9')
 
...    nargs='+', help='an integer in the range 0..9')
&gt;&gt;&gt; parser.add_argument(
+
>>> parser.add_argument(
 
...    '--sum', dest='accumulate', action='store_const', const=sum,
 
...    '--sum', dest='accumulate', action='store_const', const=sum,
 
...    default=max, help='sum the integers (default: find the max)')
 
...    default=max, help='sum the integers (default: find the max)')
&gt;&gt;&gt; parser.parse_args(['1', '2', '3', '4'])
+
>>> parser.parse_args(['1', '2', '3', '4'])
Namespace(accumulate=&lt;built-in function max&gt;, integers=[1, 2, 3, 4])
+
Namespace(accumulate=<built-in function max>, integers=[1, 2, 3, 4])
&gt;&gt;&gt; parser.parse_args(['1', '2', '3', '4', '--sum'])
+
>>> parser.parse_args(['1', '2', '3', '4', '--sum'])
Namespace(accumulate=&lt;built-in function sum&gt;, integers=[1, 2, 3, 4])</pre>
+
Namespace(accumulate=<built-in function sum>, integers=[1, 2, 3, 4])</syntaxhighlight>
  
 
</div>
 
</div>
第2,122行: 第1,835行:
  
 
<span id="namespace"></span>
 
<span id="namespace"></span>
=== The Namespace object ===
+
=== 命名空间对象 ===
  
; ''class'' <code>argparse.</code><code>Namespace</code>
+
; ''<span class="pre">class</span>'' <span class="sig-prename descclassname"><span class="pre">argparse.</span></span><span class="sig-name descname"><span class="pre">Namespace</span></span>
: Simple class used by default by [[#argparse.ArgumentParser.parse_args|<code>parse_args()</code>]] to create an object holding attributes and return it.
+
: [[#argparse.ArgumentParser.parse_args|parse_args()]] 默认使用的简单类来创建一个包含属性的对象并返回它。
  
This class is deliberately simple, just an [[../functions#object|<code>object</code>]] subclass with a
+
这个类故意简单,只是一个具有可读字符串表示的 [[../functions#object|object]] 子类。 如果您更喜欢类似 dict 的属性视图,您可以使用标准的 Python 习语,[[../functions#vars|vars()]]
readable string representation. If you prefer to have dict-like view of the
 
attributes, you can use the standard Python idiom, [[../functions#vars|<code>vars()</code>]]:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第2,135行: 第1,846行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; parser = argparse.ArgumentParser()
+
<syntaxhighlight lang="python3">>>> parser = argparse.ArgumentParser()
&gt;&gt;&gt; parser.add_argument('--foo')
+
>>> parser.add_argument('--foo')
&gt;&gt;&gt; args = parser.parse_args(['--foo', 'BAR'])
+
>>> args = parser.parse_args(['--foo', 'BAR'])
&gt;&gt;&gt; vars(args)
+
>>> vars(args)
{'foo': 'BAR'}</pre>
+
{'foo': 'BAR'}</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
It may also be useful to have an [[#argparse.ArgumentParser|<code>ArgumentParser</code>]] assign attributes to an
+
[[#argparse.ArgumentParser|ArgumentParser]] 将属性分配给已经存在的对象,而不是新的 [[#argparse.Namespace|Namespace]] 对象也可能很有用。 这可以通过指定 <code>namespace=</code> 关键字参数来实现:
already existing object, rather than a new [[#argparse.Namespace|<code>Namespace</code>]] object. This can
 
be achieved by specifying the <code>namespace=</code> keyword argument:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第2,152行: 第1,861行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; class C:
+
<syntaxhighlight lang="python3">>>> class C:
 
...    pass
 
...    pass
 
...
 
...
&gt;&gt;&gt; c = C()
+
>>> c = C()
&gt;&gt;&gt; parser = argparse.ArgumentParser()
+
>>> parser = argparse.ArgumentParser()
&gt;&gt;&gt; parser.add_argument('--foo')
+
>>> parser.add_argument('--foo')
&gt;&gt;&gt; parser.parse_args(args=['--foo', 'BAR'], namespace=c)
+
>>> parser.parse_args(args=['--foo', 'BAR'], namespace=c)
&gt;&gt;&gt; c.foo
+
>>> c.foo
'BAR'</pre>
+
'BAR'</syntaxhighlight>
  
 
</div>
 
</div>
第2,171行: 第1,880行:
 
<div id="other-utilities" class="section">
 
<div id="other-utilities" class="section">
  
== Other utilities ==
+
== 其他公用事业 ==
  
 
<div id="sub-commands" class="section">
 
<div id="sub-commands" class="section">
  
=== Sub-commands ===
+
=== 子命令 ===
  
 
<dl>
 
<dl>
<dt><code>ArgumentParser.</code><code>add_subparsers</code><span class="sig-paren">(</span><span class="optional">[</span>''title''<span class="optional">]</span><span class="optional">[</span>, ''description''<span class="optional">]</span><span class="optional">[</span>, ''prog''<span class="optional">]</span><span class="optional">[</span>, ''parser_class''<span class="optional">]</span><span class="optional">[</span>, ''action''<span class="optional">]</span><span class="optional">[</span>, ''option_string''<span class="optional">]</span><span class="optional">[</span>, ''dest''<span class="optional">]</span><span class="optional">[</span>, ''required''<span class="optional">]</span><span class="optional">[</span>, ''help''<span class="optional">]</span><span class="optional">[</span>, ''metavar''<span class="optional">]</span><span class="sig-paren">)</span></dt>
+
<dt><span class="sig-prename descclassname"><span class="pre">ArgumentParser.</span></span><span class="sig-name descname"><span class="pre">add_subparsers</span></span><span class="sig-paren">(</span><span class="optional">[</span>''<span class="pre">title</span>''<span class="optional">]</span><span class="optional">[</span>, ''<span class="pre">description</span>''<span class="optional">]</span><span class="optional">[</span>, ''<span class="pre">prog</span>''<span class="optional">]</span><span class="optional">[</span>, ''<span class="pre">parser_class</span>''<span class="optional">]</span><span class="optional">[</span>, ''<span class="pre">action</span>''<span class="optional">]</span><span class="optional">[</span>, ''<span class="pre">option_string</span>''<span class="optional">]</span><span class="optional">[</span>, ''<span class="pre">dest</span>''<span class="optional">]</span><span class="optional">[</span>, ''<span class="pre">required</span>''<span class="optional">]</span><span class="optional">[</span>, ''<span class="pre">help</span>''<span class="optional">]</span><span class="optional">[</span>, ''<span class="pre">metavar</span>''<span class="optional">]</span><span class="sig-paren">)</span></dt>
<dd><p>Many programs split up their functionality into a number of sub-commands,
+
<dd><p>许多程序将它们的功能拆分为多个子命令,例如,<code>svn</code> 程序可以调用子命令,如 <code>svn checkout</code><code>svn update</code> 和 [ X168X]。 当程序执行需要不同类型命令行参数的多个不同功能时,以这种方式拆分功能可能是一个特别好的主意。 [[#argparse.ArgumentParser|ArgumentParser]] 支持使用 [[#argparse.ArgumentParser.add_subparsers|add_subparsers()]] 方法创建此类子命令。 [[#argparse.ArgumentParser.add_subparsers|add_subparsers()]] 方法通常不带参数调用,并返回一个特殊的动作对象。 这个对象有一个方法,<code>add_parser()</code>,它接受一个命令名称和任何 [[#argparse.ArgumentParser|ArgumentParser]] 构造函数参数,并返回一个可以像往常一样修改的 [[#argparse.ArgumentParser|ArgumentParser]] 对象。</p>
for example, the <code>svn</code> program can invoke sub-commands like <code>svn checkout</code>, <code>svn update</code>, and <code>svn commit</code>. Splitting up functionality
+
<p>参数说明:</p>
this way can be a particularly good idea when a program performs several
 
different functions which require different kinds of command-line arguments.
 
[[#argparse.ArgumentParser|<code>ArgumentParser</code>]] supports the creation of such sub-commands with the
 
[[#argparse.ArgumentParser.add_subparsers|<code>add_subparsers()</code>]] method. The [[#argparse.ArgumentParser.add_subparsers|<code>add_subparsers()</code>]] method is normally
 
called with no arguments and returns a special action object. This object
 
has a single method, <code>add_parser()</code>, which takes a
 
command name and any [[#argparse.ArgumentParser|<code>ArgumentParser</code>]] constructor arguments, and
 
returns an [[#argparse.ArgumentParser|<code>ArgumentParser</code>]] object that can be modified as usual.</p>
 
<p>Description of parameters:</p>
 
 
<ul>
 
<ul>
<li><p>title - title for the sub-parser group in help output; by default
+
<li><p>title - 帮助输出中子解析器组的标题; 默认情况下“子命令”如果提供了描述,否则使用标题作为位置参数</p></li>
&quot;subcommands&quot; if description is provided, otherwise uses title for
+
<li><p>description - 帮助输出中子解析器组的描述,默认情况下 <code>None</code></p></li>
positional arguments</p></li>
+
<li><p>prog - 将与子命令帮助一起显示的使用信息,默认情况下程序的名称和 subparser 参数之前的任何位置参数</p></li>
<li><p>description - description for the sub-parser group in help output, by
+
<li><p>parser_class - 将用于创建子解析器实例的类,默认情况下当前解析器的类(例如 参数解析器)</p></li>
default <code>None</code></p></li>
+
<li><p>[[#action|action]] - 在命令行遇到此参数时要采取的基本操作类型</p></li>
<li><p>prog - usage information that will be displayed with sub-command help,
+
<li><p>[[#dest|dest]] - 将存储子命令名称的属性名称; 默认 <code>None</code> 并且不存储任何值</p></li>
by default the name of the program and any positional arguments before the
+
<li><p>[[#required|required]] - 是否必须提供子命令,默认情况下 <code>False</code>(在 3.7 中添加)</p></li>
subparser argument</p></li>
+
<li><p>[[#help|help]] - 帮助输出中子解析器组的帮助,默认情况下 <code>None</code></p></li>
<li><p>parser_class - class which will be used to create sub-parser instances, by
+
<li><p>[[#metavar|metavar]] - 在帮助中显示可用子命令的字符串; 默认情况下它是 <code>None</code> 并以 {cmd1, cmd2, ..} 形式呈现子命令</p></li></ul>
default the class of the current parser (e.g. ArgumentParser)</p></li>
 
<li><p>[[#action|action]] - the basic type of action to be taken when this argument is
 
encountered at the command line</p></li>
 
<li><p>[[#dest|dest]] - name of the attribute under which sub-command name will be
 
stored; by default <code>None</code> and no value is stored</p></li>
 
<li><p>[[#required|required]] - Whether or not a subcommand must be provided, by default
 
<code>False</code> (added in 3.7)</p></li>
 
<li><p>[[#help|help]] - help for sub-parser group in help output, by default <code>None</code></p></li>
 
<li><p>[[#metavar|metavar]] - string presenting available sub-commands in help; by default it
 
is <code>None</code> and presents sub-commands in form {cmd1, cmd2, ..}</p></li></ul>
 
  
<p>Some example usage:</p>
+
<p>一些示例用法:</p>
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
  
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; # create the top-level parser
+
<syntaxhighlight lang="python3">>>> # create the top-level parser
&gt;&gt;&gt; parser = argparse.ArgumentParser(prog='PROG')
+
>>> parser = argparse.ArgumentParser(prog='PROG')
&gt;&gt;&gt; parser.add_argument('--foo', action='store_true', help='foo help')
+
>>> parser.add_argument('--foo', action='store_true', help='foo help')
&gt;&gt;&gt; subparsers = parser.add_subparsers(help='sub-command help')
+
>>> subparsers = parser.add_subparsers(help='sub-command help')
&gt;&gt;&gt;
+
>>>
&gt;&gt;&gt; # create the parser for the &quot;a&quot; command
+
>>> # create the parser for the "a" command
&gt;&gt;&gt; parser_a = subparsers.add_parser('a', help='a help')
+
>>> parser_a = subparsers.add_parser('a', help='a help')
&gt;&gt;&gt; parser_a.add_argument('bar', type=int, help='bar help')
+
>>> parser_a.add_argument('bar', type=int, help='bar help')
&gt;&gt;&gt;
+
>>>
&gt;&gt;&gt; # create the parser for the &quot;b&quot; command
+
>>> # create the parser for the "b" command
&gt;&gt;&gt; parser_b = subparsers.add_parser('b', help='b help')
+
>>> parser_b = subparsers.add_parser('b', help='b help')
&gt;&gt;&gt; parser_b.add_argument('--baz', choices='XYZ', help='baz help')
+
>>> parser_b.add_argument('--baz', choices='XYZ', help='baz help')
&gt;&gt;&gt;
+
>>>
&gt;&gt;&gt; # parse some argument lists
+
>>> # parse some argument lists
&gt;&gt;&gt; parser.parse_args(['a', '12'])
+
>>> parser.parse_args(['a', '12'])
 
Namespace(bar=12, foo=False)
 
Namespace(bar=12, foo=False)
&gt;&gt;&gt; parser.parse_args(['--foo', 'b', '--baz', 'Z'])
+
>>> parser.parse_args(['--foo', 'b', '--baz', 'Z'])
Namespace(baz='Z', foo=True)</pre>
+
Namespace(baz='Z', foo=True)</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
<p>Note that the object returned by [[#argparse.ArgumentParser.parse_args|<code>parse_args()</code>]] will only contain
+
<p>请注意, [[#argparse.ArgumentParser.parse_args|parse_args()]] 返回的对象将仅包含主解析器和命令行选择的子解析器(而不是任何其他子解析器)的属性。 所以在上面的例子中,当指定<code>a</code>命令时,只有<code>foo</code><code>bar</code>属性存在,而当指定<code>b</code>命令时,仅存在 <code>foo</code> <code>baz</code> 属性。</p>
attributes for the main parser and the subparser that was selected by the
+
<p>类似地,当从子解析器请求帮助消息时,只会打印该特定解析器的帮助。 帮助消息将不包括父解析器或兄弟解析器消息。 (但是,可以通过将 <code>help=</code> 参数提供给上述 <code>add_parser()</code> 来给出每个子解析器命令的帮助消息。)</p>
command line (and not any other subparsers). So in the example above, when
 
the <code>a</code> command is specified, only the <code>foo</code> and <code>bar</code> attributes are
 
present, and when the <code>b</code> command is specified, only the <code>foo</code> and
 
<code>baz</code> attributes are present.</p>
 
<p>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 <code>help=</code> argument
 
to <code>add_parser()</code> as above.)</p>
 
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
  
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; parser.parse_args(['--help'])
+
<syntaxhighlight lang="python3">>>> parser.parse_args(['--help'])
 
usage: PROG [-h] [--foo] {a,b} ...
 
usage: PROG [-h] [--foo] {a,b} ...
  
第2,265行: 第1,946行:
 
   --foo  foo help
 
   --foo  foo help
  
&gt;&gt;&gt; parser.parse_args(['a', '--help'])
+
>>> parser.parse_args(['a', '--help'])
 
usage: PROG a [-h] bar
 
usage: PROG a [-h] bar
  
第2,274行: 第1,955行:
 
   -h, --help  show this help message and exit
 
   -h, --help  show this help message and exit
  
&gt;&gt;&gt; parser.parse_args(['b', '--help'])
+
>>> parser.parse_args(['b', '--help'])
 
usage: PROG b [-h] [--baz {X,Y,Z}]
 
usage: PROG b [-h] [--baz {X,Y,Z}]
  
 
optional arguments:
 
optional arguments:
 
   -h, --help    show this help message and exit
 
   -h, --help    show this help message and exit
   --baz {X,Y,Z}  baz help</pre>
+
   --baz {X,Y,Z}  baz help</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
<p>The [[#argparse.ArgumentParser.add_subparsers|<code>add_subparsers()</code>]] method also supports <code>title</code> and <code>description</code>
+
<p>[[#argparse.ArgumentParser.add_subparsers|add_subparsers()]] 方法还支持 <code>title</code> <code>description</code> 关键字参数。 当存在任何一个时,子解析器的命令将出现在帮助输出中它们自己的组中。 例如:</p>
keyword arguments. When either is present, the subparser's commands will
 
appear in their own group in the help output. For example:</p>
 
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
  
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; parser = argparse.ArgumentParser()
+
<syntaxhighlight lang="python3">>>> parser = argparse.ArgumentParser()
&gt;&gt;&gt; subparsers = parser.add_subparsers(title='subcommands',
+
>>> subparsers = parser.add_subparsers(title='subcommands',
 
...                                    description='valid subcommands',
 
...                                    description='valid subcommands',
 
...                                    help='additional help')
 
...                                    help='additional help')
&gt;&gt;&gt; subparsers.add_parser('foo')
+
>>> subparsers.add_parser('foo')
&gt;&gt;&gt; subparsers.add_parser('bar')
+
>>> subparsers.add_parser('bar')
&gt;&gt;&gt; parser.parse_args(['-h'])
+
>>> parser.parse_args(['-h'])
 
usage:  [-h] {foo,bar} ...
 
usage:  [-h] {foo,bar} ...
  
第2,306行: 第1,985行:
 
   valid subcommands
 
   valid subcommands
  
   {foo,bar}  additional help</pre>
+
   {foo,bar}  additional help</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
<p>Furthermore, <code>add_parser</code> supports an additional <code>aliases</code> argument,
+
<p>此外,<code>add_parser</code> 支持额外的 <code>aliases</code> 参数,它允许多个字符串引用同一个子解析器。 这个例子,像 <code>svn</code>,别名 <code>co</code> 作为 <code>checkout</code> 的简写:</p>
which allows multiple strings to refer to the same subparser. This example,
 
like <code>svn</code>, aliases <code>co</code> as a shorthand for <code>checkout</code>:</p>
 
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
  
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; parser = argparse.ArgumentParser()
+
<syntaxhighlight lang="python3">>>> parser = argparse.ArgumentParser()
&gt;&gt;&gt; subparsers = parser.add_subparsers()
+
>>> subparsers = parser.add_subparsers()
&gt;&gt;&gt; checkout = subparsers.add_parser('checkout', aliases=['co'])
+
>>> checkout = subparsers.add_parser('checkout', aliases=['co'])
&gt;&gt;&gt; checkout.add_argument('foo')
+
>>> checkout.add_argument('foo')
&gt;&gt;&gt; parser.parse_args(['co', 'bar'])
+
>>> parser.parse_args(['co', 'bar'])
Namespace(foo='bar')</pre>
+
Namespace(foo='bar')</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
<p>One particularly effective way of handling sub-commands is to combine the use
+
<p>处理子命令的一种特别有效的方法是将 [[#argparse.ArgumentParser.add_subparsers|add_subparsers()]] 方法的使用与对 [[#argparse.ArgumentParser.set_defaults|set_defaults()]] 的调用结合起来,以便每个子解析器知道它应该执行哪个 Python 函数。 例如:</p>
of the [[#argparse.ArgumentParser.add_subparsers|<code>add_subparsers()</code>]] method with calls to [[#argparse.ArgumentParser.set_defaults|<code>set_defaults()</code>]] so
 
that each subparser knows which Python function it should execute. For
 
example:</p>
 
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
  
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; # sub-command functions
+
<syntaxhighlight lang="python3">>>> # sub-command functions
&gt;&gt;&gt; def foo(args):
+
>>> def foo(args):
 
...    print(args.x * args.y)
 
...    print(args.x * args.y)
 
...
 
...
&gt;&gt;&gt; def bar(args):
+
>>> def bar(args):
 
...    print('((%s))' % args.z)
 
...    print('((%s))' % args.z)
 
...
 
...
&gt;&gt;&gt; # create the top-level parser
+
>>> # create the top-level parser
&gt;&gt;&gt; parser = argparse.ArgumentParser()
+
>>> parser = argparse.ArgumentParser()
&gt;&gt;&gt; subparsers = parser.add_subparsers()
+
>>> subparsers = parser.add_subparsers()
&gt;&gt;&gt;
+
>>>
&gt;&gt;&gt; # create the parser for the &quot;foo&quot; command
+
>>> # create the parser for the "foo" command
&gt;&gt;&gt; parser_foo = subparsers.add_parser('foo')
+
>>> parser_foo = subparsers.add_parser('foo')
&gt;&gt;&gt; parser_foo.add_argument('-x', type=int, default=1)
+
>>> parser_foo.add_argument('-x', type=int, default=1)
&gt;&gt;&gt; parser_foo.add_argument('y', type=float)
+
>>> parser_foo.add_argument('y', type=float)
&gt;&gt;&gt; parser_foo.set_defaults(func=foo)
+
>>> parser_foo.set_defaults(func=foo)
&gt;&gt;&gt;
+
>>>
&gt;&gt;&gt; # create the parser for the &quot;bar&quot; command
+
>>> # create the parser for the "bar" command
&gt;&gt;&gt; parser_bar = subparsers.add_parser('bar')
+
>>> parser_bar = subparsers.add_parser('bar')
&gt;&gt;&gt; parser_bar.add_argument('z')
+
>>> parser_bar.add_argument('z')
&gt;&gt;&gt; parser_bar.set_defaults(func=bar)
+
>>> parser_bar.set_defaults(func=bar)
&gt;&gt;&gt;
+
>>>
&gt;&gt;&gt; # parse the args and call whatever function was selected
+
>>> # parse the args and call whatever function was selected
&gt;&gt;&gt; args = parser.parse_args('foo 1 -x 2'.split())
+
>>> args = parser.parse_args('foo 1 -x 2'.split())
&gt;&gt;&gt; args.func(args)
+
>>> args.func(args)
 
2.0
 
2.0
&gt;&gt;&gt;
+
>>>
&gt;&gt;&gt; # parse the args and call whatever function was selected
+
>>> # parse the args and call whatever function was selected
&gt;&gt;&gt; args = parser.parse_args('bar XYZYX'.split())
+
>>> args = parser.parse_args('bar XYZYX'.split())
&gt;&gt;&gt; args.func(args)
+
>>> args.func(args)
((XYZYX))</pre>
+
((XYZYX))</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
<p>This way, you can let [[#argparse.ArgumentParser.parse_args|<code>parse_args()</code>]] do the job of calling the
+
<p>这样,您可以让 [[#argparse.ArgumentParser.parse_args|parse_args()]] 在参数解析完成后执行调用适当函数的工作。 将函数与这样的动作相关联通常是处理每个子解析器不同动作的最简单方法。 但是,如果需要检查被调用的子解析器的名称,[[#argparse.ArgumentParser.add_subparsers|add_subparsers()]] 调用的 <code>dest</code> 关键字参数将起作用:</p>
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 <code>dest</code> keyword
 
argument to the [[#argparse.ArgumentParser.add_subparsers|<code>add_subparsers()</code>]] call will work:</p>
 
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
  
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; parser = argparse.ArgumentParser()
+
<syntaxhighlight lang="python3">>>> parser = argparse.ArgumentParser()
&gt;&gt;&gt; subparsers = parser.add_subparsers(dest='subparser_name')
+
>>> subparsers = parser.add_subparsers(dest='subparser_name')
&gt;&gt;&gt; subparser1 = subparsers.add_parser('1')
+
>>> subparser1 = subparsers.add_parser('1')
&gt;&gt;&gt; subparser1.add_argument('-x')
+
>>> subparser1.add_argument('-x')
&gt;&gt;&gt; subparser2 = subparsers.add_parser('2')
+
>>> subparser2 = subparsers.add_parser('2')
&gt;&gt;&gt; subparser2.add_argument('y')
+
>>> subparser2.add_argument('y')
&gt;&gt;&gt; parser.parse_args(['2', 'frobble'])
+
>>> parser.parse_args(['2', 'frobble'])
Namespace(subparser_name='2', y='frobble')</pre>
+
Namespace(subparser_name='2', y='frobble')</syntaxhighlight>
  
 
</div>
 
</div>
第2,395行: 第2,064行:
 
<div class="versionchanged">
 
<div class="versionchanged">
  
<p><span class="versionmodified changed">在 3.7 版更改: </span>New ''required'' keyword argument.</p>
+
<p><span class="versionmodified changed">在 3.7 版更改:</span>新增 ''required'' 关键字参数。</p>
  
 
</div></dd></dl>
 
</div></dd></dl>
第2,403行: 第2,072行:
 
<div id="filetype-objects" class="section">
 
<div id="filetype-objects" class="section">
  
=== FileType objects ===
+
=== 文件类型对象 ===
  
 
<dl>
 
<dl>
<dt>''class'' <code>argparse.</code><code>FileType</code><span class="sig-paren">(</span>''<span class="n">mode</span><span class="o">=</span><span class="default_value">'r'</span>'', ''<span class="n">bufsize</span><span class="o">=</span><span class="default_value">- 1</span>'', ''<span class="n">encoding</span><span class="o">=</span><span class="default_value">None</span>'', ''<span class="n">errors</span><span class="o">=</span><span class="default_value">None</span>''<span class="sig-paren">)</span></dt>
+
<dt>''<span class="pre">class</span>'' <span class="sig-prename descclassname"><span class="pre">argparse.</span></span><span class="sig-name descname"><span class="pre">FileType</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">mode</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">'r'</span></span>'', ''<span class="n"><span class="pre">bufsize</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">-</span> <span class="pre">1</span></span>'', ''<span class="n"><span class="pre">encoding</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>'', ''<span class="n"><span class="pre">errors</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>The [[#argparse.FileType|<code>FileType</code>]] factory creates objects that can be passed to the type
+
<dd><p>[[#argparse.FileType|FileType]] 工厂创建可以传递给 [[#argparse.ArgumentParser.add_argument|ArgumentParser.add_argument()]] 的类型参数的对象。 将 [[#argparse.FileType|FileType]] 对象作为其类型的参数将打开命令行参数作为具有请求模式、缓冲区大小、编码和错误处理的文件(有关更多详细信息,请参阅 [[../functions#open|open()]] 函数)</p>
argument of [[#argparse.ArgumentParser.add_argument|<code>ArgumentParser.add_argument()</code>]]. Arguments that have
 
[[#argparse.FileType|<code>FileType</code>]] objects as their type will open command-line arguments as
 
files with the requested modes, buffer sizes, encodings and error handling
 
(see the [[../functions#open|<code>open()</code>]] function for more details):</p>
 
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
  
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; parser = argparse.ArgumentParser()
+
<syntaxhighlight lang="python3">>>> parser = argparse.ArgumentParser()
&gt;&gt;&gt; parser.add_argument('--raw', type=argparse.FileType('wb', 0))
+
>>> parser.add_argument('--raw', type=argparse.FileType('wb', 0))
&gt;&gt;&gt; parser.add_argument('out', type=argparse.FileType('w', encoding='UTF-8'))
+
>>> parser.add_argument('out', type=argparse.FileType('w', encoding='UTF-8'))
&gt;&gt;&gt; parser.parse_args(['--raw', 'raw.dat', 'file.txt'])
+
>>> parser.parse_args(['--raw', 'raw.dat', 'file.txt'])
Namespace(out=&lt;_io.TextIOWrapper name='file.txt' mode='w' encoding='UTF-8'&gt;, raw=&lt;_io.FileIO name='raw.dat' mode='wb'&gt;)</pre>
+
Namespace(out=<_io.TextIOWrapper name='file.txt' mode='w' encoding='UTF-8'>, raw=<_io.FileIO name='raw.dat' mode='wb'>)</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
<p>FileType objects understand the pseudo-argument <code>'-'</code> and automatically
+
<p>FileType 对象理解伪参数 <code>'-'</code> 并自动将其转换为 <code>sys.stdin</code> 可读 [[#argparse.FileType|FileType]] 对象和 <code>sys.stdout</code> 可写 [[#argparse.FileType|FileType]]对象:</p>
convert this into <code>sys.stdin</code> for readable [[#argparse.FileType|<code>FileType</code>]] objects and
 
<code>sys.stdout</code> for writable [[#argparse.FileType|<code>FileType</code>]] objects:</p>
 
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
  
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; parser = argparse.ArgumentParser()
+
<syntaxhighlight lang="python3">>>> parser = argparse.ArgumentParser()
&gt;&gt;&gt; parser.add_argument('infile', type=argparse.FileType('r'))
+
>>> parser.add_argument('infile', type=argparse.FileType('r'))
&gt;&gt;&gt; parser.parse_args(['-'])
+
>>> parser.parse_args(['-'])
Namespace(infile=&lt;_io.TextIOWrapper name='&lt;stdin&gt;' encoding='UTF-8'&gt;)</pre>
+
Namespace(infile=<_io.TextIOWrapper name='<stdin>' encoding='UTF-8'>)</syntaxhighlight>
  
 
</div>
 
</div>
第2,442行: 第2,105行:
 
<div class="versionadded">
 
<div class="versionadded">
  
<p><span class="versionmodified added">3.4 新版功能: </span>The ''encodings'' and ''errors'' keyword arguments.</p>
+
<p><span class="versionmodified added">3.4 版新功能:</span>''encodings'' ''errors'' 关键字参数。</p>
  
 
</div></dd></dl>
 
</div></dd></dl>
第2,450行: 第2,113行:
 
<div id="argument-groups" class="section">
 
<div id="argument-groups" class="section">
  
=== Argument groups ===
+
=== 参数组 ===
  
 
<dl>
 
<dl>
<dt><code>ArgumentParser.</code><code>add_argument_group</code><span class="sig-paren">(</span>''<span class="n">title</span><span class="o">=</span><span class="default_value">None</span>'', ''<span class="n">description</span><span class="o">=</span><span class="default_value">None</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-prename descclassname"><span class="pre">ArgumentParser.</span></span><span class="sig-name descname"><span class="pre">add_argument_group</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">title</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>'', ''<span class="n"><span class="pre">description</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>By default, [[#argparse.ArgumentParser|<code>ArgumentParser</code>]] groups command-line arguments into
+
<dd><p>默认情况下,[[#argparse.ArgumentParser|ArgumentParser]] 在显示帮助消息时将命令行参数分为“位置参数”和“可选参数”。 当存在比默认参数更好的概念分组时,可以使用 [[#argparse.ArgumentParser.add_argument_group|add_argument_group()]] 方法创建适当的组:</p>
&quot;positional arguments&quot; and &quot;optional arguments&quot; when displaying help
 
messages. When there is a better conceptual grouping of arguments than this
 
default one, appropriate groups can be created using the
 
[[#argparse.ArgumentParser.add_argument_group|<code>add_argument_group()</code>]] method:</p>
 
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
  
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; parser = argparse.ArgumentParser(prog='PROG', add_help=False)
+
<syntaxhighlight lang="python3">>>> parser = argparse.ArgumentParser(prog='PROG', add_help=False)
&gt;&gt;&gt; group = parser.add_argument_group('group')
+
>>> group = parser.add_argument_group('group')
&gt;&gt;&gt; group.add_argument('--foo', help='foo help')
+
>>> group.add_argument('--foo', help='foo help')
&gt;&gt;&gt; group.add_argument('bar', help='bar help')
+
>>> group.add_argument('bar', help='bar help')
&gt;&gt;&gt; parser.print_help()
+
>>> parser.print_help()
 
usage: PROG [--foo FOO] bar
 
usage: PROG [--foo FOO] bar
  
 
group:
 
group:
 
   bar    bar help
 
   bar    bar help
   --foo FOO  foo help</pre>
+
   --foo FOO  foo help</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
<p>The [[#argparse.ArgumentParser.add_argument_group|<code>add_argument_group()</code>]] method returns an argument group object which
+
<p>[[#argparse.ArgumentParser.add_argument_group|add_argument_group()]] 方法返回一个参数组对象,它有一个 [[#argparse.ArgumentParser.add_argument|add_argument()]] 方法,就像一个常规的 [[#argparse.ArgumentParser|ArgumentParser]]。 将参数添加到组中时,解析器会将其视为普通参数,但会在单独的组中显示该参数以获取帮助消息。 [[#argparse.ArgumentParser.add_argument_group|add_argument_group()]] 方法接受 ''title'' ''description'' 参数,可用于自定义此显示:</p>
has an [[#argparse.ArgumentParser.add_argument|<code>add_argument()</code>]] method just like a regular
 
[[#argparse.ArgumentParser|<code>ArgumentParser</code>]]. 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 [[#argparse.ArgumentParser.add_argument_group|<code>add_argument_group()</code>]] method
 
accepts ''title'' and ''description'' arguments which can be used to
 
customize this display:</p>
 
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
  
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; parser = argparse.ArgumentParser(prog='PROG', add_help=False)
+
<syntaxhighlight lang="python3">>>> parser = argparse.ArgumentParser(prog='PROG', add_help=False)
&gt;&gt;&gt; group1 = parser.add_argument_group('group1', 'group1 description')
+
>>> group1 = parser.add_argument_group('group1', 'group1 description')
&gt;&gt;&gt; group1.add_argument('foo', help='foo help')
+
>>> group1.add_argument('foo', help='foo help')
&gt;&gt;&gt; group2 = parser.add_argument_group('group2', 'group2 description')
+
>>> group2 = parser.add_argument_group('group2', 'group2 description')
&gt;&gt;&gt; group2.add_argument('--bar', help='bar help')
+
>>> group2.add_argument('--bar', help='bar help')
&gt;&gt;&gt; parser.print_help()
+
>>> parser.print_help()
 
usage: PROG [--bar BAR] foo
 
usage: PROG [--bar BAR] foo
  
第2,504行: 第2,157行:
 
   group2 description
 
   group2 description
  
   --bar BAR  bar help</pre>
+
   --bar BAR  bar help</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
<p>Note that any arguments not in your user-defined groups will end up back
+
<p>请注意,任何不在用户定义组中的参数最终都会回到通常的“位置参数”和“可选参数”部分。</p></dd></dl>
in the usual &quot;positional arguments&quot; and &quot;optional arguments&quot; sections.</p></dd></dl>
 
  
  
第2,516行: 第2,168行:
 
<div id="mutual-exclusion" class="section">
 
<div id="mutual-exclusion" class="section">
  
=== Mutual exclusion ===
+
=== 相互排斥 ===
  
 
<dl>
 
<dl>
<dt><code>ArgumentParser.</code><code>add_mutually_exclusive_group</code><span class="sig-paren">(</span>''<span class="n">required</span><span class="o">=</span><span class="default_value">False</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-prename descclassname"><span class="pre">ArgumentParser.</span></span><span class="sig-name descname"><span class="pre">add_mutually_exclusive_group</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">required</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">False</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Create a mutually exclusive group. [[#module-argparse|<code>argparse</code>]] will make sure that only
+
<dd><p>创建一个互斥组。 [[#module-argparse|argparse]] 将确保在互斥组中只有一个参数出现在命令行上:</p>
one of the arguments in the mutually exclusive group was present on the
 
command line:</p>
 
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
  
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; parser = argparse.ArgumentParser(prog='PROG')
+
<syntaxhighlight lang="python3">>>> parser = argparse.ArgumentParser(prog='PROG')
&gt;&gt;&gt; group = parser.add_mutually_exclusive_group()
+
>>> group = parser.add_mutually_exclusive_group()
&gt;&gt;&gt; group.add_argument('--foo', action='store_true')
+
>>> group.add_argument('--foo', action='store_true')
&gt;&gt;&gt; group.add_argument('--bar', action='store_false')
+
>>> group.add_argument('--bar', action='store_false')
&gt;&gt;&gt; parser.parse_args(['--foo'])
+
>>> parser.parse_args(['--foo'])
 
Namespace(bar=True, foo=True)
 
Namespace(bar=True, foo=True)
&gt;&gt;&gt; parser.parse_args(['--bar'])
+
>>> parser.parse_args(['--bar'])
 
Namespace(bar=False, foo=False)
 
Namespace(bar=False, foo=False)
&gt;&gt;&gt; parser.parse_args(['--foo', '--bar'])
+
>>> parser.parse_args(['--foo', '--bar'])
 
usage: PROG [-h] [--foo | --bar]
 
usage: PROG [-h] [--foo | --bar]
PROG: error: argument --bar: not allowed with argument --foo</pre>
+
PROG: error: argument --bar: not allowed with argument --foo</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
<p>The [[#argparse.ArgumentParser.add_mutually_exclusive_group|<code>add_mutually_exclusive_group()</code>]] method also accepts a ''required''
+
<p>[[#argparse.ArgumentParser.add_mutually_exclusive_group|add_mutually_exclusive_group()]] 方法还接受 ''required'' 参数,以指示至少需要一个互斥参数:</p>
argument, to indicate that at least one of the mutually exclusive arguments
 
is required:</p>
 
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
  
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; parser = argparse.ArgumentParser(prog='PROG')
+
<syntaxhighlight lang="python3">>>> parser = argparse.ArgumentParser(prog='PROG')
&gt;&gt;&gt; group = parser.add_mutually_exclusive_group(required=True)
+
>>> group = parser.add_mutually_exclusive_group(required=True)
&gt;&gt;&gt; group.add_argument('--foo', action='store_true')
+
>>> group.add_argument('--foo', action='store_true')
&gt;&gt;&gt; group.add_argument('--bar', action='store_false')
+
>>> group.add_argument('--bar', action='store_false')
&gt;&gt;&gt; parser.parse_args([])
+
>>> parser.parse_args([])
 
usage: PROG [-h] (--foo | --bar)
 
usage: PROG [-h] (--foo | --bar)
PROG: error: one of the arguments --foo --bar is required</pre>
+
PROG: error: one of the arguments --foo --bar is required</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
<p>Note that currently mutually exclusive argument groups do not support the
+
<p>请注意,当前互斥的参数组不支持 [[#argparse.ArgumentParser.add_argument_group|add_argument_group()]] 的 ''title'' 和 ''description'' 参数。</p></dd></dl>
''title'' and ''description'' arguments of
 
[[#argparse.ArgumentParser.add_argument_group|<code>add_argument_group()</code>]].</p></dd></dl>
 
  
  
第2,568行: 第2,214行:
 
<div id="parser-defaults" class="section">
 
<div id="parser-defaults" class="section">
  
=== Parser defaults ===
+
=== 解析器默认值 ===
  
 
<dl>
 
<dl>
<dt><code>ArgumentParser.</code><code>set_defaults</code><span class="sig-paren">(</span>''<span class="o">**</span><span class="n">kwargs</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-prename descclassname"><span class="pre">ArgumentParser.</span></span><span class="sig-name descname"><span class="pre">set_defaults</span></span><span class="sig-paren">(</span>''<span class="o"><span class="pre">**</span></span><span class="n"><span class="pre">kwargs</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Most of the time, the attributes of the object returned by [[#argparse.ArgumentParser.parse_args|<code>parse_args()</code>]]
+
<dd><p>大多数情况下,[[#argparse.ArgumentParser.parse_args|parse_args()]] 返回的对象的属性将通过检查命令行参数和参数操作来完全确定。 [[#argparse.ArgumentParser.set_defaults|set_defaults()]] 允许添加一些无需检查命令行即可确定的其他属性:</p>
will be fully determined by inspecting the command-line arguments and the argument
 
actions. [[#argparse.ArgumentParser.set_defaults|<code>set_defaults()</code>]] allows some additional
 
attributes that are determined without any inspection of the command line to
 
be added:</p>
 
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
  
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; parser = argparse.ArgumentParser()
+
<syntaxhighlight lang="python3">>>> parser = argparse.ArgumentParser()
&gt;&gt;&gt; parser.add_argument('foo', type=int)
+
>>> parser.add_argument('foo', type=int)
&gt;&gt;&gt; parser.set_defaults(bar=42, baz='badger')
+
>>> parser.set_defaults(bar=42, baz='badger')
&gt;&gt;&gt; parser.parse_args(['736'])
+
>>> parser.parse_args(['736'])
Namespace(bar=42, baz='badger', foo=736)</pre>
+
Namespace(bar=42, baz='badger', foo=736)</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
<p>Note that parser-level defaults always override argument-level defaults:</p>
+
<p>请注意,解析器级别的默认值始终覆盖参数级别的默认值:</p>
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
  
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; parser = argparse.ArgumentParser()
+
<syntaxhighlight lang="python3">>>> parser = argparse.ArgumentParser()
&gt;&gt;&gt; parser.add_argument('--foo', default='bar')
+
>>> parser.add_argument('--foo', default='bar')
&gt;&gt;&gt; parser.set_defaults(foo='spam')
+
>>> parser.set_defaults(foo='spam')
&gt;&gt;&gt; parser.parse_args([])
+
>>> parser.parse_args([])
Namespace(foo='spam')</pre>
+
Namespace(foo='spam')</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
<p>Parser-level defaults can be particularly useful when working with multiple
+
<p>当使用多个解析器时,解析器级别的默认值特别有用。 有关此类型的示例,请参阅 [[#argparse.ArgumentParser.add_subparsers|add_subparsers()]] 方法。</p></dd></dl>
parsers. See the [[#argparse.ArgumentParser.add_subparsers|<code>add_subparsers()</code>]] method for an
 
example of this type.</p></dd></dl>
 
  
 
<dl>
 
<dl>
<dt><code>ArgumentParser.</code><code>get_default</code><span class="sig-paren">(</span>''<span class="n">dest</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-prename descclassname"><span class="pre">ArgumentParser.</span></span><span class="sig-name descname"><span class="pre">get_default</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">dest</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Get the default value for a namespace attribute, as set by either
+
<dd><p>获取命名空间属性的默认值,由 [[#argparse.ArgumentParser.add_argument|add_argument()]] [[#argparse.ArgumentParser.set_defaults|set_defaults()]] 设置:</p>
[[#argparse.ArgumentParser.add_argument|<code>add_argument()</code>]] or by
 
[[#argparse.ArgumentParser.set_defaults|<code>set_defaults()</code>]]:</p>
 
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
  
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; parser = argparse.ArgumentParser()
+
<syntaxhighlight lang="python3">>>> parser = argparse.ArgumentParser()
&gt;&gt;&gt; parser.add_argument('--foo', default='badger')
+
>>> parser.add_argument('--foo', default='badger')
&gt;&gt;&gt; parser.get_default('foo')
+
>>> parser.get_default('foo')
'badger'</pre>
+
'badger'</syntaxhighlight>
  
 
</div>
 
</div>
第2,630行: 第2,268行:
 
<div id="printing-help" class="section">
 
<div id="printing-help" class="section">
  
=== Printing help ===
+
=== 打印帮助 ===
  
In most typical applications, [[#argparse.ArgumentParser.parse_args|<code>parse_args()</code>]] will take
+
在大多数典型应用程序中, [[#argparse.ArgumentParser.parse_args|parse_args()]] 将负责格式化和打印任何用法或错误消息。 但是,有几种格式化方法可用:
care of formatting and printing any usage or error messages. However, several
 
formatting methods are available:
 
  
; <code>ArgumentParser.</code><code>print_usage</code><span class="sig-paren">(</span>''<span class="n">file</span><span class="o">=</span><span class="default_value">None</span>''<span class="sig-paren">)</span>
+
; <span class="sig-prename descclassname"><span class="pre">ArgumentParser.</span></span><span class="sig-name descname"><span class="pre">print_usage</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">file</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>''<span class="sig-paren">)</span>
: Print a brief description of how the [[#argparse.ArgumentParser|<code>ArgumentParser</code>]] should be invoked on the command line. If ''file'' is <code>None</code>, [[../sys#sys|<code>sys.stdout</code>]] is assumed.
+
: 打印有关如何在命令行上调用 [[#argparse.ArgumentParser|ArgumentParser]] 的简要说明。 如果 ''file'' <code>None</code>,则假定为 [[../sys#sys|sys.stdout]]
  
; <code>ArgumentParser.</code><code>print_help</code><span class="sig-paren">(</span>''<span class="n">file</span><span class="o">=</span><span class="default_value">None</span>''<span class="sig-paren">)</span>
+
; <span class="sig-prename descclassname"><span class="pre">ArgumentParser.</span></span><span class="sig-name descname"><span class="pre">print_help</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">file</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>''<span class="sig-paren">)</span>
: Print a help message, including the program usage and information about the arguments registered with the [[#argparse.ArgumentParser|<code>ArgumentParser</code>]]. If ''file'' is <code>None</code>, [[../sys#sys|<code>sys.stdout</code>]] is assumed.
+
: 打印一条帮助消息,包括程序使用情况和有关使用 [[#argparse.ArgumentParser|ArgumentParser]] 注册的参数的信息。 如果 ''file'' <code>None</code>,则假定为 [[../sys#sys|sys.stdout]]
  
There are also variants of these methods that simply return a string instead of
+
这些方法还有一些变体,它们只是返回一个字符串而不是打印它:
printing it:
 
  
; <code>ArgumentParser.</code><code>format_usage</code><span class="sig-paren">(</span><span class="sig-paren">)</span>
+
; <span class="sig-prename descclassname"><span class="pre">ArgumentParser.</span></span><span class="sig-name descname"><span class="pre">format_usage</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span>
: Return a string containing a brief description of how the [[#argparse.ArgumentParser|<code>ArgumentParser</code>]] should be invoked on the command line.
+
: 返回一个字符串,其中包含有关如何在命令行上调用 [[#argparse.ArgumentParser|ArgumentParser]] 的简要说明。
  
; <code>ArgumentParser.</code><code>format_help</code><span class="sig-paren">(</span><span class="sig-paren">)</span>
+
; <span class="sig-prename descclassname"><span class="pre">ArgumentParser.</span></span><span class="sig-name descname"><span class="pre">format_help</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span>
: Return a string containing a help message, including the program usage and information about the arguments registered with the [[#argparse.ArgumentParser|<code>ArgumentParser</code>]].
+
: 返回一个包含帮助消息的字符串,包括程序使用情况和有关使用 [[#argparse.ArgumentParser|ArgumentParser]] 注册的参数的信息。
  
  
第2,655行: 第2,290行:
 
<div id="partial-parsing" class="section">
 
<div id="partial-parsing" class="section">
  
=== Partial parsing ===
+
=== 部分解析 ===
  
; <code>ArgumentParser.</code><code>parse_known_args</code><span class="sig-paren">(</span>''<span class="n">args</span><span class="o">=</span><span class="default_value">None</span>'', ''<span class="n">namespace</span><span class="o">=</span><span class="default_value">None</span>''<span class="sig-paren">)</span>
+
; <span class="sig-prename descclassname"><span class="pre">ArgumentParser.</span></span><span class="sig-name descname"><span class="pre">parse_known_args</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">args</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>'', ''<span class="n"><span class="pre">namespace</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>''<span class="sig-paren">)</span>
 
:  
 
:  
  
Sometimes a script may only parse a few of the command-line arguments, passing
+
有时一个脚本可能只解析几个命令行参数,将剩余的参数传递给另一个脚本或程序。 在这些情况下,[[#argparse.ArgumentParser.parse_known_args|parse_known_args()]] 方法会很有用。 它的工作方式与 [[#argparse.ArgumentParser.parse_args|parse_args()]] 非常相似,不同之处在于它在存在额外参数时不会产生错误。 相反,它返回一个包含填充的命名空间和剩余参数字符串列表的两项元组。
the remaining arguments on to another script or program. In these cases, the
 
[[#argparse.ArgumentParser.parse_known_args|<code>parse_known_args()</code>]] method can be useful. It works much like
 
[[#argparse.ArgumentParser.parse_args|<code>parse_args()</code>]] 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.
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第2,671行: 第2,301行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; parser = argparse.ArgumentParser()
+
<syntaxhighlight lang="python3">>>> parser = argparse.ArgumentParser()
&gt;&gt;&gt; parser.add_argument('--foo', action='store_true')
+
>>> parser.add_argument('--foo', action='store_true')
&gt;&gt;&gt; parser.add_argument('bar')
+
>>> parser.add_argument('bar')
&gt;&gt;&gt; parser.parse_known_args(['--foo', '--badger', 'BAR', 'spam'])
+
>>> parser.parse_known_args(['--foo', '--badger', 'BAR', 'spam'])
(Namespace(bar='BAR', foo=True), ['--badger', 'spam'])</pre>
+
(Namespace(bar='BAR', foo=True), ['--badger', 'spam'])</syntaxhighlight>
  
 
</div>
 
</div>
第2,684行: 第2,314行:
 
警告
 
警告
  
[[#prefix-matching|<span class="std std-ref">Prefix matching</span>]] rules apply to
+
[[#prefix-matching|前缀匹配]]规则适用于<code>parse_known_args()</code>。 解析器可能会使用一个选项,即使它只是其已知选项之一的前缀,而不是将它留在剩余的参数列表中。
<code>parse_known_args()</code>. 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.
 
  
  
第2,695行: 第2,322行:
 
<div id="customizing-file-parsing" class="section">
 
<div id="customizing-file-parsing" class="section">
  
=== Customizing file parsing ===
+
=== 自定义文件解析 ===
  
 
<dl>
 
<dl>
<dt><code>ArgumentParser.</code><code>convert_arg_line_to_args</code><span class="sig-paren">(</span>''<span class="n">arg_line</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-prename descclassname"><span class="pre">ArgumentParser.</span></span><span class="sig-name descname"><span class="pre">convert_arg_line_to_args</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">arg_line</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Arguments that are read from a file (see the ''fromfile_prefix_chars''
+
<dd><p>从文件中读取的参数(请参阅 [[#argparse.ArgumentParser|ArgumentParser]] 构造函数的 ''fromfile_prefix_chars'' 关键字参数)每行读取一个参数。 [[#argparse.ArgumentParser.convert_arg_line_to_args|convert_arg_line_to_args()]] 可以被覆盖以进行更高级的阅读。</p>
keyword argument to the [[#argparse.ArgumentParser|<code>ArgumentParser</code>]] constructor) are read one
+
<p>此方法采用单个参数 ''arg_line'',它是从参数文件中读取的字符串。 它返回从此字符串解析的参数列表。 该方法按顺序从参数文件中读取的每一行调用一次。</p>
argument per line. [[#argparse.ArgumentParser.convert_arg_line_to_args|<code>convert_arg_line_to_args()</code>]] can be overridden for
+
<p>此方法的一个有用覆盖是将每个空格分隔的单词视为参数。 以下示例演示了如何执行此操作:</p>
fancier reading.</p>
 
<p>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.</p>
 
<p>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:</p>
 
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
  
 
<div class="highlight">
 
<div class="highlight">
  
<pre>class MyArgumentParser(argparse.ArgumentParser):
+
<syntaxhighlight lang="python3">class MyArgumentParser(argparse.ArgumentParser):
 
     def convert_arg_line_to_args(self, arg_line):
 
     def convert_arg_line_to_args(self, arg_line):
         return arg_line.split()</pre>
+
         return arg_line.split()</syntaxhighlight>
  
 
</div>
 
</div>
第2,724行: 第2,345行:
 
<div id="exiting-methods" class="section">
 
<div id="exiting-methods" class="section">
  
=== Exiting methods ===
+
=== 退出方法 ===
  
 
<dl>
 
<dl>
<dt><code>ArgumentParser.</code><code>exit</code><span class="sig-paren">(</span>''<span class="n">status</span><span class="o">=</span><span class="default_value">0</span>'', ''<span class="n">message</span><span class="o">=</span><span class="default_value">None</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-prename descclassname"><span class="pre">ArgumentParser.</span></span><span class="sig-name descname"><span class="pre">exit</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">status</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">0</span></span>'', ''<span class="n"><span class="pre">message</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>This method terminates the program, exiting with the specified ''status''
+
<dd><p>此方法终止程序,以指定的 ''状态'' 退出,如果给定,则在此之前打印 ''消息'' 。 用户可以覆盖此方法以不同方式处理这些步骤:</p>
and, if given, it prints a ''message'' before that. The user can override
 
this method to handle these steps differently:</p>
 
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
  
 
<div class="highlight">
 
<div class="highlight">
  
<pre>class ErrorCatchingArgumentParser(argparse.ArgumentParser):
+
<syntaxhighlight lang="python3">class ErrorCatchingArgumentParser(argparse.ArgumentParser):
 
     def exit(self, status=0, message=None):
 
     def exit(self, status=0, message=None):
 
         if status:
 
         if status:
 
             raise Exception(f'Exiting because of an error: {message}')
 
             raise Exception(f'Exiting because of an error: {message}')
         exit(status)</pre>
+
         exit(status)</syntaxhighlight>
  
 
</div>
 
</div>
第2,745行: 第2,364行:
 
</div></dd></dl>
 
</div></dd></dl>
  
; <code>ArgumentParser.</code><code>error</code><span class="sig-paren">(</span>''<span class="n">message</span>''<span class="sig-paren">)</span>
+
; <span class="sig-prename descclassname"><span class="pre">ArgumentParser.</span></span><span class="sig-name descname"><span class="pre">error</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">message</span></span>''<span class="sig-paren">)</span>
: This method prints a usage message including the ''message'' to the standard error and terminates the program with a status code of 2.
+
: 此方法将包含 ''消息'' 的用法消息打印到标准错误,并以状态代码 2 终止程序。
  
  
第2,752行: 第2,371行:
 
<div id="intermixed-parsing" class="section">
 
<div id="intermixed-parsing" class="section">
  
=== Intermixed parsing ===
+
=== 混合解析 ===
  
; <code>ArgumentParser.</code><code>parse_intermixed_args</code><span class="sig-paren">(</span>''<span class="n">args</span><span class="o">=</span><span class="default_value">None</span>'', ''<span class="n">namespace</span><span class="o">=</span><span class="default_value">None</span>''<span class="sig-paren">)</span>
+
; <span class="sig-prename descclassname"><span class="pre">ArgumentParser.</span></span><span class="sig-name descname"><span class="pre">parse_intermixed_args</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">args</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>'', ''<span class="n"><span class="pre">namespace</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>''<span class="sig-paren">)</span>
 
:  
 
:  
  
; <code>ArgumentParser.</code><code>parse_known_intermixed_args</code><span class="sig-paren">(</span>''<span class="n">args</span><span class="o">=</span><span class="default_value">None</span>'', ''<span class="n">namespace</span><span class="o">=</span><span class="default_value">None</span>''<span class="sig-paren">)</span>
+
; <span class="sig-prename descclassname"><span class="pre">ArgumentParser.</span></span><span class="sig-name descname"><span class="pre">parse_known_intermixed_args</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">args</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>'', ''<span class="n"><span class="pre">namespace</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>''<span class="sig-paren">)</span>
 
:  
 
:  
  
A number of Unix commands allow the user to intermix optional arguments with
+
许多 Unix 命令允许用户混合可选参数和位置参数。 [[#argparse.ArgumentParser.parse_intermixed_args|parse_intermixed_args()]] [[#argparse.ArgumentParser.parse_known_intermixed_args|parse_known_intermixed_args()]] 方法支持这种解析风格。
positional arguments. The [[#argparse.ArgumentParser.parse_intermixed_args|<code>parse_intermixed_args()</code>]]
 
and [[#argparse.ArgumentParser.parse_known_intermixed_args|<code>parse_known_intermixed_args()</code>]] methods
 
support this parsing style.
 
  
These parsers do not support all the argparse features, and will raise
+
这些解析器不支持所有 argparse 功能,如果使用了不受支持的功能,则会引发异常。 特别是,不支持子解析器、<code>argparse.REMAINDER</code> 和包含可选和位置的互斥组。
exceptions if unsupported features are used. In particular, subparsers,
 
<code>argparse.REMAINDER</code>, and mutually exclusive groups that include both
 
optionals and positionals are not supported.
 
  
The following example shows the difference between
+
下面的例子展示了 [[#argparse.ArgumentParser.parse_known_args|parse_known_args()]] [[#argparse.ArgumentParser.parse_intermixed_args|parse_intermixed_args()]] 的区别:前者返回 <code>['2', '3']</code> 作为未解析的参数,而后者将所有位置收集到 <code>rest</code>
[[#argparse.ArgumentParser.parse_known_args|<code>parse_known_args()</code>]] and
 
[[#argparse.ArgumentParser.parse_intermixed_args|<code>parse_intermixed_args()</code>]]: the former returns <code>['2', '3']</code> as unparsed arguments, while the latter collects all the positionals
 
into <code>rest</code>.
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第2,779行: 第2,389行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; parser = argparse.ArgumentParser()
+
<syntaxhighlight lang="python3">>>> parser = argparse.ArgumentParser()
&gt;&gt;&gt; parser.add_argument('--foo')
+
>>> parser.add_argument('--foo')
&gt;&gt;&gt; parser.add_argument('cmd')
+
>>> parser.add_argument('cmd')
&gt;&gt;&gt; parser.add_argument('rest', nargs='*', type=int)
+
>>> parser.add_argument('rest', nargs='*', type=int)
&gt;&gt;&gt; parser.parse_known_args('doit 1 --foo bar 2 3'.split())
+
>>> parser.parse_known_args('doit 1 --foo bar 2 3'.split())
 
(Namespace(cmd='doit', foo='bar', rest=[1]), ['2', '3'])
 
(Namespace(cmd='doit', foo='bar', rest=[1]), ['2', '3'])
&gt;&gt;&gt; parser.parse_intermixed_args('doit 1 --foo bar 2 3'.split())
+
>>> parser.parse_intermixed_args('doit 1 --foo bar 2 3'.split())
Namespace(cmd='doit', foo='bar', rest=[1, 2, 3])</pre>
+
Namespace(cmd='doit', foo='bar', rest=[1, 2, 3])</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
[[#argparse.ArgumentParser.parse_known_intermixed_args|<code>parse_known_intermixed_args()</code>]] returns a two item tuple
+
[[#argparse.ArgumentParser.parse_known_intermixed_args|parse_known_intermixed_args()]] 返回一个包含填充的命名空间和剩余参数字符串列表的两项元组。 [[#argparse.ArgumentParser.parse_intermixed_args|parse_intermixed_args()]] 如果还有任何未解析的参数字符串,则会引发错误。
containing the populated namespace and the list of remaining argument strings.
 
[[#argparse.ArgumentParser.parse_intermixed_args|<code>parse_intermixed_args()</code>]] raises an error if there are any
 
remaining unparsed argument strings.
 
  
 
<div class="versionadded">
 
<div class="versionadded">
  
<span class="versionmodified added">3.7 新版功能.</span>
+
<span class="versionmodified added">3.7 版中的新功能。</span>
  
  
第2,808行: 第2,415行:
 
<div id="upgrading-optparse-code" class="section">
 
<div id="upgrading-optparse-code" class="section">
  
<span id="id2"></span>
+
<span id="id4"></span>
== Upgrading optparse code ==
+
== 升级 optparse 代码 ==
  
Originally, the [[#module-argparse|<code>argparse</code>]] module had attempted to maintain compatibility
+
最初,[[#module-argparse|argparse]] 模块试图保持与 [[../optparse#module-optparse|optparse]] 的兼容性。 然而,[[../optparse#module-optparse|optparse]] 很难透明地扩展,特别是在支持新的 <code>nargs=</code> 说明符和更好的使用消息所需的更改时。 当 [[../optparse#module-optparse|optparse]] 中的大部分内容都被复制粘贴或猴子修补时,尝试保持向后兼容性似乎不再可行。
with [[../optparse#module-optparse|<code>optparse</code>]]. However, [[../optparse#module-optparse|<code>optparse</code>]] was difficult to extend
 
transparently, particularly with the changes required to support the new
 
<code>nargs=</code> specifiers and better usage messages. When most everything in
 
[[../optparse#module-optparse|<code>optparse</code>]] had either been copy-pasted over or monkey-patched, it no
 
longer seemed practical to try to maintain the backwards compatibility.
 
  
The [[#module-argparse|<code>argparse</code>]] module improves on the standard library [[../optparse#module-optparse|<code>optparse</code>]]
+
[[#module-argparse|argparse]] 模块以多种方式改进了标准库 [[../optparse#module-optparse|optparse]] 模块,包括:
module in a number of ways including:
 
  
* Handling positional arguments.
+
* 处理位置参数。
* Supporting sub-commands.
+
* 支持子命令。
* Allowing alternative option prefixes like <code>+</code> and <code>/</code>.
+
* 允许替代选项前缀,如 <code>+</code> <code>/</code>
* Handling zero-or-more and one-or-more style arguments.
+
* 处理零个或多个和一个或多个样式参数。
* Producing more informative usage messages.
+
* 生成更多信息丰富的使用消息。
* Providing a much simpler interface for custom <code>type</code> and <code>action</code>.
+
* 为自定义 <code>type</code> <code>action</code> 提供更简单的界面。
  
A partial upgrade path from [[../optparse#module-optparse|<code>optparse</code>]] to [[#module-argparse|<code>argparse</code>]]:
+
[[../optparse#module-optparse|optparse]] [[#module-argparse|argparse]] 的部分升级路径:
  
* Replace all [[../optparse#optparse.OptionParser|<code>optparse.OptionParser.add_option()</code>]] calls with [[#argparse.ArgumentParser.add_argument|<code>ArgumentParser.add_argument()</code>]] calls.
+
* 将所有 [[../optparse#optparse.OptionParser|optparse.OptionParser.add_option()]] 调用替换为 [[#argparse.ArgumentParser.add_argument|ArgumentParser.add_argument()]] 调用。
* Replace <code>(options, args) = parser.parse_args()</code> with <code>args = parser.parse_args()</code> and add additional [[#argparse.ArgumentParser.add_argument|<code>ArgumentParser.add_argument()</code>]] calls for the positional arguments. Keep in mind that what was previously called <code>options</code>, now in the [[#module-argparse|<code>argparse</code>]] context is called <code>args</code>.
+
* <code>(options, args) = parser.parse_args()</code> 替换为 <code>args = parser.parse_args()</code>,并为位置参数添加额外的 [[#argparse.ArgumentParser.add_argument|ArgumentParser.add_argument()]] 调用。 请记住,以前称为 <code>options</code>,现在在 [[#module-argparse|argparse]] 上下文中称为 <code>args</code>
* Replace [[../optparse#optparse.OptionParser|<code>optparse.OptionParser.disable_interspersed_args()</code>]] by using [[#argparse.ArgumentParser.parse_intermixed_args|<code>parse_intermixed_args()</code>]] instead of [[#argparse.ArgumentParser.parse_args|<code>parse_args()</code>]].
+
* 使用 [[#argparse.ArgumentParser.parse_intermixed_args|parse_intermixed_args()]] 代替 [[#argparse.ArgumentParser.parse_args|parse_args()]] 替换 [[../optparse#optparse.OptionParser|optparse.OptionParser.disable_interspersed_args()]]
* Replace callback actions and the <code>callback_*</code> keyword arguments with <code>type</code> or <code>action</code> arguments.
+
* 将回调操作和 <code>callback_*</code> 关键字参数替换为 <code>type</code> <code>action</code> 参数。
* Replace string names for <code>type</code> keyword arguments with the corresponding type objects (e.g. int, float, complex, etc).
+
* <code>type</code> 关键字参数的字符串名称替换为相应的类型对象(例如 int、float、complex 等)。
* Replace <code>optparse.Values</code> with [[#argparse.Namespace|<code>Namespace</code>]] and <code>optparse.OptionError</code> and <code>optparse.OptionValueError</code> with <code>ArgumentError</code>.
+
* <code>optparse.Values</code> 替换为 [[#argparse.Namespace|命名空间]] ,将 <code>optparse.OptionError</code> <code>optparse.OptionValueError</code> 替换为 <code>ArgumentError</code>
* Replace strings with implicit arguments such as <code>%default</code> or <code>%prog</code> with the standard Python syntax to use dictionaries to format strings, that is, <code>%(default)s</code> and <code>%(prog)s</code>.
+
* 将带有隐式参数的字符串(例如 <code>%default</code> <code>%prog</code>)替换为标准 Python 语法,以使用字典来格式化字符串,即 <code>%(default)s</code> <code>%(prog)s</code>
* Replace the OptionParser constructor <code>version</code> argument with a call to <code>parser.add_argument('--version', action='version', version='&lt;the version&gt;')</code>.
+
* OptionParser 构造函数 <code>version</code> 参数替换为对 <code>parser.add_argument('--version', action='version', version='&lt;the version&gt;')</code> 的调用。
  
  
 
</div>
 
</div>
 +
 +
</div>
 +
<div class="clearer">
 +
 +
  
 
</div>
 
</div>
  
[[Category:Python 3.9 中文文档]]
+
[[Category:Python 3.9 文档]]

2021年10月31日 (日) 04:51的最新版本

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

3.2 版中的新功能。


源代码: :source:`Lib/argparse.py`



教程

此页面包含 API 参考信息。 有关 Python 命令行解析的更温和的介绍,请查看 argparse 教程

argparse 模块使编写用户友好的命令行界面变得容易。 该程序定义了它需要哪些参数,argparse 将找出如何从 sys.argv 中解析出这些参数。 argparse 模块还自动生成帮助和使用消息,并在用户给程序提供无效参数时发出错误。

例子

下面的代码是一个 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 的第一步是创建一个 ArgumentParser 对象:

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

ArgumentParser 对象将保存将命令行解析为 Python 数据类型所需的所有信息。


添加参数

用有关程序参数的信息填充 ArgumentParser 是通过调用 add_argument() 方法来完成的。 通常,这些调用会告诉 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() 将返回一个具有两个属性的对象,integersaccumulateintegers 属性将是一个或多个整数的列表,accumulate 属性将是 sum() 函数,如果 --sum 是在命令行中指定,如果不是,则在 max() 函数中指定。


解析参数

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

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

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


ArgumentParser 对象

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

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

  • prog - 程序名称(默认:sys.argv[0]

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

  • description - 在参数帮助之前显示的文本(默认值:无)

  • epilog - 参数帮助后显示的文本(默认值:无)

  • parents - ArgumentParser 对象的列表,其参数也应包括在内

  • formatter_class - 自定义帮助输出的类

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

  • fromfile_prefix_chars - 应该从中读取附加参数的文件前缀字符集(默认值:None

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

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

  • add_help - 向解析器添加 -h/--help 选项(默认:True

  • allow_abbrev - 如果缩写是明确的,则允许缩写长选项。 (默认:True

  • exit_on_error - 确定发生错误时 ArgumentParser 是否退出并显示错误信息。 (默认:True

3.5 版更改:添加了 allow_abbrev 参数。

3.8 版更改: 在之前的版本中,allow_abbrev 还禁用了对诸如 -vv 之类的短标志分组以表示 -v -v

3.9 版更改:添加了 exit_on_error 参数。

以下各节描述了如何使用它们中的每一个。

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

要更改此默认行为,可以使用 ArgumentParserprog= 参数提供另一个值:

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

用法

默认情况下,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 格式说明符可用于在您的使用消息中填写程序名称。


描述

大多数对 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

默认情况下,描述将被换行以适应给定的空间。 要更改此行为,请参阅 formatter_class 参数。


结语

一些程序喜欢在参数描述之后显示程序的附加描述。 可以使用 ArgumentParserepilog= 参数指定此类文本:

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

A foo that bars

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

And that's how you'd foo a bar

description 参数一样,epilog= 文本默认为换行,但可以使用 formatter_class 参数调整 ArgumentParser ]。


父母

有时,多个解析器共享一组公共参数。 不是重复这些参数的定义,而是可以使用具有所有共享参数并传递给 parents= 参数到 ArgumentParser 的单个解析器。 parents= 参数采用 ArgumentParser 对象列表,从中收集所有位置和可选操作,并将这些操作添加到正在构造的 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。 否则, ArgumentParser 将看到两个 -h/--help 选项(一个在父级中,一个在子级中)并引发错误。

笔记

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


格式化程序类

ArgumentParser 对象允许通过指定替代格式类来自定义帮助格式。 目前,有四个这样的类:

class argparse.RawDescriptionHelpFormatter

class argparse.RawTextHelpFormatter
class argparse.ArgumentDefaultsHelpFormatter
class argparse.MetavarTypeHelpFormatter

RawDescriptionHelpFormatterRawTextHelpFormatter 可以更好地控制文本描述的显示方式。 默认情况下,ArgumentParser 对象对命令行帮助消息中的 descriptionepilog 文本进行换行:

>>> 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 作为 formatter_class= 传递表示 descriptionepilog 已正确格式化,不应换行:

>>> 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 为各种帮助文本保留空格,包括参数描述。 但是,多个新行被替换为一个。 如果您希望保留多个空行,请在换行符之间添加空格。

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

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

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

MetavarTypeHelpFormatter 使用每个参数的 type 参数的名称作为其值的显示名称(而不是像常规格式化程序那样使用 dest):

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

positional arguments:
  float

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

前缀字符

大多数命令行选项将使用 - 作为前缀,例如 -f/--foo。 需要支持不同或额外前缀字符的解析器,例如 对于 +f/foo 之类的选项,可以使用 prefix_chars= 参数给 ArgumentParser 构造函数指定它们:

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

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


fromfile_prefix_chars

有时,例如在处理特别长的参数列表时,将参数列表保存在文件中而不是在命令行中输入可能更有意义。 如果将 fromfile_prefix_chars= 参数提供给 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()),并被视为与原始文件引用参数在命令行上的位置相同。 所以在上面的例子中,表达式 ['-f', 'foo', '@args.txt'] 被认为等价于表达式 ['-f', 'foo', '-f', 'bar']

fromfile_prefix_chars= 参数默认为 None,这意味着参数永远不会被视为文件引用。


参数_默认值

通常,通过将默认值传递给 add_argument() 或通过使用一组特定的名称-值对调用 set_defaults() 方法来指定参数默认值。 然而,有时为参数指定单个解析器范围的默认值可能很有用。 这可以通过将 argument_default= 关键字参数传递给 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

通常,当您将参数列表传递给 ArgumentParserparse_args() 方法时,它 识别长选项的缩写

可以通过将 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 版中的新功能。


冲突处理程序

ArgumentParser 对象不允许具有相同选项字符串的两个操作。 默认情况下,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) 时,用相同的选项字符串简单地覆盖任何旧参数可能很有用。 要获得此行为,可以将值 'resolve' 提供给 ArgumentParserconflict_handler= 参数:

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

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

请注意, ArgumentParser 对象仅在其所有选项字符串都被覆盖时删除操作。 因此,在上面的示例中,旧的 -f/--foo 操作保留为 -f 操作,因为只有 --foo 选项字符串被覆盖。


添加帮助

默认情况下, ArgumentParser 对象添加一个选项,该选项仅显示解析器的帮助消息。 例如,考虑一个名为 myprogram.py 的文件,其中包含以下代码:

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

如果在命令行提供 -h--help,将打印 ArgumentParser 帮助:

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

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

有时,禁用此帮助选项的添加可能会很有用。 这可以通过将 False 作为 add_help= 参数传递给 ArgumentParser 来实现:

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

exit_on_error

通常,当您将无效参数列表传递给 ArgumentParserparse_args() 方法时,它将退出并显示错误信息。

如果用户想手动捕获错误,可以通过将 exit_on_error 设置为 False 来启用该功能:

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

3.9 版中的新功能。


add_argument() 方法

ArgumentParser.add_argument(name or flags...[, action][, nargs][, const][, default][, type][, choices][, required][, help][, metavar][, dest])
定义应如何解析单个命令行参数。 每个参数在下面都有更详细的描述,但简而言之,它们是:
  • name 或 flags - 名称或选项字符串列表,例如 foo-f, --foo
  • action - 在命令行遇到此参数时要采取的基本操作类型。
  • nargs - 应该使用的命令行参数的数量。
  • const - 某些 actionnargs 选择所需的常量值。
  • default - 命令行中不存在参数并且命名空间对象中不存在时产生的值。
  • type - 命令行参数应转换为的类型。
  • choices - 参数允许值的容器。
  • required - 是否可以省略命令行选项(仅限可选)。
  • help - 对参数作用的简要描述。
  • metavar - 使用消息中参数的名称。
  • dest - 要添加到 parse_args() 返回的对象的属性名称。

以下各节描述了如何使用它们中的每一个。

名称或标志

add_argument() 方法必须知道是否需要可选参数(如 -f--foo)或位置参数(如文件名列表)。 因此,传递给 add_argument() 的第一个参数必须是一系列标志或一个简单的参数名称。 例如,可以创建一个可选参数,如:

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

虽然可以创建位置参数,例如:

>>> parser.add_argument('bar')

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

行动

ArgumentParser 对象将命令行参数与操作相关联。 这些操作几乎可以使用与其关联的命令行参数执行任何操作,尽管大多数操作只是向 parse_args() 返回的对象添加一个属性。 action 关键字参数指定应如何处理命令行参数。 提供的操作是:

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

    >>> parser = argparse.ArgumentParser()
    >>> parser.add_argument('--foo')
    >>> parser.parse_args('--foo 1'.split())
    Namespace(foo='1')
  • 'store_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''store_false' - 这些是 'store_const' 的特例,分别用于存储值 TrueFalse。 此外,它们分别创建 FalseTrue 的默认值。 例如:

    >>> parser = argparse.ArgumentParser()
    >>> parser.add_argument('--foo', action='store_true')
    >>> parser.add_argument('--bar', action='store_false')
    >>> parser.add_argument('--baz', action='store_false')
    >>> parser.parse_args('--foo --bar'.split())
    Namespace(foo=True, bar=False, baz=True)
  • 'append' - 存储一个列表,并将每个参数值附加到列表中。 这对于允许多次指定一个选项很有用。 用法示例:

    >>> 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 关键字参数默认为 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', default=0)
    >>> parser.parse_args(['-vvv'])
    Namespace(verbose=3)

    请注意,除非明确设置为 0,否则 默认 将为 None

  • 'help' - 这会打印当前解析器中所有选项的完整帮助消息,然后退出。 默认情况下,帮助操作会自动添加到解析器中。 有关如何创建输出的详细信息,请参阅 ArgumentParser

  • 'version' - 这需要 add_argument() 调用中的 version= 关键字参数,并在调用时打印版本信息并退出:

    >>> import argparse
    >>> parser = argparse.ArgumentParser(prog='PROG')
    >>> parser.add_argument('--version', action='version', version='%(prog)s 2.0')
    >>> parser.parse_args(['--version'])
    PROG 2.0
  • 'extend' - 这存储一个列表,并将每个参数值扩展到列表。 用法示例:

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

    3.8 版中的新功能。

您还可以通过传递实现相同接口的 Action 子类或其他对象来指定任意操作。 BooleanOptionalActionargparse 中可用,并添加了对布尔操作的支持,例如 --foo--no-foo

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

3.9 版中的新功能。


创建自定义操作的推荐方法是扩展 Action,覆盖 __call__ 方法和可选的 __init__format_usage 方法。

自定义操作的示例:

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

详情请参见动作


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 中的值。 请注意,对于可选参数,还有一种情况 - 选项字符串存在但后面没有命令行参数。 在这种情况下,将产生来自 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='*' 拥有多个位置参数通常没有多大意义,但使用 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

如果未提供 nargs 关键字参数,则消耗的参数数量由 action 决定。 通常这意味着将使用单个命令行参数并生成单个项目(不是列表)。


常量

add_argument()const 参数用于保存不是从命令行读取但各种 ArgumentParser 操作所需的常量值。 它的两个最常见用途是:

  • 当使用 action='store_const'action='append_const' 调用 add_argument() 时。 这些操作将 const 值添加到 parse_args() 返回的对象属性之一。 有关示例,请参阅 action 说明。
  • 当使用选项字符串(如 -f--foo)和 nargs='?' 调用 add_argument() 时。 这将创建一个可选参数,其后可以跟零个或一个命令行参数。 解析命令行时,如果遇到选项字符串后面没有命令行参数,则将假定 const 的值。 有关示例,请参阅 nargs 说明。

对于 'store_const''append_const' 操作,必须给出 const 关键字参数。 其他动作默认为None


默认

在命令行中可以省略所有可选参数和一些位置参数。 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 不会覆盖它:

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

如果 default 值是一个字符串,解析器将解析该值,就好像它是一个命令行参数一样。 特别是,解析器在设置 Namespace 返回值的属性之前应用任何 type 转换参数(如果提供)。 否则,解析器按原样使用该值:

>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--length', default='10', type=int)
>>> parser.add_argument('--width', default=10.5, type=int)
>>> parser.parse_args()
Namespace(length=10, width=10.5)

对于 nargs 等于 ?* 的位置参数,当不存在命令行参数时使用 default 值:

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

类型

默认情况下,解析器以简单字符串的形式读取命令行参数。 但是,命令行字符串通常应该被解释为另一种类型,例如 floatintadd_argument()type 关键字允许执行任何必要的类型检查和类型转换。

如果 type 关键字与 default 关键字一起使用,则仅当默认值为字符串时才应用类型转换器。

type 的参数可以是任何接受单个字符串的可调用对象。 如果函数引发 ArgumentTypeErrorTypeErrorValueError,则会捕获异常并显示格式良好的错误消息。 不处理其他异常类型。

常见的内置类型和函数可以用作类型转换器:

import argparse
import pathlib

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

也可以使用用户定义的函数:

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

bool() 函数不推荐作为类型转换器。 它所做的只是将空字符串转换为 False,将非空字符串转换为 True。 这通常不是所希望的。

通常,type 关键字是一种便利,应该仅用于只能引发三种受支持异常之一的简单转换。 在解析参数后,任何更有趣的错误处理或资源管理都应该在下游完成。

例如,JSON 或 YAML 转换具有复杂的错误情况,需要比 type 关键字提供更好的报告。 JSONDecodeError 的格式不会很好,并且根本不会处理 FileNotFound 异常。

甚至 FileType 也有其与 type 关键字一起使用的限制。 如果一个参数使用 FileType 并且随后的参数失败,则会报告错误但不会自动关闭文件。 在这种情况下,最好等到解析器运行后,然后使用 with 语句来管理文件。

对于仅针对一组固定值进行检查的类型检查器,请考虑改用 choices 关键字。


选择

一些命令行参数应该从一组受限制的值中选择。 这些可以通过将容器对象作为 choices 关键字参数传递给 add_argument() 来处理。 解析命令行时,将检查参数值,如果参数不是可接受的值之一,则会显示错误消息:

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

请注意,在执行任何 type 转换后检查是否包含在 choices 容器中,因此 choices 容器中的对象类型应与 匹配]type 指定:

>>> parser = argparse.ArgumentParser(prog='doors.py')
>>> parser.add_argument('door', type=int, choices=range(1, 4))
>>> print(parser.parse_args(['3']))
Namespace(door=3)
>>> parser.parse_args(['4'])
usage: doors.py [-h] {1,2,3}
doors.py: error: argument door: invalid choice: 4 (choose from 1, 2, 3)

任何容器都可以作为 choices 值传递,所以 list 对象、set 对象和自定义容器都被支持。

不推荐使用 enum.Enum,因为它很难控制它在使用、帮助和错误消息中的外观。

格式化选项会覆盖默认的 metavar,它通常派生自 dest。 这通常是您想要的,因为用户永远不会看到 dest 参数。 如果这种显示不是可取的(可能是因为有很多选择),只需指定一个明确的 metavar


必需的

通常,argparse 模块假设像 -f--bar 表示 optional 参数,这些参数在命令行中总是可以省略的。 要使选项 required,可以为 add_argument()required= 关键字参数指定 True

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

如示例所示,如果一个选项被标记为 required,如果命令行中不存在该选项,则 parse_args() 将报告错误。

笔记

必需的选项通常被认为是不好的形式,因为用户希望 optionsoptional,因此应该尽可能避免它们。


帮助

help 值是一个包含参数简要描述的字符串。 当用户请求帮助时(通常通过在命令行使用 -h--help),这些 help 描述将与每个参数一起显示:

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

positional arguments:
 bar     one of the bars to be frobbled

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

help 字符串可以包含各种格式说明符,以避免重复诸如程序名称或参数 default 之类的内容。 可用的说明符包括程序名称、%(prog)sadd_argument() 的大多数关键字参数,例如 %(default)s%(type)s 等:

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

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

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

由于帮助字符串支持 %-f 格式,如果您希望文字 % 出现在帮助字符串中,则必须将其转义为 %%

argparse 通过将 help 值设置为 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

元变量

ArgumentParser 生成帮助消息时,它需要某种方式来引用每个预期的参数。 默认情况下,ArgumentParser 对象使用 dest 值作为每个对象的“名称”。 默认情况下,对于位置参数动作,直接使用 dest 值,对于可选参数动作,dest 值是大写的。 因此,带有 dest='bar' 的单个位置参数将被称为 bar。 单个可选参数 --foo 后面应该跟一个命令行参数将被称为 FOO。 一个例子:

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

positional arguments:
 bar

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

可以使用 metavar 指定替代名称:

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

positional arguments:
 XXX

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

请注意,metavar 仅更改 displayed 名称 - parse_args() 对象上的属性名称仍由 dest 值决定.

nargs 的不同值可能会导致元变量被多次使用。 为 metavar 提供一个元组为每个参数指定不同的显示:

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

目的地

大多数 ArgumentParser 操作添加一些值作为 parse_args() 返回的对象的属性。 该属性的名称由 add_argument()dest 关键字参数决定。 对于位置参数操作,dest 通常作为第一个参数提供给 add_argument()

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

对于可选参数操作,dest 的值通常是从选项字符串中推断出来的。 ArgumentParser 通过取第一个长选项字符串并剥离初始 -- 字符串来生成 dest 的值。 如果未提供长选项字符串,则 dest 将通过剥离初始 - 字符从第一个短选项字符串派生。 任何内部 - 字符都将转换为 _ 字符以确保字符串是有效的属性名称。 下面的示例说明了这种行为:

>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('-f', '--foo-bar', '--foo')
>>> parser.add_argument('-x', '-y')
>>> parser.parse_args('-f 1 -x 2'.split())
Namespace(foo_bar='1', x='2')
>>> parser.parse_args('--foo 1 -y 2'.split())
Namespace(foo_bar='1', x='2')

dest 允许提供自定义属性名称:

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

动作类

Action 类实现了 Action API,这是一个可调用的,它返回一个可调用的,它处理来自命令行的参数。 任何遵循此 API 的对象都可以作为 action 参数传递给 add_argument()

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

ArgumentParser 使用 Action 对象来表示从命令行中的一个或多个字符串解析单个参数所需的信息。 Action 类必须接受两个位置参数以及传递给 ArgumentParser.add_argument() 的任何关键字参数,除了 action 本身。

Action 实例(或任何可调用 action 参数的返回值)应具有属性“dest”、“option_strings”、“default”、“type”、“required”、“help”等。 定义。 确保定义这些属性的最简单方法是调用 Action.__init__

Action 实例应该是可调用的,因此子类必须覆盖 __call__ 方法,该方法应该接受四个参数:

  • parser - 包含此操作的 ArgumentParser 对象。
  • namespace - parse_args() 将返回的 Namespace 对象。 大多数操作使用 setattr() 向该对象添加属性。
  • values - 关联的命令行参数,应用了任何类型转换。 类型转换使用 add_argument()type 关键字参数指定。
  • option_string - 用于调用此操作的选项字符串。 option_string 参数是可选的,如果操作与位置参数相关联,则该参数将不存在。

__call__ 方法可以执行任意操作,但通常会根据 destvaluesnamespace 上设置属性。

Action 子类可以定义一个 format_usage 方法,该方法不带参数并返回一个字符串,该字符串将在打印程序的用法时使用。 如果未提供此类方法,则将使用合理的默认值。


parse_args() 方法

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

将参数字符串转换为对象并将它们分配为命名空间的属性。 返回填充的命名空间。

之前对 add_argument() 的调用确定了创建哪些对象以及如何分配它们。 有关详细信息,请参阅 add_argument() 的文档。

  • args - 要解析的字符串列表。 默认值取自 sys.argv

  • namespace - 获取属性的对象。 默认值是一个新的空 Namespace 对象。

选项值语法

parse_args() 方法支持多种指定选项值的方法(如果需要的话)。 在最简单的情况下,选项及其值作为两个单独的参数传递:

>>> parser = argparse.ArgumentParser(prog='PROG')
>>> parser.add_argument('-x')
>>> parser.add_argument('--foo')
>>> parser.parse_args(['-x', 'X'])
Namespace(foo=None, x='X')
>>> parser.parse_args(['--foo', 'FOO'])
Namespace(foo='FOO', x=None)

对于长选项(名称长于单个字符的选项),选项和值也可以作为单个命令行参数传递,使用 = 将它们分开:

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

对于短选项(选项只有一个字符长),可以连接选项及其值:

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

几个短选项可以连接在一起,只使用一个 - 前缀,只要最后一个选项(或没有一个)需要一个值:

>>> parser = argparse.ArgumentParser(prog='PROG')
>>> parser.add_argument('-x', action='store_true')
>>> parser.add_argument('-y', action='store_true')
>>> parser.add_argument('-z')
>>> parser.parse_args(['-xyzZ'])
Namespace(x=True, y=True, z='Z')

无效参数

在解析命令行时,parse_args() 会检查各种错误,包括歧义选项、无效类型、无效选项、位置参数数量错误等。 当它遇到这样的错误时,它会退出并打印错误以及使用信息:

>>> parser = argparse.ArgumentParser(prog='PROG')
>>> parser.add_argument('--foo', type=int)
>>> parser.add_argument('bar', nargs='?')

>>> # invalid type
>>> parser.parse_args(['--foo', 'spam'])
usage: PROG [-h] [--foo FOO] [bar]
PROG: error: argument --foo: invalid int value: 'spam'

>>> # invalid option
>>> parser.parse_args(['--bar'])
usage: PROG [-h] [--foo FOO] [bar]
PROG: error: no such option: --bar

>>> # wrong number of arguments
>>> parser.parse_args(['spam', 'badger'])
usage: PROG [-h] [--foo FOO] [bar]
PROG: error: extra arguments found: badger

包含 - 的参数

parse_args() 方法试图在用户明显犯了错误时给出错误,但有些情况本质上是模棱两可的。 例如,命令行参数 -1 可能是尝试指定选项或尝试提供位置参数。 parse_args() 方法在这里是谨慎的:位置参数只能以 - 开头,如果它们看起来像负数并且解析器中没有看起来像负数的选项:

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

如果您的位置参数必须以 - 开头并且看起来不像负数,则可以插入伪参数 '--',它告诉 parse_args()之后是位置参数:

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

参数缩写(前缀匹配)

parse_args() 方法 默认情况下 允许将长选项缩写为前缀,如果缩写是明确的(前缀匹配唯一选项):

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

产生多个选项的参数会产生错误。 可以通过将 allow_abbrev 设置为 False 来禁用此功能。


超越sys.argv

有时,让 ArgumentParser 解析除 sys.argv 之外的参数可能会很有用。 这可以通过将字符串列表传递给 parse_args() 来完成。 这对于在交互式提示下进行测试很有用:

>>> parser = argparse.ArgumentParser()
>>> parser.add_argument(
...     'integers', metavar='int', type=int, choices=range(10),
...     nargs='+', help='an integer in the range 0..9')
>>> parser.add_argument(
...     '--sum', dest='accumulate', action='store_const', const=sum,
...     default=max, help='sum the integers (default: find the max)')
>>> parser.parse_args(['1', '2', '3', '4'])
Namespace(accumulate=<built-in function max>, integers=[1, 2, 3, 4])
>>> parser.parse_args(['1', '2', '3', '4', '--sum'])
Namespace(accumulate=<built-in function sum>, integers=[1, 2, 3, 4])

命名空间对象

class argparse.Namespace
parse_args() 默认使用的简单类来创建一个包含属性的对象并返回它。

这个类故意简单,只是一个具有可读字符串表示的 object 子类。 如果您更喜欢类似 dict 的属性视图,您可以使用标准的 Python 习语,vars()

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

ArgumentParser 将属性分配给已经存在的对象,而不是新的 Namespace 对象也可能很有用。 这可以通过指定 namespace= 关键字参数来实现:

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

其他公用事业

子命令

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

许多程序将它们的功能拆分为多个子命令,例如,svn 程序可以调用子命令,如 svn checkoutsvn update 和 [ X168X]。 当程序执行需要不同类型命令行参数的多个不同功能时,以这种方式拆分功能可能是一个特别好的主意。 ArgumentParser 支持使用 add_subparsers() 方法创建此类子命令。 add_subparsers() 方法通常不带参数调用,并返回一个特殊的动作对象。 这个对象有一个方法,add_parser(),它接受一个命令名称和任何 ArgumentParser 构造函数参数,并返回一个可以像往常一样修改的 ArgumentParser 对象。

参数说明:

  • title - 帮助输出中子解析器组的标题; 默认情况下“子命令”如果提供了描述,否则使用标题作为位置参数

  • description - 帮助输出中子解析器组的描述,默认情况下 None

  • prog - 将与子命令帮助一起显示的使用信息,默认情况下程序的名称和 subparser 参数之前的任何位置参数

  • parser_class - 将用于创建子解析器实例的类,默认情况下当前解析器的类(例如 参数解析器)

  • action - 在命令行遇到此参数时要采取的基本操作类型

  • dest - 将存储子命令名称的属性名称; 默认 None 并且不存储任何值

  • required - 是否必须提供子命令,默认情况下 False(在 3.7 中添加)

  • help - 帮助输出中子解析器组的帮助,默认情况下 None

  • metavar - 在帮助中显示可用子命令的字符串; 默认情况下它是 None 并以 {cmd1, cmd2, ..} 形式呈现子命令

一些示例用法:

>>> # create the top-level parser
>>> parser = argparse.ArgumentParser(prog='PROG')
>>> parser.add_argument('--foo', action='store_true', help='foo help')
>>> subparsers = parser.add_subparsers(help='sub-command help')
>>>
>>> # create the parser for the "a" command
>>> parser_a = subparsers.add_parser('a', help='a help')
>>> parser_a.add_argument('bar', type=int, help='bar help')
>>>
>>> # create the parser for the "b" command
>>> parser_b = subparsers.add_parser('b', help='b help')
>>> parser_b.add_argument('--baz', choices='XYZ', help='baz help')
>>>
>>> # parse some argument lists
>>> parser.parse_args(['a', '12'])
Namespace(bar=12, foo=False)
>>> parser.parse_args(['--foo', 'b', '--baz', 'Z'])
Namespace(baz='Z', foo=True)

请注意, parse_args() 返回的对象将仅包含主解析器和命令行选择的子解析器(而不是任何其他子解析器)的属性。 所以在上面的例子中,当指定a命令时,只有foobar属性存在,而当指定b命令时,仅存在 foobaz 属性。

类似地,当从子解析器请求帮助消息时,只会打印该特定解析器的帮助。 帮助消息将不包括父解析器或兄弟解析器消息。 (但是,可以通过将 help= 参数提供给上述 add_parser() 来给出每个子解析器命令的帮助消息。)

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

add_subparsers() 方法还支持 titledescription 关键字参数。 当存在任何一个时,子解析器的命令将出现在帮助输出中它们自己的组中。 例如:

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

此外,add_parser 支持额外的 aliases 参数,它允许多个字符串引用同一个子解析器。 这个例子,像 svn,别名 co 作为 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')

处理子命令的一种特别有效的方法是将 add_subparsers() 方法的使用与对 set_defaults() 的调用结合起来,以便每个子解析器知道它应该执行哪个 Python 函数。 例如:

>>> # sub-command functions
>>> def foo(args):
...     print(args.x * args.y)
...
>>> def bar(args):
...     print('((%s))' % args.z)
...
>>> # create the top-level parser
>>> parser = argparse.ArgumentParser()
>>> subparsers = parser.add_subparsers()
>>>
>>> # create the parser for the "foo" command
>>> parser_foo = subparsers.add_parser('foo')
>>> parser_foo.add_argument('-x', type=int, default=1)
>>> parser_foo.add_argument('y', type=float)
>>> parser_foo.set_defaults(func=foo)
>>>
>>> # create the parser for the "bar" command
>>> parser_bar = subparsers.add_parser('bar')
>>> parser_bar.add_argument('z')
>>> parser_bar.set_defaults(func=bar)
>>>
>>> # parse the args and call whatever function was selected
>>> args = parser.parse_args('foo 1 -x 2'.split())
>>> args.func(args)
2.0
>>>
>>> # parse the args and call whatever function was selected
>>> args = parser.parse_args('bar XYZYX'.split())
>>> args.func(args)
((XYZYX))

这样,您可以让 parse_args() 在参数解析完成后执行调用适当函数的工作。 将函数与这样的动作相关联通常是处理每个子解析器不同动作的最简单方法。 但是,如果需要检查被调用的子解析器的名称,add_subparsers() 调用的 dest 关键字参数将起作用:

>>> parser = argparse.ArgumentParser()
>>> subparsers = parser.add_subparsers(dest='subparser_name')
>>> subparser1 = subparsers.add_parser('1')
>>> subparser1.add_argument('-x')
>>> subparser2 = subparsers.add_parser('2')
>>> subparser2.add_argument('y')
>>> parser.parse_args(['2', 'frobble'])
Namespace(subparser_name='2', y='frobble')

在 3.7 版更改:新增 required 关键字参数。


文件类型对象

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

FileType 工厂创建可以传递给 ArgumentParser.add_argument() 的类型参数的对象。 将 FileType 对象作为其类型的参数将打开命令行参数作为具有请求模式、缓冲区大小、编码和错误处理的文件(有关更多详细信息,请参阅 open() 函数):

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

FileType 对象理解伪参数 '-' 并自动将其转换为 sys.stdin 可读 FileType 对象和 sys.stdout 可写 FileType对象:

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

3.4 版新功能:encodingserrors 关键字参数。


参数组

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

默认情况下,ArgumentParser 在显示帮助消息时将命令行参数分为“位置参数”和“可选参数”。 当存在比默认参数更好的概念分组时,可以使用 add_argument_group() 方法创建适当的组:

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

group:
  bar    bar help
  --foo FOO  foo help

add_argument_group() 方法返回一个参数组对象,它有一个 add_argument() 方法,就像一个常规的 ArgumentParser。 将参数添加到组中时,解析器会将其视为普通参数,但会在单独的组中显示该参数以获取帮助消息。 add_argument_group() 方法接受 titledescription 参数,可用于自定义此显示:

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

请注意,任何不在用户定义组中的参数最终都会回到通常的“位置参数”和“可选参数”部分。


相互排斥

ArgumentParser.add_mutually_exclusive_group(required=False)

创建一个互斥组。 argparse 将确保在互斥组中只有一个参数出现在命令行上:

>>> 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() 方法还接受 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()titledescription 参数。


解析器默认值

ArgumentParser.set_defaults(**kwargs)

大多数情况下,parse_args() 返回的对象的属性将通过检查命令行参数和参数操作来完全确定。 set_defaults() 允许添加一些无需检查命令行即可确定的其他属性:

>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('foo', type=int)
>>> parser.set_defaults(bar=42, baz='badger')
>>> parser.parse_args(['736'])
Namespace(bar=42, baz='badger', foo=736)

请注意,解析器级别的默认值始终覆盖参数级别的默认值:

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

当使用多个解析器时,解析器级别的默认值特别有用。 有关此类型的示例,请参阅 add_subparsers() 方法。

ArgumentParser.get_default(dest)

获取命名空间属性的默认值,由 add_argument()set_defaults() 设置:

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


打印帮助

在大多数典型应用程序中, parse_args() 将负责格式化和打印任何用法或错误消息。 但是,有几种格式化方法可用:

ArgumentParser.print_usage(file=None)
打印有关如何在命令行上调用 ArgumentParser 的简要说明。 如果 fileNone,则假定为 sys.stdout
ArgumentParser.print_help(file=None)
打印一条帮助消息,包括程序使用情况和有关使用 ArgumentParser 注册的参数的信息。 如果 fileNone,则假定为 sys.stdout

这些方法还有一些变体,它们只是返回一个字符串而不是打印它:

ArgumentParser.format_usage()
返回一个字符串,其中包含有关如何在命令行上调用 ArgumentParser 的简要说明。
ArgumentParser.format_help()
返回一个包含帮助消息的字符串,包括程序使用情况和有关使用 ArgumentParser 注册的参数的信息。


部分解析

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

有时一个脚本可能只解析几个命令行参数,将剩余的参数传递给另一个脚本或程序。 在这些情况下,parse_known_args() 方法会很有用。 它的工作方式与 parse_args() 非常相似,不同之处在于它在存在额外参数时不会产生错误。 相反,它返回一个包含填充的命名空间和剩余参数字符串列表的两项元组。

>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo', action='store_true')
>>> parser.add_argument('bar')
>>> parser.parse_known_args(['--foo', '--badger', 'BAR', 'spam'])
(Namespace(bar='BAR', foo=True), ['--badger', 'spam'])

警告

前缀匹配规则适用于parse_known_args()。 解析器可能会使用一个选项,即使它只是其已知选项之一的前缀,而不是将它留在剩余的参数列表中。


自定义文件解析

ArgumentParser.convert_arg_line_to_args(arg_line)

从文件中读取的参数(请参阅 ArgumentParser 构造函数的 fromfile_prefix_chars 关键字参数)每行读取一个参数。 convert_arg_line_to_args() 可以被覆盖以进行更高级的阅读。

此方法采用单个参数 arg_line,它是从参数文件中读取的字符串。 它返回从此字符串解析的参数列表。 该方法按顺序从参数文件中读取的每一行调用一次。

此方法的一个有用覆盖是将每个空格分隔的单词视为参数。 以下示例演示了如何执行此操作:

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


退出方法

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

此方法终止程序,以指定的 状态 退出,如果给定,则在此之前打印 消息 。 用户可以覆盖此方法以不同方式处理这些步骤:

class ErrorCatchingArgumentParser(argparse.ArgumentParser):
    def exit(self, status=0, message=None):
        if status:
            raise Exception(f'Exiting because of an error: {message}')
        exit(status)
ArgumentParser.error(message)
此方法将包含 消息 的用法消息打印到标准错误,并以状态代码 2 终止程序。


混合解析

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

许多 Unix 命令允许用户混合可选参数和位置参数。 parse_intermixed_args()parse_known_intermixed_args() 方法支持这种解析风格。

这些解析器不支持所有 argparse 功能,如果使用了不受支持的功能,则会引发异常。 特别是,不支持子解析器、argparse.REMAINDER 和包含可选和位置的互斥组。

下面的例子展示了 parse_known_args()parse_intermixed_args() 的区别:前者返回 ['2', '3'] 作为未解析的参数,而后者将所有位置收集到 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() 返回一个包含填充的命名空间和剩余参数字符串列表的两项元组。 parse_intermixed_args() 如果还有任何未解析的参数字符串,则会引发错误。

3.7 版中的新功能。


升级 optparse 代码

最初,argparse 模块试图保持与 optparse 的兼容性。 然而,optparse 很难透明地扩展,特别是在支持新的 nargs= 说明符和更好的使用消息所需的更改时。 当 optparse 中的大部分内容都被复制粘贴或猴子修补时,尝试保持向后兼容性似乎不再可行。

argparse 模块以多种方式改进了标准库 optparse 模块,包括:

  • 处理位置参数。
  • 支持子命令。
  • 允许替代选项前缀,如 +/
  • 处理零个或多个和一个或多个样式参数。
  • 生成更多信息丰富的使用消息。
  • 为自定义 typeaction 提供更简单的界面。

optparseargparse 的部分升级路径:

  • 将所有 optparse.OptionParser.add_option() 调用替换为 ArgumentParser.add_argument() 调用。
  • (options, args) = parser.parse_args() 替换为 args = parser.parse_args(),并为位置参数添加额外的 ArgumentParser.add_argument() 调用。 请记住,以前称为 options,现在在 argparse 上下文中称为 args
  • 使用 parse_intermixed_args() 代替 parse_args() 替换 optparse.OptionParser.disable_interspersed_args()
  • 将回调操作和 callback_* 关键字参数替换为 typeaction 参数。
  • type 关键字参数的字符串名称替换为相应的类型对象(例如 int、float、complex 等)。
  • optparse.Values 替换为 命名空间 ,将 optparse.OptionErroroptparse.OptionValueError 替换为 ArgumentError
  • 将带有隐式参数的字符串(例如 %default%prog)替换为标准 Python 语法,以使用字典来格式化字符串,即 %(default)s%(prog)s
  • 将 OptionParser 构造函数 version 参数替换为对 parser.add_argument('--version', action='version', version='<the version>') 的调用。