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

来自菜鸟教程
Python/docs/3.9/library/optparse
跳转至:导航、​搜索
(autoload)
 
(Page commit)
 
第1行: 第1行:
 +
{{DISPLAYTITLE:optparse — 命令行选项解析器 — Python 文档}}
 
<div id="module-optparse" class="section">
 
<div id="module-optparse" class="section">
  
 
<span id="optparse-parser-for-command-line-options"></span>
 
<span id="optparse-parser-for-command-line-options"></span>
= [[#module-optparse|<code>optparse</code>]] --- Parser for command line options =
+
= optparse — 命令行选项解析器 =
  
'''Source code:''' [https://github.com/python/cpython/tree/3.9/Lib/optparse.py Lib/optparse.py]
+
'''源代码:''' [[#id1|<span id="id2" class="problematic">:source:`Lib/optparse.py`</span>]]
  
 
<div class="deprecated">
 
<div class="deprecated">
  
<span class="versionmodified deprecated">3.2 版后已移除: </span>The [[#module-optparse|<code>optparse</code>]] module is deprecated and will not be developed further;
+
<span class="versionmodified deprecated">Deprecated since version 3.2: </span>The [[#module-optparse|optparse]] 模块已弃用,不会进一步开发; [[../argparse#module-argparse|argparse]] 模块将继续开发。
development will continue with the [[../argparse#module-argparse|<code>argparse</code>]] module.
 
  
  
 
</div>
 
</div>
[[#module-optparse|<code>optparse</code>]] is a more convenient, flexible, and powerful library for parsing
 
command-line options than the old [[../getopt#module-getopt|<code>getopt</code>]] module. [[#module-optparse|<code>optparse</code>]] uses a
 
more declarative style of command-line parsing: you create an instance of
 
[[#optparse.OptionParser|<code>OptionParser</code>]], populate it with options, and parse the command
 
line. [[#module-optparse|<code>optparse</code>]] allows users to specify options in the conventional
 
GNU/POSIX syntax, and additionally generates usage and help messages for you.
 
  
Here's an example of using [[#module-optparse|<code>optparse</code>]] in a simple script:
+
-----
 +
 
 +
[[#module-optparse|optparse]] 是一个比旧的 [[../getopt#module-getopt|getopt]] 模块更方便、灵活和强大的命令行选项解析库。 [[#module-optparse|optparse]] 使用更具声明性的命令行解析风格:创建 [[#optparse.OptionParser|OptionParser]] 的实例,用选项填充它,然后解析命令行。 [[#module-optparse|optparse]] 允许用户在传统的 GNU/POSIX 语法中指定选项,并额外为您生成用法和帮助消息。
 +
 
 +
这是在简单脚本中使用 [[#module-optparse|optparse]] 的示例:
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第26行: 第24行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>from optparse import OptionParser
+
<syntaxhighlight lang="python3">from optparse import OptionParser
 
...
 
...
 
parser = OptionParser()
 
parser = OptionParser()
parser.add_option(&quot;-f&quot;, &quot;--file&quot;, dest=&quot;filename&quot;,
+
parser.add_option("-f", "--file", dest="filename",
                   help=&quot;write report to FILE&quot;, metavar=&quot;FILE&quot;)
+
                   help="write report to FILE", metavar="FILE")
parser.add_option(&quot;-q&quot;, &quot;--quiet&quot;,
+
parser.add_option("-q", "--quiet",
                   action=&quot;store_false&quot;, dest=&quot;verbose&quot;, default=True,
+
                   action="store_false", dest="verbose", default=True,
                   help=&quot;don't print status messages to stdout&quot;)
+
                   help="don't print status messages to stdout")
  
(options, args) = parser.parse_args()</pre>
+
(options, args) = parser.parse_args()</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
With these few lines of code, users of your script can now do the &quot;usual thing&quot;
+
使用这几行代码,您的脚本用户现在可以在命令行上执行“常规操作”,例如:
on the command-line, for example:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第47行: 第44行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&lt;yourscript&gt; --file=outfile -q</pre>
+
<syntaxhighlight lang="python3"><yourscript> --file=outfile -q</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
As it parses the command line, [[#module-optparse|<code>optparse</code>]] sets attributes of the
+
在解析命令行时,[[#module-optparse|optparse]] 根据用户提供的命令行值设置 <code>parse_args()</code> 返回的 <code>options</code> 对象的属性。 当 <code>parse_args()</code> 解析此命令行返回时,<code>options.filename</code> 将是 <code>&quot;outfile&quot;</code>,而 <code>options.verbose</code> 将是 <code>False</code>[[#module-optparse|optparse]] 支持长选项和短选项,允许将短选项合并在一起,并允许选项以多种方式与其参数相关联。 因此,以下命令行都等效于上面的示例:
<code>options</code> object returned by <code>parse_args()</code> based on user-supplied
 
command-line values. When <code>parse_args()</code> returns from parsing this command
 
line, <code>options.filename</code> will be <code>&quot;outfile&quot;</code> and <code>options.verbose</code> will be
 
<code>False</code>. [[#module-optparse|<code>optparse</code>]] supports both long and short options, allows short
 
options to be merged together, and allows options to be associated with their
 
arguments in a variety of ways. Thus, the following command lines are all
 
equivalent to the above example:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第65行: 第55行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&lt;yourscript&gt; -f outfile --quiet
+
<syntaxhighlight lang="python3"><yourscript> -f outfile --quiet
&lt;yourscript&gt; --quiet --file outfile
+
<yourscript> --quiet --file outfile
&lt;yourscript&gt; -q -foutfile
+
<yourscript> -q -foutfile
&lt;yourscript&gt; -qfoutfile</pre>
+
<yourscript> -qfoutfile</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
Additionally, users can run one of the following
+
此外,用户可以运行以下之一
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第79行: 第69行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&lt;yourscript&gt; -h
+
<syntaxhighlight lang="python3"><yourscript> -h
&lt;yourscript&gt; --help</pre>
+
<yourscript> --help</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
and [[#module-optparse|<code>optparse</code>]] will print out a brief summary of your script's options:
+
[[#module-optparse|optparse]] 将打印出脚本选项的简要摘要:
  
 
<div class="highlight-text notranslate">
 
<div class="highlight-text notranslate">
第91行: 第81行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>Usage: &lt;yourscript&gt; [options]
+
<syntaxhighlight lang="text">Usage: <yourscript> [options]
  
 
Options:
 
Options:
 
   -h, --help            show this help message and exit
 
   -h, --help            show this help message and exit
 
   -f FILE, --file=FILE  write report to FILE
 
   -f FILE, --file=FILE  write report to FILE
   -q, --quiet          don't print status messages to stdout</pre>
+
   -q, --quiet          don't print status messages to stdout</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
where the value of ''yourscript'' is determined at runtime (normally from
+
其中 ''yourscript'' 的值在运行时确定(通常来自 <code>sys.argv[0]</code>)。
<code>sys.argv[0]</code>).
 
  
 
<div id="background" class="section">
 
<div id="background" class="section">
  
 
<span id="optparse-background"></span>
 
<span id="optparse-background"></span>
== Background ==
+
== 背景 ==
  
[[#module-optparse|<code>optparse</code>]] was explicitly designed to encourage the creation of programs
+
[[#module-optparse|optparse]] 被明确设计为鼓励使用简单的、传统的命令行界面创建程序。 为此,它仅支持在 Unix 下常规使用的最常见的命令行语法和语义。 如果您不熟悉这些约定,请阅读本节以熟悉它们。
with straightforward, conventional command-line interfaces. To that end, it
 
supports only the most common command-line syntax and semantics conventionally
 
used under Unix. If you are unfamiliar with these conventions, read this
 
section to acquaint yourself with them.
 
  
 
<div id="terminology" class="section">
 
<div id="terminology" class="section">
  
 
<span id="optparse-terminology"></span>
 
<span id="optparse-terminology"></span>
=== Terminology ===
+
=== 术语 ===
  
 
<dl>
 
<dl>
<dt>argument</dt>
+
<dt>争论</dt>
<dd><p>a string entered on the command-line, and passed by the shell to <code>execl()</code>
+
<dd><p>在命令行上输入的字符串,并由 shell 传递给 <code>execl()</code> <code>execv()</code>。 在 Python 中,参数是 <code>sys.argv[1:]</code> 的元素(<code>sys.argv[0]</code> 是正在执行的程序的名称)。 Unix shell 也使用术语“单词”。</p>
or <code>execv()</code>. In Python, arguments are elements of <code>sys.argv[1:]</code>
+
<p>有时需要替换除 <code>sys.argv[1:]</code> 以外的参数列表,因此您应该将“参数”读作“<code>sys.argv[1:]</code> 的元素,或作为 <code>sys.argv[1:]</code>”。</p></dd>
(<code>sys.argv[0]</code> is the name of the program being executed). Unix shells
+
<dt>选项</dt>
also use the term &quot;word&quot;.</p>
+
<dd><p>用于提供额外信息以指导或自定义程序执行的参数。 选项有许多不同的语法; 传统的 Unix 语法是一个连字符(“-”)后跟一个字母,例如 <code>-x</code> <code>-F</code>。 此外,传统的 Unix 语法允许将多个选项合并为一个参数,例如 <code>-x -F</code> 相当于 <code>-xF</code>GNU 项目引入了 <code>--</code> 后跟一系列连字符分隔的单词,例如 <code>--file</code> <code>--dry-run</code>。 这些是 [[#module-optparse|optparse]] 提供的仅有的两个选项语法。</p>
<p>It is occasionally desirable to substitute an argument list other than
+
<p>世界上看到的其他一些选项语法包括:</p>
<code>sys.argv[1:]</code>, so you should read &quot;argument&quot; as &quot;an element of
 
<code>sys.argv[1:]</code>, or of some other list provided as a substitute for
 
<code>sys.argv[1:]</code>&quot;.</p></dd>
 
<dt>option</dt>
 
<dd><p>an argument used to supply extra information to guide or customize the
 
execution of a program. There are many different syntaxes for options; the
 
traditional Unix syntax is a hyphen (&quot;-&quot;) followed by a single letter,
 
e.g. <code>-x</code> or <code>-F</code>. Also, traditional Unix syntax allows multiple
 
options to be merged into a single argument, e.g. <code>-x -F</code> is equivalent
 
to <code>-xF</code>. The GNU project introduced <code>--</code> followed by a series of
 
hyphen-separated words, e.g. <code>--file</code> or <code>--dry-run</code>. These are the
 
only two option syntaxes provided by [[#module-optparse|<code>optparse</code>]].</p>
 
<p>Some other option syntaxes that the world has seen include:</p>
 
 
<ul>
 
<ul>
<li><p>a hyphen followed by a few letters, e.g. <code>-pf</code> (this is ''not'' the same
+
<li><p>一个连字符后跟几个字母,例如 <code>-pf</code>(这是 ''不是'' 与合并为单个参数的多个选项相同)</p></li>
as multiple options merged into a single argument)</p></li>
+
<li><p>一个连字符后跟一个完整的词,例如 <code>-file</code>(这在技术上等同于前面的语法,但它们通常不会出现在同一个程序中)</p></li>
<li><p>a hyphen followed by a whole word, e.g. <code>-file</code> (this is technically
+
<li><p>一个加号后跟一个字母,或几个字母,或一个词,例如 <code>+f</code><code>+rgb</code></p></li>
equivalent to the previous syntax, but they aren't usually seen in the same
+
<li><p>斜线后跟一个字母、几个字母或一个词,例如 <code>/f</code><code>/file</code></p></li></ul>
program)</p></li>
 
<li><p>a plus sign followed by a single letter, or a few letters, or a word, e.g.
 
<code>+f</code>, <code>+rgb</code></p></li>
 
<li><p>a slash followed by a letter, or a few letters, or a word, e.g. <code>/f</code>,
 
<code>/file</code></p></li></ul>
 
  
<p>These option syntaxes are not supported by [[#module-optparse|<code>optparse</code>]], and they never
+
<p>[[#module-optparse|optparse]] 不支持这些选项语法,并且永远不会支持。 这是故意的:前三个在任何环境中都是非标准的,最后一个只有在您专门针对 VMS、MS-DOS /Windows 时才有意义。</p></dd>
will be. This is deliberate: the first three are non-standard on any
+
<dt>选项参数</dt>
environment, and the last only makes sense if you're exclusively targeting
+
<dd><p>跟随选项的参数与该选项密切相关,并在该选项存在时从参数列表中使用。 使用 [[#module-optparse|optparse]],选项参数可以在与其选项分开的参数中:</p>
VMS, MS-DOS, and/or Windows.</p></dd>
 
<dt>option argument</dt>
 
<dd><p>an argument that follows an option, is closely associated with that option,
 
and is consumed from the argument list when that option is. With
 
[[#module-optparse|<code>optparse</code>]], option arguments may either be in a separate argument from
 
their option:</p>
 
 
<div class="highlight-text notranslate">
 
<div class="highlight-text notranslate">
  
 
<div class="highlight">
 
<div class="highlight">
  
<pre>-f foo
+
<syntaxhighlight lang="text">-f foo
--file foo</pre>
+
--file foo</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
<p>or included in the same argument:</p>
+
<p>或包含在同一参数中:</p>
 
<div class="highlight-text notranslate">
 
<div class="highlight-text notranslate">
  
 
<div class="highlight">
 
<div class="highlight">
  
<pre>-ffoo
+
<syntaxhighlight lang="text">-ffoo
--file=foo</pre>
+
--file=foo</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
<p>Typically, a given option either takes an argument or it doesn't. Lots of
+
<p>通常,给定的选项要么接受一个参数,要么不接受。 很多人想要一个“可选的选项参数”功能,这意味着如果他们看到一些选项会接受一个参数,如果他们没有则不会。 这有点有争议,因为它使解析模棱两可:如果 <code>-a</code> 接受一个可选参数而 <code>-b</code> 完全是另一个选项,我们如何解释 <code>-ab</code>? 由于这种歧义,[[#module-optparse|optparse]] 不支持此功能。</p></dd>
people want an &quot;optional option arguments&quot; feature, meaning that some options
+
<dt>位置论证</dt>
will take an argument if they see it, and won't if they don't. This is
+
<dd><p>解析选项后参数列表中剩余的内容,即 在选项及其参数被解析并从参数列表中删除之后。</p></dd>
somewhat controversial, because it makes parsing ambiguous: if <code>-a</code> takes
+
<dt>必选选项</dt>
an optional argument and <code>-b</code> is another option entirely, how do we
+
<dd><p>必须在命令行上提供的选项; 请注意,“必需选项”一词在英语中自相矛盾。 [[#module-optparse|optparse]] 不会阻止您实现所需的选项,但也不会给您太多帮助。</p></dd></dl>
interpret <code>-ab</code>? Because of this ambiguity, [[#module-optparse|<code>optparse</code>]] does not
 
support this feature.</p></dd>
 
<dt>positional argument</dt>
 
<dd><p>something leftover in the argument list after options have been parsed, i.e.
 
after options and their arguments have been parsed and removed from the
 
argument list.</p></dd>
 
<dt>required option</dt>
 
<dd><p>an option that must be supplied on the command-line; note that the phrase
 
&quot;required option&quot; is self-contradictory in English. [[#module-optparse|<code>optparse</code>]] doesn't
 
prevent you from implementing required options, but doesn't give you much
 
help at it either.</p></dd></dl>
 
  
For example, consider this hypothetical command-line:
+
例如,考虑这个假设的命令行:
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第204行: 第154行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>prog -v --report report.txt foo bar</pre>
+
<syntaxhighlight lang="python3">prog -v --report report.txt foo bar</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
<code>-v</code> and <code>--report</code> are both options. Assuming that <code>--report</code>
+
<code>-v</code> <code>--report</code> 都是选项。 假设 <code>--report</code> 接受一个参数,<code>report.txt</code> 是一个选项参数。 <code>foo</code> <code>bar</code> 是位置参数。
takes one argument, <code>report.txt</code> is an option argument. <code>foo</code> and
 
<code>bar</code> are positional arguments.
 
  
  
第218行: 第166行:
  
 
<span id="optparse-what-options-for"></span>
 
<span id="optparse-what-options-for"></span>
=== What are options for? ===
+
=== 什么是选项? ===
  
Options are used to provide extra information to tune or customize the execution
+
选项用于提供额外信息以调整或自定义程序的执行。 如果不清楚,选项通常是 ''optional''。 程序应该能够在没有任何选项的情况下正常运行。 (从 Unix GNU 工具集中随机选择一个程序。 它可以在没有任何选项的情况下运行并且仍然有意义吗? 主要的例外是 <code>find</code><code>tar</code> <code>dd</code>——所有这些都是变异的古怪,因其非标准的语法和令人困惑的界面而受到了正确的批评。)
of a program. In case it wasn't clear, options are usually ''optional''. A
 
program should be able to run just fine with no options whatsoever. (Pick a
 
random program from the Unix or GNU toolsets. Can it run without any options at
 
all and still make sense? The main exceptions are <code>find</code>, <code>tar</code>, and
 
<code>dd</code>---all of which are mutant oddballs that have been rightly criticized
 
for their non-standard syntax and confusing interfaces.)
 
  
Lots of people want their programs to have &quot;required options&quot;. Think about it.
+
许多人希望他们的程序具有“必需的选项”。 想想看。 如果它是必需的,那么它是 ''不是可选的'' ! 如果有一条信息是您的程序成功运行所绝对需要的,这就是位置参数的用途。
If it's required, then it's ''not optional''! If there is a piece of information
 
that your program absolutely requires in order to run successfully, that's what
 
positional arguments are for.
 
  
As an example of good command-line interface design, consider the humble <code>cp</code>
+
作为良好的命令行界面设计的一个例子,考虑用于复制文件的不起眼的 <code>cp</code> 实用程序。 在不提供目的地和至少一个来源的情况下尝试复制文件没有多大意义。 因此,如果不带参数运行 <code>cp</code> 会失败。 但是,它具有灵活、有用的语法,根本不需要任何选项:
utility, for copying files. It doesn't make much sense to try to copy files
 
without supplying a destination and at least one source. Hence, <code>cp</code> fails if
 
you run it with no arguments. However, it has a flexible, useful syntax that
 
does not require any options at all:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第243行: 第178行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>cp SOURCE DEST
+
<syntaxhighlight lang="python3">cp SOURCE DEST
cp SOURCE ... DEST-DIR</pre>
+
cp SOURCE ... DEST-DIR</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
You can get pretty far with just that. Most <code>cp</code> implementations provide a
+
你可以走得很远。 大多数 <code>cp</code> 实现提供了一系列选项来精确调整文件的复制方式:您可以保留模式和修改时间、避免跟随符号链接、在破坏现有文件之前询问等。 但这一切都不会分散 <code>cp</code> 的核心任务,即将一个文件复制到另一个文件,或将多个文件复制到另一个目录。
bunch of options to tweak exactly how the files are copied: you can preserve
 
mode and modification time, avoid following symlinks, ask before clobbering
 
existing files, etc. But none of this distracts from the core mission of
 
<code>cp</code>, which is to copy either one file to another, or several files to another
 
directory.
 
  
  
第261行: 第191行:
  
 
<span id="optparse-what-positional-arguments-for"></span>
 
<span id="optparse-what-positional-arguments-for"></span>
=== What are positional arguments for? ===
+
=== 什么是位置参数? ===
  
Positional arguments are for those pieces of information that your program
+
位置参数用于您的程序绝对需要运行的那些信息。
absolutely, positively requires to run.
 
  
A good user interface should have as few absolute requirements as possible. If
+
一个好的用户界面应该有尽可能少的绝对要求。 如果你的程序需要 17 条不同的信息才能成功运行,那么''如何''从用户那里获得这些信息并不重要——大多数人会在成功运行程序之前放弃并走开. 无论用户界面是命令行、配置文件还是 GUI,这都适用:如果您对用户提出那么多要求,他们中的大多数都会简单地放弃。
your program requires 17 distinct pieces of information in order to run
 
successfully, it doesn't much matter ''how'' you get that information from the
 
user---most people will give up and walk away before they successfully run the
 
program. This applies whether the user interface is a command-line, a
 
configuration file, or a GUI: if you make that many demands on your users, most
 
of them will simply give up.
 
  
In short, try to minimize the amount of information that users are absolutely
+
简而言之,尽量减少绝对需要用户提供的信息量——尽可能使用合理的默认值。 当然,您还希望使您的程序具有相当的灵活性。 这就是选项的用途。 同样,它们是配置文件中的条目、GUI 的“首选项”对话框中的小部件还是命令行选项都无关紧要——你实现的选项越多,你的程序就越灵活,也就越复杂它的实现变成了。 当然,太多的灵活性也有缺点。 太多的选项会让用户不知所措,并使您的代码更难维护。
required to supply---use sensible defaults whenever possible. Of course, you
 
also want to make your programs reasonably flexible. That's what options are
 
for. Again, it doesn't matter if they are entries in a config file, widgets in
 
the &quot;Preferences&quot; dialog of a GUI, or command-line options---the more options
 
you implement, the more flexible your program is, and the more complicated its
 
implementation becomes. Too much flexibility has drawbacks as well, of course;
 
too many options can overwhelm users and make your code much harder to maintain.
 
  
  
第290行: 第206行:
  
 
<span id="optparse-tutorial"></span>
 
<span id="optparse-tutorial"></span>
== Tutorial ==
+
== 教程 ==
  
While [[#module-optparse|<code>optparse</code>]] is quite flexible and powerful, it's also straightforward
+
虽然 [[#module-optparse|optparse]] 非常灵活和强大,但在大多数情况下使用起来也很简单。 本节涵盖了任何基于 [[#module-optparse|optparse]] 的程序通用的代码模式。
to use in most cases. This section covers the code patterns that are common to
 
any [[#module-optparse|<code>optparse</code>]]-based program.
 
  
First, you need to import the OptionParser class; then, early in the main
+
首先,需要导入OptionParser类; 然后,在主程序的早期,创建一个 OptionParser 实例:
program, create an OptionParser instance:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第303行: 第216行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>from optparse import OptionParser
+
<syntaxhighlight lang="python3">from optparse import OptionParser
 
...
 
...
parser = OptionParser()</pre>
+
parser = OptionParser()</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
Then you can start defining options. The basic syntax is:
+
然后您可以开始定义选项。 基本语法是:
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第316行: 第229行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>parser.add_option(opt_str, ...,
+
<syntaxhighlight lang="python3">parser.add_option(opt_str, ...,
                   attr=value, ...)</pre>
+
                   attr=value, ...)</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
Each option has one or more option strings, such as <code>-f</code> or <code>--file</code>,
+
每个选项都有一个或多个选项字符串,例如 <code>-f</code> <code>--file</code>,还有几个选项属性告诉 [[#module-optparse|optparse]] 期望什么以及遇到该选项时要做什么在命令行上。
and several option attributes that tell [[#module-optparse|<code>optparse</code>]] what to expect and what
 
to do when it encounters that option on the command line.
 
  
Typically, each option will have one short option string and one long option
+
通常,每个选项都有一个短选项字符串和一个长选项字符串,例如:
string, e.g.:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第333行: 第243行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>parser.add_option(&quot;-f&quot;, &quot;--file&quot;, ...)</pre>
+
<syntaxhighlight lang="python3">parser.add_option("-f", "--file", ...)</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
You're free to define as many short option strings and as many long option
+
您可以随意定义任意数量的短选项字符串和任意数量的长选项字符串(包括零),只要总体上至少有一个选项字符串即可。
strings as you like (including zero), as long as there is at least one option
 
string overall.
 
  
The option strings passed to [[#optparse.OptionParser.add_option|<code>OptionParser.add_option()</code>]] are effectively
+
传递给 [[#optparse.OptionParser.add_option|OptionParser.add_option()]] 的选项字符串实际上是该调用定义的选项的标签。 为简洁起见,我们会经常在命令行中提到''遇到一个选项''; 实际上,[[#module-optparse|optparse]] 遇到 ''option strings'' 并从中查找选项。
labels for the
 
option defined by that call. For brevity, we will frequently refer to
 
''encountering an option'' on the command line; in reality, [[#module-optparse|<code>optparse</code>]]
 
encounters ''option strings'' and looks up options from them.
 
  
Once all of your options are defined, instruct [[#module-optparse|<code>optparse</code>]] to parse your
+
定义所有选项后,指示 [[#module-optparse|optparse]] 解析程序的命令行:
program's command line:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第355行: 第258行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>(options, args) = parser.parse_args()</pre>
+
<syntaxhighlight lang="python3">(options, args) = parser.parse_args()</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
(If you like, you can pass a custom argument list to <code>parse_args()</code>, but
+
(如果您愿意,可以将自定义参数列表传递给 <code>parse_args()</code>,但这很少需要:默认情况下它使用 <code>sys.argv[1:]</code>。)
that's rarely necessary: by default it uses <code>sys.argv[1:]</code>.)
 
  
<code>parse_args()</code> returns two values:
+
<code>parse_args()</code> 返回两个值:
  
* <code>options</code>, an object containing values for all of your options---e.g. if <code>--file</code> takes a single string argument, then <code>options.file</code> will be the filename supplied by the user, or <code>None</code> if the user did not supply that option
+
* <code>options</code>,一个包含所有选项值的对象——例如 如果 <code>--file</code> 采用单个字符串参数,则 <code>options.file</code> 将是用户提供的文件名,如果用户未提供该选项,则 <code>None</code>
* <code>args</code>, the list of positional arguments leftover after parsing options
+
* <code>args</code>,解析选项后剩余的位置参数列表
  
This tutorial section only covers the four most important option attributes:
+
本教程部分仅涵盖四个最重要的选项属性:[[#optparse.Option.action|action]][[#optparse.Option.type|type]][[#optparse.Option.dest|dest]](目的地)和 [[#optparse.Option.help|help]]。 其中,[[#optparse.Option.action|action]]是最基本的。
[[#optparse.Option.action|<code>action</code>]], [[#optparse.Option.type|<code>type</code>]], [[#optparse.Option.dest|<code>dest</code>]]
 
(destination), and [[#optparse.Option.help|<code>help</code>]]. Of these, [[#optparse.Option.action|<code>action</code>]] is the
 
most fundamental.
 
  
 
<div id="understanding-option-actions" class="section">
 
<div id="understanding-option-actions" class="section">
  
 
<span id="optparse-understanding-option-actions"></span>
 
<span id="optparse-understanding-option-actions"></span>
=== Understanding option actions ===
+
=== 了解选项操作 ===
  
Actions tell [[#module-optparse|<code>optparse</code>]] what to do when it encounters an option on the
+
Actions 告诉 [[#module-optparse|optparse]] 当它在命令行上遇到一个选项时要做什么。 有一组固定的动作硬编码到 [[#module-optparse|optparse]] 中; 添加新操作是 [[#optparse-extending-optparse|扩展 optparse]] 部分中介绍的高级主题。 大多数操作告诉 [[#module-optparse|optparse]] 将值存储在某个变量中 - 例如,从命令行获取字符串并将其存储在 <code>options</code> 的属性中。
command line. There is a fixed set of actions hard-coded into [[#module-optparse|<code>optparse</code>]];
 
adding new actions is an advanced topic covered in section
 
[[#optparse-extending-optparse|<span class="std std-ref">Extending optparse</span>]]. Most actions tell [[#module-optparse|<code>optparse</code>]] to store
 
a value in some variable---for example, take a string from the command line and
 
store it in an attribute of <code>options</code>.
 
  
If you don't specify an option action, [[#module-optparse|<code>optparse</code>]] defaults to <code>store</code>.
+
如果不指定选项操作,[[#module-optparse|optparse]] 默认为 <code>store</code>
  
  
第392行: 第286行:
  
 
<span id="optparse-store-action"></span>
 
<span id="optparse-store-action"></span>
=== The store action ===
+
=== 店铺动作 ===
  
The most common option action is <code>store</code>, which tells [[#module-optparse|<code>optparse</code>]] to take
+
最常见的选项动作是 <code>store</code>,它告诉 [[#module-optparse|optparse]] 取下一个参数(或当前参数的剩余部分),确保它是正确的类型,并将其存储到您选择的目的地。
the next argument (or the remainder of the current argument), ensure that it is
 
of the correct type, and store it to your chosen destination.
 
  
For example:
+
例如:
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第404行: 第296行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>parser.add_option(&quot;-f&quot;, &quot;--file&quot;,
+
<syntaxhighlight lang="python3">parser.add_option("-f", "--file",
                   action=&quot;store&quot;, type=&quot;string&quot;, dest=&quot;filename&quot;)</pre>
+
                   action="store", type="string", dest="filename")</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
Now let's make up a fake command line and ask [[#module-optparse|<code>optparse</code>]] to parse it:
+
现在让我们编写一个假命令行并要求 [[#module-optparse|optparse]] 解析它:
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第416行: 第308行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>args = [&quot;-f&quot;, &quot;foo.txt&quot;]
+
<syntaxhighlight lang="python3">args = ["-f", "foo.txt"]
(options, args) = parser.parse_args(args)</pre>
+
(options, args) = parser.parse_args(args)</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
When [[#module-optparse|<code>optparse</code>]] sees the option string <code>-f</code>, it consumes the next
+
[[#module-optparse|optparse]] 看到选项字符串 <code>-f</code> 时,它会消耗下一个参数 <code>foo.txt</code>,并将其存储在 <code>options.filename</code> 中。 因此,在调用 <code>parse_args()</code> 之后,<code>options.filename</code> <code>&quot;foo.txt&quot;</code>
argument, <code>foo.txt</code>, and stores it in <code>options.filename</code>. So, after this
 
call to <code>parse_args()</code>, <code>options.filename</code> is <code>&quot;foo.txt&quot;</code>.
 
  
Some other option types supported by [[#module-optparse|<code>optparse</code>]] are <code>int</code> and <code>float</code>.
+
[[#module-optparse|optparse]] 支持的其他一些选项类型是 <code>int</code> <code>float</code>。 这是一个需要整数参数的选项:
Here's an option that expects an integer argument:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第433行: 第322行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>parser.add_option(&quot;-n&quot;, type=&quot;int&quot;, dest=&quot;num&quot;)</pre>
+
<syntaxhighlight lang="python3">parser.add_option("-n", type="int", dest="num")</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
Note that this option has no long option string, which is perfectly acceptable.
+
请注意,此选项没有长选项字符串,这是完全可以接受的。 此外,没有明确的操作,因为默认值为 <code>store</code>
Also, there's no explicit action, since the default is <code>store</code>.
 
  
Let's parse another fake command-line. This time, we'll jam the option argument
+
让我们解析另一个假命令行。 这一次,我们将把 option 参数直接与 option 相对:由于 <code>-n42</code>(一个参数)等价于 <code>-n 42</code>(两个参数),代码
right up against the option: since <code>-n42</code> (one argument) is equivalent to
 
<code>-n 42</code> (two arguments), the code
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第449行: 第335行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>(options, args) = parser.parse_args([&quot;-n42&quot;])
+
<syntaxhighlight lang="python3">(options, args) = parser.parse_args(["-n42"])
print(options.num)</pre>
+
print(options.num)</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
will print <code>42</code>.
+
将打印 <code>42</code>
  
If you don't specify a type, [[#module-optparse|<code>optparse</code>]] assumes <code>string</code>. Combined with
+
如果不指定类型,[[#module-optparse|optparse]] 假定为 <code>string</code>。 结合默认操作是 <code>store</code> 的事实,这意味着我们的第一个示例可以更短:
the fact that the default action is <code>store</code>, that means our first example can
 
be a lot shorter:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第465行: 第349行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>parser.add_option(&quot;-f&quot;, &quot;--file&quot;, dest=&quot;filename&quot;)</pre>
+
<syntaxhighlight lang="python3">parser.add_option("-f", "--file", dest="filename")</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
If you don't supply a destination, [[#module-optparse|<code>optparse</code>]] figures out a sensible
+
如果您不提供目的地,[[#module-optparse|optparse]] 会从选项字符串中找出合理的默认值:如果第一个长选项字符串是 <code>--foo-bar</code>,则默认目的地是 <code>foo_bar</code> ]。 如果没有长选项字符串,[[#module-optparse|optparse]] 会查看第一个短选项字符串:<code>-f</code> 的默认目标是 <code>f</code>
default from the option strings: if the first long option string is
 
<code>--foo-bar</code>, then the default destination is <code>foo_bar</code>. If there are no
 
long option strings, [[#module-optparse|<code>optparse</code>]] looks at the first short option string: the
 
default destination for <code>-f</code> is <code>f</code>.
 
  
[[#module-optparse|<code>optparse</code>]] also includes the built-in <code>complex</code> type. Adding
+
[[#module-optparse|optparse]] 还包括内置的 <code>complex</code> 类型。 添加类型在 [[#optparse-extending-optparse|扩展 optparse]] 部分中有介绍。
types is covered in section [[#optparse-extending-optparse|<span class="std std-ref">Extending optparse</span>]].
 
  
  
第484行: 第363行:
  
 
<span id="optparse-handling-boolean-options"></span>
 
<span id="optparse-handling-boolean-options"></span>
=== Handling boolean (flag) options ===
+
=== 处理布尔(标志)选项 ===
  
Flag options---set a variable to true or false when a particular option is
+
标记选项——在看到特定选项时将变量设置为 true 或 false——非常常见。 [[#module-optparse|optparse]] 通过两个单独的动作支持它们,<code>store_true</code> <code>store_false</code>。 例如,您可能有一个 <code>verbose</code> 标志,用 <code>-v</code> 打开,用 <code>-q</code> 关闭:
seen---are quite common. [[#module-optparse|<code>optparse</code>]] supports them with two separate actions,
 
<code>store_true</code> and <code>store_false</code>. For example, you might have a <code>verbose</code>
 
flag that is turned on with <code>-v</code> and off with <code>-q</code>:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第495行: 第371行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>parser.add_option(&quot;-v&quot;, action=&quot;store_true&quot;, dest=&quot;verbose&quot;)
+
<syntaxhighlight lang="python3">parser.add_option("-v", action="store_true", dest="verbose")
parser.add_option(&quot;-q&quot;, action=&quot;store_false&quot;, dest=&quot;verbose&quot;)</pre>
+
parser.add_option("-q", action="store_false", dest="verbose")</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
Here we have two different options with the same destination, which is perfectly
+
在这里,我们有两个具有相同目的地的不同选项,这完全没问题。 (这只是意味着你在设置默认值时必须小心一点——见下文。)
OK. (It just means you have to be a bit careful when setting default
 
values---see below.)
 
  
When [[#module-optparse|<code>optparse</code>]] encounters <code>-v</code> on the command line, it sets
+
[[#module-optparse|optparse]]在命令行遇到<code>-v</code>时,将<code>options.verbose</code>设置为<code>True</code>; 当遇到<code>-q</code>时,将<code>options.verbose</code>设置为<code>False</code>
<code>options.verbose</code> to <code>True</code>; when it encounters <code>-q</code>,
 
<code>options.verbose</code> is set to <code>False</code>.
 
  
  
第514行: 第386行:
  
 
<span id="optparse-other-actions"></span>
 
<span id="optparse-other-actions"></span>
=== Other actions ===
+
=== 其他行为 ===
  
Some other actions supported by [[#module-optparse|<code>optparse</code>]] are:
+
[[#module-optparse|optparse]] 支持的其他一些操作是:
  
 
; <code>&quot;store_const&quot;</code>
 
; <code>&quot;store_const&quot;</code>
: store a constant value
+
: 存储一个常数值
 
; <code>&quot;append&quot;</code>
 
; <code>&quot;append&quot;</code>
: append this option's argument to a list
+
: 将此选项的参数附加到列表中
 
; <code>&quot;count&quot;</code>
 
; <code>&quot;count&quot;</code>
: increment a counter by one
+
: 将计数器加一
 
; <code>&quot;callback&quot;</code>
 
; <code>&quot;callback&quot;</code>
: call a specified function
+
: 调用指定的函数
  
These are covered in section [[#optparse-reference-guide|<span class="std std-ref">Reference Guide</span>]],
+
这些在 [[#optparse-reference-guide|参考指南]] 部分和 [[#optparse-option-callbacks|选项回调]] 部分中有介绍。
and section [[#optparse-option-callbacks|<span class="std std-ref">Option Callbacks</span>]].
 
  
  
第535行: 第406行:
  
 
<span id="optparse-default-values"></span>
 
<span id="optparse-default-values"></span>
=== Default values ===
+
=== 默认值 ===
  
All of the above examples involve setting some variable (the &quot;destination&quot;) when
+
上述所有示例都涉及在看到某些命令行选项时设置一些变量(“目标”)。 如果从未见过这些选项会怎样? 由于我们没有提供任何默认值,它们都设置为 <code>None</code>。 这通常很好,但有时您需要更多控制。 [[#module-optparse|optparse]] 允许您为每个目标提供默认值,该值在解析命令行之前分配。
certain command-line options are seen. What happens if those options are never
 
seen? Since we didn't supply any defaults, they are all set to <code>None</code>. This
 
is usually fine, but sometimes you want more control. [[#module-optparse|<code>optparse</code>]] lets you
 
supply a default value for each destination, which is assigned before the
 
command line is parsed.
 
  
First, consider the verbose/quiet example. If we want [[#module-optparse|<code>optparse</code>]] to set
+
首先,考虑冗长/安静的例子。 如果我们想让 [[#module-optparse|optparse]] <code>verbose</code> 设置为 <code>True</code> 除非看到 <code>-q</code>,那么我们可以这样做:
<code>verbose</code> to <code>True</code> unless <code>-q</code> is seen, then we can do this:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第551行: 第416行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>parser.add_option(&quot;-v&quot;, action=&quot;store_true&quot;, dest=&quot;verbose&quot;, default=True)
+
<syntaxhighlight lang="python3">parser.add_option("-v", action="store_true", dest="verbose", default=True)
parser.add_option(&quot;-q&quot;, action=&quot;store_false&quot;, dest=&quot;verbose&quot;)</pre>
+
parser.add_option("-q", action="store_false", dest="verbose")</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
Since default values apply to the ''destination'' rather than to any particular
+
由于默认值适用于 ''destination'' 而不是任何特定选项,并且这两个选项恰好具有相同的目标,这完全等效:
option, and these two options happen to have the same destination, this is
 
exactly equivalent:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第565行: 第428行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>parser.add_option(&quot;-v&quot;, action=&quot;store_true&quot;, dest=&quot;verbose&quot;)
+
<syntaxhighlight lang="python3">parser.add_option("-v", action="store_true", dest="verbose")
parser.add_option(&quot;-q&quot;, action=&quot;store_false&quot;, dest=&quot;verbose&quot;, default=True)</pre>
+
parser.add_option("-q", action="store_false", dest="verbose", default=True)</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
Consider this:
+
考虑一下:
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第577行: 第440行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>parser.add_option(&quot;-v&quot;, action=&quot;store_true&quot;, dest=&quot;verbose&quot;, default=False)
+
<syntaxhighlight lang="python3">parser.add_option("-v", action="store_true", dest="verbose", default=False)
parser.add_option(&quot;-q&quot;, action=&quot;store_false&quot;, dest=&quot;verbose&quot;, default=True)</pre>
+
parser.add_option("-q", action="store_false", dest="verbose", default=True)</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
Again, the default value for <code>verbose</code> will be <code>True</code>: the last default
+
同样,<code>verbose</code> 的默认值将是 <code>True</code>:为任何特定目的地提供的最后一个默认值是重要的。
value supplied for any particular destination is the one that counts.
 
  
A clearer way to specify default values is the <code>set_defaults()</code> method of
+
一个更清晰的指定默认值的方法是OptionParser的<code>set_defaults()</code>方法,你可以在调用<code>parse_args()</code>之前随时调用它:
OptionParser, which you can call at any time before calling <code>parse_args()</code>:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第593行: 第454行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>parser.set_defaults(verbose=True)
+
<syntaxhighlight lang="python3">parser.set_defaults(verbose=True)
 
parser.add_option(...)
 
parser.add_option(...)
(options, args) = parser.parse_args()</pre>
+
(options, args) = parser.parse_args()</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
As before, the last value specified for a given option destination is the one
+
和以前一样,为给定选项目标指定的最后一个值是最重要的值。 为清楚起见,请尝试使用一种方法或另一种设置默认值的方法,而不是同时使用两种方法。
that counts. For clarity, try to use one method or the other of setting default
 
values, not both.
 
  
  
第609行: 第468行:
  
 
<span id="optparse-generating-help"></span>
 
<span id="optparse-generating-help"></span>
=== Generating help ===
+
=== 生成帮助 ===
  
[[#module-optparse|<code>optparse</code>]]'s ability to generate help and usage text automatically is
+
[[#module-optparse|optparse]] 自动生成帮助和使用文本的能力对于创建用户友好的命令行界面非常有用。 您所要做的就是为每个选项提供一个 [[#optparse.Option.help|help]] 值,并且可以选择为整个程序提供一个简短的使用消息。 这是一个填充了用户友好(记录)选项的 OptionParser:
useful for creating user-friendly command-line interfaces. All you have to do
 
is supply a [[#optparse.Option.help|<code>help</code>]] value for each option, and optionally a short
 
usage message for your whole program. Here's an OptionParser populated with
 
user-friendly (documented) options:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第621行: 第476行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>usage = &quot;usage: %prog [options] arg1 arg2&quot;
+
<syntaxhighlight lang="python3">usage = "usage: %prog [options] arg1 arg2"
 
parser = OptionParser(usage=usage)
 
parser = OptionParser(usage=usage)
parser.add_option(&quot;-v&quot;, &quot;--verbose&quot;,
+
parser.add_option("-v", "--verbose",
                   action=&quot;store_true&quot;, dest=&quot;verbose&quot;, default=True,
+
                   action="store_true", dest="verbose", default=True,
                   help=&quot;make lots of noise [default]&quot;)
+
                   help="make lots of noise [default]")
parser.add_option(&quot;-q&quot;, &quot;--quiet&quot;,
+
parser.add_option("-q", "--quiet",
                   action=&quot;store_false&quot;, dest=&quot;verbose&quot;,
+
                   action="store_false", dest="verbose",
                   help=&quot;be vewwy quiet (I'm hunting wabbits)&quot;)
+
                   help="be vewwy quiet (I'm hunting wabbits)")
parser.add_option(&quot;-f&quot;, &quot;--filename&quot;,
+
parser.add_option("-f", "--filename",
                   metavar=&quot;FILE&quot;, help=&quot;write output to FILE&quot;)
+
                   metavar="FILE", help="write output to FILE")
parser.add_option(&quot;-m&quot;, &quot;--mode&quot;,
+
parser.add_option("-m", "--mode",
                   default=&quot;intermediate&quot;,
+
                   default="intermediate",
                   help=&quot;interaction mode: novice, intermediate, &quot;
+
                   help="interaction mode: novice, intermediate, "
                       &quot;or expert [default: %default]&quot;)</pre>
+
                       "or expert [default: %default]")</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
If [[#module-optparse|<code>optparse</code>]] encounters either <code>-h</code> or <code>--help</code> on the
+
如果 [[#module-optparse|optparse]] 在命令行上遇到 <code>-h</code> <code>--help</code>,或者如果您只是调用 <code>parser.print_help()</code>,它会将以下内容打印到标准输出:
command-line, or if you just call <code>parser.print_help()</code>, it prints the
 
following to standard output:
 
  
 
<div class="highlight-text notranslate">
 
<div class="highlight-text notranslate">
第647行: 第500行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>Usage: &lt;yourscript&gt; [options] arg1 arg2
+
<syntaxhighlight lang="text">Usage: <yourscript> [options] arg1 arg2
  
 
Options:
 
Options:
第656行: 第509行:
 
                         write output to FILE
 
                         write output to FILE
 
   -m MODE, --mode=MODE  interaction mode: novice, intermediate, or
 
   -m MODE, --mode=MODE  interaction mode: novice, intermediate, or
                         expert [default: intermediate]</pre>
+
                         expert [default: intermediate]</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
(If the help output is triggered by a help option, [[#module-optparse|<code>optparse</code>]] exits after
+
(如果帮助输出是由帮助选项触发的,则在打印帮助文本后 [[#module-optparse|optparse]] 退出。)
printing the help text.)
 
  
There's a lot going on here to help [[#module-optparse|<code>optparse</code>]] generate the best possible
+
这里有很多事情可以帮助 [[#module-optparse|optparse]] 生成最好的帮助消息:
help message:
 
  
 
<ul>
 
<ul>
<li><p>the script defines its own usage message:</p>
+
<li><p>该脚本定义了自己的使用消息:</p>
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
  
 
<div class="highlight">
 
<div class="highlight">
  
<pre>usage = &quot;usage: %prog [options] arg1 arg2&quot;</pre>
+
<syntaxhighlight lang="python3">usage = "usage: %prog [options] arg1 arg2"</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
<p>[[#module-optparse|<code>optparse</code>]] expands <code>%prog</code> in the usage string to the name of the
+
<p>[[#module-optparse|optparse]] 将用法字符串中的 <code>%prog</code> 扩展为当前程序的名称,即 <code>os.path.basename(sys.argv[0])</code>。 然后在详细选项帮助之前打印扩展的字符串。</p>
current program, i.e. <code>os.path.basename(sys.argv[0])</code>. The expanded string
+
<p>如果您不提供用法字符串,[[#module-optparse|optparse]] 使用平淡但合理的默认值:<code>&quot;Usage: %prog [options]&quot;</code>,如果您的脚本不采用任何位置参数,这很好。</p></li>
is then printed before the detailed option help.</p>
+
<li><p>每个选项都定义了一个帮助字符串,并且不用担心换行——[[#module-optparse|optparse]] 负责换行并使帮助输出看起来不错。</p></li>
<p>If you don't supply a usage string, [[#module-optparse|<code>optparse</code>]] uses a bland but sensible
+
<li><p>带值的选项在其自动生成的帮助消息中表明这一事实,例如 对于“模式”选项:</p>
default: <code>&quot;Usage: %prog [options]&quot;</code>, which is fine if your script doesn't
 
take any positional arguments.</p></li>
 
<li><p>every option defines a help string, and doesn't worry about
 
line-wrapping---[[#module-optparse|<code>optparse</code>]] takes care of wrapping lines and making
 
the help output look good.</p></li>
 
<li><p>options that take a value indicate this fact in their automatically-generated
 
help message, e.g. for the &quot;mode&quot; option:</p>
 
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
  
 
<div class="highlight">
 
<div class="highlight">
  
<pre>-m MODE, --mode=MODE</pre>
+
<syntaxhighlight lang="python3">-m MODE, --mode=MODE</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
<p>Here, &quot;MODE&quot; is called the meta-variable: it stands for the argument that the
+
<p>这里,“MODE”被称为元变量:它代表用户应该提供给 <code>-m</code>/<code>--mode</code> 的参数。 默认情况下,[[#module-optparse|optparse]] 将目标变量名称转换为大写并将其用于元变量。 有时,这不是您想要的——例如,<code>--filename</code> 选项显式设置 <code>metavar=&quot;FILE&quot;</code>,从而导致此自动生成的选项描述:</p>
user is expected to supply to <code>-m</code>/<code>--mode</code>. By default,
 
[[#module-optparse|<code>optparse</code>]] converts the destination variable name to uppercase and uses
 
that for the meta-variable. Sometimes, that's not what you want---for
 
example, the <code>--filename</code> option explicitly sets <code>metavar=&quot;FILE&quot;</code>,
 
resulting in this automatically-generated option description:</p>
 
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
  
 
<div class="highlight">
 
<div class="highlight">
  
<pre>-f FILE, --filename=FILE</pre>
+
<syntaxhighlight lang="python3">-f FILE, --filename=FILE</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
<p>This is important for more than just saving space, though: the manually
+
<p>不过,这不仅仅是节省空间的重要原因:手动编写的帮助文本使用元变量 <code>FILE</code> 来提示用户,因为半正式语法 <code>-f FILE</code> 和非正式语义描述“将输出写入文件”。 这是一种简单但有效的方法,可以使您的帮助文本更清晰,对最终用户更有用。</p></li>
written help text uses the meta-variable <code>FILE</code> to clue the user in that
+
<li><p>具有默认值的选项可以在帮助字符串中包含 <code>%default</code> - [[#module-optparse|optparse]] 将替换为选项默认值的 [[../stdtypes#str|str()]]。 如果选项没有默认值(或默认值为 <code>None</code>),则 <code>%default</code> 扩展为 <code>none</code></p></li></ul>
there's a connection between the semi-formal syntax <code>-f FILE</code> and the informal
 
semantic description &quot;write output to FILE&quot;. This is a simple but effective
 
way to make your help text a lot clearer and more useful for end users.</p></li>
 
<li><p>options that have a default value can include <code>%default</code> in the help
 
string---[[#module-optparse|<code>optparse</code>]] will replace it with [[../stdtypes#str|<code>str()</code>]] of the option's
 
default value. If an option has no default value (or the default value is
 
<code>None</code>), <code>%default</code> expands to <code>none</code>.</p></li></ul>
 
  
 
<div id="grouping-options" class="section">
 
<div id="grouping-options" class="section">
  
==== Grouping Options ====
+
==== 分组选项 ====
  
When dealing with many options, it is convenient to group these options for
+
在处理多个选项时,可以方便地将这些选项分组以获得更好的帮助输出。 一个 [[#optparse.OptionParser|OptionParser]] 可以包含多个选项组,每个选项组可以包含多个选项。
better help output. An [[#optparse.OptionParser|<code>OptionParser</code>]] can contain several option groups,
 
each of which can contain several options.
 
  
An option group is obtained using the class [[#optparse.OptionGroup|<code>OptionGroup</code>]]:
+
使用类 [[#optparse.OptionGroup|OptionGroup]] 获得选项组:
  
; ''class'' <code>optparse.</code><code>OptionGroup</code><span class="sig-paren">(</span>''<span class="n">parser</span>'', ''<span class="n">title</span>'', ''<span class="n">description</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">optparse.</span></span><span class="sig-name descname"><span class="pre">OptionGroup</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">parser</span></span>'', ''<span class="n"><span class="pre">title</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>
: where
+
: 在哪里
;* parser is the [[#optparse.OptionParser|<code>OptionParser</code>]] instance the group will be inserted in to
+
;* parser 是组将插入到的 [[#optparse.OptionParser|OptionParser]] 实例
;* title is the group title
+
;* 标题是组标题
;* description, optional, is a long description of the group
+
;* description,可选,是对组的详细描述
  
[[#optparse.OptionGroup|<code>OptionGroup</code>]] inherits from <code>OptionContainer</code> (like
+
[[#optparse.OptionGroup|OptionGroup]] 继承自 <code>OptionContainer</code>(如 [[#optparse.OptionParser|OptionParser]]),因此 <code>add_option()</code> 方法可用于向组添加选项。
[[#optparse.OptionParser|<code>OptionParser</code>]]) and so the <code>add_option()</code> method can be used to add
 
an option to the group.
 
  
Once all the options are declared, using the [[#optparse.OptionParser|<code>OptionParser</code>]] method
+
声明所有选项后,使用 [[#optparse.OptionParser|OptionParser]] 方法 <code>add_option_group()</code> 将组添加到先前定义的解析器。
<code>add_option_group()</code> the group is added to the previously defined parser.
 
  
Continuing with the parser defined in the previous section, adding an
+
继续上一节中定义的解析器,向解析器添加 [[#optparse.OptionGroup|OptionGroup]] 很容易:
[[#optparse.OptionGroup|<code>OptionGroup</code>]] to a parser is easy:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第753行: 第579行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>group = OptionGroup(parser, &quot;Dangerous Options&quot;,
+
<syntaxhighlight lang="python3">group = OptionGroup(parser, "Dangerous Options",
                     &quot;Caution: use these options at your own risk.  &quot;
+
                     "Caution: use these options at your own risk.  "
                     &quot;It is believed that some of them bite.&quot;)
+
                     "It is believed that some of them bite.")
group.add_option(&quot;-g&quot;, action=&quot;store_true&quot;, help=&quot;Group option.&quot;)
+
group.add_option("-g", action="store_true", help="Group option.")
parser.add_option_group(group)</pre>
+
parser.add_option_group(group)</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
This would result in the following help output:
+
这将导致以下帮助输出:
  
 
<div class="highlight-text notranslate">
 
<div class="highlight-text notranslate">
第768行: 第594行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>Usage: &lt;yourscript&gt; [options] arg1 arg2
+
<syntaxhighlight lang="text">Usage: <yourscript> [options] arg1 arg2
  
 
Options:
 
Options:
第783行: 第609行:
 
     of them bite.
 
     of them bite.
  
     -g                  Group option.</pre>
+
     -g                  Group option.</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
A bit more complete example might involve using more than one group: still
+
更完整的示例可能涉及使用多个组:仍然扩展前一个示例:
extending the previous example:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第795行: 第620行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>group = OptionGroup(parser, &quot;Dangerous Options&quot;,
+
<syntaxhighlight lang="python3">group = OptionGroup(parser, "Dangerous Options",
                     &quot;Caution: use these options at your own risk.  &quot;
+
                     "Caution: use these options at your own risk.  "
                     &quot;It is believed that some of them bite.&quot;)
+
                     "It is believed that some of them bite.")
group.add_option(&quot;-g&quot;, action=&quot;store_true&quot;, help=&quot;Group option.&quot;)
+
group.add_option("-g", action="store_true", help="Group option.")
 
parser.add_option_group(group)
 
parser.add_option_group(group)
  
group = OptionGroup(parser, &quot;Debug Options&quot;)
+
group = OptionGroup(parser, "Debug Options")
group.add_option(&quot;-d&quot;, &quot;--debug&quot;, action=&quot;store_true&quot;,
+
group.add_option("-d", "--debug", action="store_true",
                 help=&quot;Print debug information&quot;)
+
                 help="Print debug information")
group.add_option(&quot;-s&quot;, &quot;--sql&quot;, action=&quot;store_true&quot;,
+
group.add_option("-s", "--sql", action="store_true",
                 help=&quot;Print all SQL statements executed&quot;)
+
                 help="Print all SQL statements executed")
group.add_option(&quot;-e&quot;, action=&quot;store_true&quot;, help=&quot;Print every action done&quot;)
+
group.add_option("-e", action="store_true", help="Print every action done")
parser.add_option_group(group)</pre>
+
parser.add_option_group(group)</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
that results in the following output:
+
这导致以下输出:
  
 
<div class="highlight-text notranslate">
 
<div class="highlight-text notranslate">
第818行: 第643行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>Usage: &lt;yourscript&gt; [options] arg1 arg2
+
<syntaxhighlight lang="text">Usage: <yourscript> [options] arg1 arg2
  
 
Options:
 
Options:
第838行: 第663行:
 
     -d, --debug        Print debug information
 
     -d, --debug        Print debug information
 
     -s, --sql          Print all SQL statements executed
 
     -s, --sql          Print all SQL statements executed
     -e                  Print every action done</pre>
+
     -e                  Print every action done</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
Another interesting method, in particular when working programmatically with
+
另一个有趣的方法,特别是在以编程方式使用选项组时:
option groups is:
 
  
; <code>OptionParser.</code><code>get_option_group</code><span class="sig-paren">(</span>''<span class="n">opt_str</span>''<span class="sig-paren">)</span>
+
; <span class="sig-prename descclassname"><span class="pre">OptionParser.</span></span><span class="sig-name descname"><span class="pre">get_option_group</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">opt_str</span></span>''<span class="sig-paren">)</span>
: Return the [[#optparse.OptionGroup|<code>OptionGroup</code>]] to which the short or long option string ''opt_str'' (e.g. <code>'-o'</code> or <code>'--option'</code>) belongs. If there's no such [[#optparse.OptionGroup|<code>OptionGroup</code>]], return <code>None</code>.
+
: 返回短或长选项字符串 ''opt_str'' 的 [[#optparse.OptionGroup|OptionGroup]](例如 <code>'-o'</code> <code>'--option'</code>) 属于。 如果没有这样的 [[#optparse.OptionGroup|OptionGroup]],则返回 <code>None</code>
  
  
第856行: 第680行:
  
 
<span id="optparse-printing-version-string"></span>
 
<span id="optparse-printing-version-string"></span>
=== Printing a version string ===
+
=== 打印版本字符串 ===
  
Similar to the brief usage string, [[#module-optparse|<code>optparse</code>]] can also print a version
+
与简要用法字符串类似,[[#module-optparse|optparse]] 也可以为您的程序打印版本字符串。 您必须将字符串作为 <code>version</code> 参数提供给 OptionParser:
string for your program. You have to supply the string as the <code>version</code>
 
argument to OptionParser:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第866行: 第688行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>parser = OptionParser(usage=&quot;%prog [-f] [-q]&quot;, version=&quot;%prog 1.0&quot;)</pre>
+
<syntaxhighlight lang="python3">parser = OptionParser(usage="%prog [-f] [-q]", version="%prog 1.0")</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
<code>%prog</code> is expanded just like it is in <code>usage</code>. Apart from that,
+
<code>%prog</code> 像在 <code>usage</code> 中一样展开。 除此之外,<code>version</code> 可以包含任何你喜欢的东西。 当您提供它时, [[#module-optparse|optparse]] 会自动向您的解析器添加一个 <code>--version</code> 选项。 如果它在命令行上遇到此选项,它会扩展您的 <code>version</code> 字符串(通过替换 <code>%prog</code>),将其打印到标准输出,然后退出。
<code>version</code> can contain anything you like. When you supply it, [[#module-optparse|<code>optparse</code>]]
 
automatically adds a <code>--version</code> option to your parser. If it encounters
 
this option on the command line, it expands your <code>version</code> string (by
 
replacing <code>%prog</code>), prints it to stdout, and exits.
 
  
For example, if your script is called <code>/usr/bin/foo</code>:
+
例如,如果您的脚本名为 <code>/usr/bin/foo</code>
  
 
<div class="highlight-shell-session notranslate">
 
<div class="highlight-shell-session notranslate">
第883行: 第701行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>$ /usr/bin/foo --version
+
<pre class="session">$ /usr/bin/foo --version
 
foo 1.0</pre>
 
foo 1.0</pre>
  
第889行: 第707行:
  
 
</div>
 
</div>
The following two methods can be used to print and get the <code>version</code> string:
+
可以使用以下两种方法打印和获取 <code>version</code> 字符串:
  
; <code>OptionParser.</code><code>print_version</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">OptionParser.</span></span><span class="sig-name descname"><span class="pre">print_version</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 the version message for the current program (<code>self.version</code>) to ''file'' (default stdout). As with [[#optparse.OptionParser.print_usage|<code>print_usage()</code>]], any occurrence of <code>%prog</code> in <code>self.version</code> is replaced with the name of the current program. Does nothing if <code>self.version</code> is empty or undefined.
+
: 将当前程序 (<code>self.version</code>) 的版本信息打印到 ''file''(默认标准输出)。 与 [[#optparse.OptionParser.print_usage|print_usage()]] 一样,<code>self.version</code> 中出现的任何 <code>%prog</code> 都将替换为当前程序的名称。 如果 <code>self.version</code> 为空或未定义,则不执行任何操作。
  
; <code>OptionParser.</code><code>get_version</code><span class="sig-paren">(</span><span class="sig-paren">)</span>
+
; <span class="sig-prename descclassname"><span class="pre">OptionParser.</span></span><span class="sig-name descname"><span class="pre">get_version</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span>
: Same as [[#optparse.OptionParser.print_version|<code>print_version()</code>]] but returns the version string instead of printing it.
+
: [[#optparse.OptionParser.print_version|print_version()]] 相同,但返回版本字符串而不是打印它。
  
  
第902行: 第720行:
  
 
<span id="optparse-how-optparse-handles-errors"></span>
 
<span id="optparse-how-optparse-handles-errors"></span>
=== How [[#module-optparse|<code>optparse</code>]] handles errors ===
+
=== optparse 如何处理错误 ===
  
There are two broad classes of errors that [[#module-optparse|<code>optparse</code>]] has to worry about:
+
[[#module-optparse|optparse]] 必须担心两大类错误:程序员错误和用户错误。 程序员错误通常是对 [[#optparse.OptionParser.add_option|OptionParser.add_option()]] 的错误调用,例如 无效的选项字符串、未知的选项属性、缺少选项属性等。 这些以通常的方式处理:引发异常(<code>optparse.OptionError</code> [[../exceptions#TypeError|TypeError]])并让程序崩溃。
programmer errors and user errors. Programmer errors are usually erroneous
 
calls to [[#optparse.OptionParser.add_option|<code>OptionParser.add_option()</code>]], e.g. invalid option strings, unknown
 
option attributes, missing option attributes, etc. These are dealt with in the
 
usual way: raise an exception (either <code>optparse.OptionError</code> or
 
[[../exceptions#TypeError|<code>TypeError</code>]]) and let the program crash.
 
  
Handling user errors is much more important, since they are guaranteed to happen
+
处理用户错误更为重要,因为无论您的代码多么稳定,它们都一定会发生。 [[#module-optparse|optparse]] 可以自动检测一些用户错误,例如错误的选项参数(传递 <code>-n 4x</code> 其中 <code>-n</code> 需要一个整数参数),缺少参数(<code>-n</code> 在命令行的末尾,其中 <code>-n</code> 接受任何类型的参数)。 此外,您可以调用 <code>OptionParser.error()</code> 来表示应用程序定义的错误条件:
no matter how stable your code is. [[#module-optparse|<code>optparse</code>]] can automatically detect
 
some user errors, such as bad option arguments (passing <code>-n 4x</code> where
 
<code>-n</code> takes an integer argument), missing arguments (<code>-n</code> at the end
 
of the command line, where <code>-n</code> takes an argument of any type). Also,
 
you can call <code>OptionParser.error()</code> to signal an application-defined error
 
condition:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第923行: 第730行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>(options, args) = parser.parse_args()
+
<syntaxhighlight lang="python3">(options, args) = parser.parse_args()
 
...
 
...
 
if options.a and options.b:
 
if options.a and options.b:
     parser.error(&quot;options -a and -b are mutually exclusive&quot;)</pre>
+
     parser.error("options -a and -b are mutually exclusive")</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
In either case, [[#module-optparse|<code>optparse</code>]] handles the error the same way: it prints the
+
在任何一种情况下,[[#module-optparse|optparse]] 都以相同的方式处理错误:它将程序的使用消息和错误消息打印到标准错误,并以错误状态 2 退出。
program's usage message and an error message to standard error and exits with
 
error status 2.
 
  
Consider the first example above, where the user passes <code>4x</code> to an option
+
考虑上面的第一个示例,其中用户将 <code>4x</code> 传递给一个接受整数的选项:
that takes an integer:
 
  
 
<div class="highlight-shell-session notranslate">
 
<div class="highlight-shell-session notranslate">
第942行: 第746行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>$ /usr/bin/foo -n 4x
+
<pre class="session">$ /usr/bin/foo -n 4x
 
Usage: foo [options]
 
Usage: foo [options]
  
第950行: 第754行:
  
 
</div>
 
</div>
Or, where the user fails to pass a value at all:
+
或者,用户根本无法传递值:
  
 
<div class="highlight-shell-session notranslate">
 
<div class="highlight-shell-session notranslate">
第956行: 第760行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>$ /usr/bin/foo -n
+
<pre class="session">$ /usr/bin/foo -n
 
Usage: foo [options]
 
Usage: foo [options]
  
第964行: 第768行:
  
 
</div>
 
</div>
[[#module-optparse|<code>optparse</code>]]-generated error messages take care always to mention the
+
[[#module-optparse|optparse]] 生成的错误消息注意总是提及错误中涉及的选项; 从您的应用程序代码调用 <code>OptionParser.error()</code> 时一定要这样做。
option involved in the error; be sure to do the same when calling
 
<code>OptionParser.error()</code> from your application code.
 
  
If [[#module-optparse|<code>optparse</code>]]'s default error-handling behaviour does not suit your needs,
+
如果 [[#module-optparse|optparse]] 的默认错误处理行为不适合您的需要,您需要继承 OptionParser 并覆盖其 <code>exit()</code> /<code>error()</code> 方法。
you'll need to subclass OptionParser and override its <code>exit()</code>
 
and/or <code>error()</code> methods.
 
  
  
第977行: 第777行:
  
 
<span id="optparse-putting-it-all-together"></span>
 
<span id="optparse-putting-it-all-together"></span>
=== Putting it all together ===
+
=== 把这一切放在一起 ===
  
Here's what [[#module-optparse|<code>optparse</code>]]-based scripts usually look like:
+
以下是基于 [[#module-optparse|optparse]] 的脚本通常的样子:
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第985行: 第785行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>from optparse import OptionParser
+
<syntaxhighlight lang="python3">from optparse import OptionParser
 
...
 
...
 
def main():
 
def main():
     usage = &quot;usage: %prog [options] arg&quot;
+
     usage = "usage: %prog [options] arg"
 
     parser = OptionParser(usage)
 
     parser = OptionParser(usage)
     parser.add_option(&quot;-f&quot;, &quot;--file&quot;, dest=&quot;filename&quot;,
+
     parser.add_option("-f", "--file", dest="filename",
                       help=&quot;read data from FILENAME&quot;)
+
                       help="read data from FILENAME")
     parser.add_option(&quot;-v&quot;, &quot;--verbose&quot;,
+
     parser.add_option("-v", "--verbose",
                       action=&quot;store_true&quot;, dest=&quot;verbose&quot;)
+
                       action="store_true", dest="verbose")
     parser.add_option(&quot;-q&quot;, &quot;--quiet&quot;,
+
     parser.add_option("-q", "--quiet",
                       action=&quot;store_false&quot;, dest=&quot;verbose&quot;)
+
                       action="store_false", dest="verbose")
 
     ...
 
     ...
 
     (options, args) = parser.parse_args()
 
     (options, args) = parser.parse_args()
 
     if len(args) != 1:
 
     if len(args) != 1:
         parser.error(&quot;incorrect number of arguments&quot;)
+
         parser.error("incorrect number of arguments")
 
     if options.verbose:
 
     if options.verbose:
         print(&quot;reading %s...&quot; % options.filename)
+
         print("reading %s..." % options.filename)
 
     ...
 
     ...
  
if __name__ == &quot;__main__&quot;:
+
if __name__ == "__main__":
     main()</pre>
+
     main()</syntaxhighlight>
  
 
</div>
 
</div>
第1,017行: 第817行:
  
 
<span id="optparse-reference-guide"></span>
 
<span id="optparse-reference-guide"></span>
== Reference Guide ==
+
== 参考指南 ==
  
 
<div id="creating-the-parser" class="section">
 
<div id="creating-the-parser" class="section">
  
 
<span id="optparse-creating-parser"></span>
 
<span id="optparse-creating-parser"></span>
=== Creating the parser ===
+
=== 创建解析器 ===
  
The first step in using [[#module-optparse|<code>optparse</code>]] is to create an OptionParser instance.
+
使用 [[#module-optparse|optparse]] 的第一步是创建一个 OptionParser 实例。
  
; ''class'' <code>optparse.</code><code>OptionParser</code><span class="sig-paren">(</span>''...''<span class="sig-paren">)</span>
+
; ''<span class="pre">class</span>'' <span class="sig-prename descclassname"><span class="pre">optparse.</span></span><span class="sig-name descname"><span class="pre">OptionParser</span></span><span class="sig-paren">(</span>''<span class="pre">...</span>''<span class="sig-paren">)</span>
: The OptionParser constructor has no required arguments, but a number of optional keyword arguments. You should always pass them as keyword arguments, i.e. do not rely on the order in which the arguments are declared.
+
: OptionParser 构造函数没有必需的参数,但有一些可选的关键字参数。 您应该始终将它们作为关键字参数传递,即 不要依赖声明参数的顺序。
;; <code>usage</code> (default: <code>&quot;%prog [options]&quot;</code>)
+
;; <code>usage</code>(默认:<code>&quot;%prog [options]&quot;</code>
;: The usage summary to print when your program is run incorrectly or with a help option. When [[#module-optparse|<code>optparse</code>]] prints the usage string, it expands <code>%prog</code> to <code>os.path.basename(sys.argv[0])</code> (or to <code>prog</code> if you passed that keyword argument). To suppress a usage message, pass the special value <code>optparse.SUPPRESS_USAGE</code>.
+
;: 当您的程序运行不正确或带有帮助选项时要打印的使用摘要。 当 [[#module-optparse|optparse]] 打印用法字符串时,它会将 <code>%prog</code> 扩展为 <code>os.path.basename(sys.argv[0])</code>(如果您传递了该关键字参数,则扩展为 <code>prog</code>)。 要禁止使用消息,请传递特殊值 <code>optparse.SUPPRESS_USAGE</code>
;; <code>option_list</code> (default: <code>[]</code>)
+
;; <code>option_list</code>(默认:<code>[]</code>
;: A list of Option objects to populate the parser with. The options in <code>option_list</code> are added after any options in <code>standard_option_list</code> (a class attribute that may be set by OptionParser subclasses), but before any version or help options. Deprecated; use [[#optparse.OptionParser.add_option|<code>add_option()</code>]] after creating the parser instead.
+
;: 用于填充解析器的 Option 对象列表。 <code>option_list</code> 中的选项添加在 <code>standard_option_list</code> 中的任何选项之后(可由 OptionParser 子类设置的类属性),但在任何版本或帮助选项之前。 已弃用; 改为在创建解析器后使用 [[#optparse.OptionParser.add_option|add_option()]]
;; <code>option_class</code> (default: optparse.Option)
+
;; <code>option_class</code>(默认值:optparse.Option)
;: Class to use when adding options to the parser in [[#optparse.OptionParser.add_option|<code>add_option()</code>]].
+
;: [[#optparse.OptionParser.add_option|add_option()]] 中向解析器添加选项时使用的类。
;; <code>version</code> (default: <code>None</code>)
+
;; <code>version</code>(默认:<code>None</code>
;: A version string to print when the user supplies a version option. If you supply a true value for <code>version</code>, [[#module-optparse|<code>optparse</code>]] automatically adds a version option with the single option string <code>--version</code>. The substring <code>%prog</code> is expanded the same as for <code>usage</code>.
+
;: 当用户提供版本选项时要打印的版本字符串。 如果您为 <code>version</code> 提供真值,[[#module-optparse|optparse]] 会自动添加带有单个选项字符串 <code>--version</code> 的版本选项。 子串 <code>%prog</code> 的扩展方式与 <code>usage</code> 相同。
;; <code>conflict_handler</code> (default: <code>&quot;error&quot;</code>)
+
;; <code>conflict_handler</code>(默认:<code>&quot;error&quot;</code>
;: Specifies what to do when options with conflicting option strings are added to the parser; see section [[#optparse-conflicts-between-options|<span class="std std-ref">Conflicts between options</span>]].
+
;: 指定将具有冲突选项字符串的选项添加到解析器时要执行的操作; 参见章节 [[#optparse-conflicts-between-options|选项之间的冲突]]
;; <code>description</code> (default: <code>None</code>)
+
;; <code>description</code>(默认:<code>None</code>
;: A paragraph of text giving a brief overview of your program. [[#module-optparse|<code>optparse</code>]] reformats this paragraph to fit the current terminal width and prints it when the user requests help (after <code>usage</code>, but before the list of options).
+
;: 一段文字,简要概述您的程序。 [[#module-optparse|optparse]] 重新格式化此段落以适应当前终端宽度并在用户请求帮助时打印它(在 <code>usage</code> 之后,但在选项列表之前)。
;; <code>formatter</code> (default: a new <code>IndentedHelpFormatter</code>)
+
;; <code>formatter</code>(默认:新的 <code>IndentedHelpFormatter</code>
;: An instance of optparse.HelpFormatter that will be used for printing help text. [[#module-optparse|<code>optparse</code>]] provides two concrete classes for this purpose: IndentedHelpFormatter and TitledHelpFormatter.
+
;: optparse.HelpFormatter 的一个实例,用于打印帮助文本。 [[#module-optparse|optparse]] 为此提供了两个具体的类:IndentedHelpFormatter 和 TitledHelpFormatter。
;; <code>add_help_option</code> (default: <code>True</code>)
+
;; <code>add_help_option</code>(默认:<code>True</code>
;: If true, [[#module-optparse|<code>optparse</code>]] will add a help option (with option strings <code>-h</code> and <code>--help</code>) to the parser.
+
;: 如果为 true,[[#module-optparse|optparse]] 将向解析器添加一个帮助选项(带有选项字符串 <code>-h</code> <code>--help</code>)。
 
;; <code>prog</code>
 
;; <code>prog</code>
;: The string to use when expanding <code>%prog</code> in <code>usage</code> and <code>version</code> instead of <code>os.path.basename(sys.argv[0])</code>.
+
;: <code>usage</code> <code>version</code> 中扩展 <code>%prog</code> 而不是 <code>os.path.basename(sys.argv[0])</code> 时使用的字符串。
;; <code>epilog</code> (default: <code>None</code>)
+
;; <code>epilog</code>(默认:<code>None</code>
;: A paragraph of help text to print after the option help.
+
;: 在选项帮助之后打印的一段帮助文本。
  
  
第1,054行: 第854行:
  
 
<span id="optparse-populating-parser"></span>
 
<span id="optparse-populating-parser"></span>
=== Populating the parser ===
+
=== 填充解析器 ===
  
There are several ways to populate the parser with options. The preferred way
+
有几种方法可以用选项填充解析器。 首选方法是使用 [[#optparse.OptionParser.add_option|OptionParser.add_option()]],如 [[#optparse-tutorial|Tutorial]] 部分所示。 <code>add_option()</code> 可以通过以下两种方式之一调用:
is by using [[#optparse.OptionParser.add_option|<code>OptionParser.add_option()</code>]], as shown in section
 
[[#optparse-tutorial|<span class="std std-ref">Tutorial</span>]]. <code>add_option()</code> can be called in one of two ways:
 
  
* pass it an Option instance (as returned by <code>make_option()</code>)
+
* 传递给它一个 Option 实例(由 <code>make_option()</code> 返回)
* pass it any combination of positional and keyword arguments that are acceptable to <code>make_option()</code> (i.e., to the Option constructor), and it will create the Option instance for you
+
* <code>make_option()</code> 可接受的位置和关键字参数的任意组合传递给它(即传递给 Option 构造函数),它将为您创建 Option 实例
  
The other alternative is to pass a list of pre-constructed Option instances to
+
另一种选择是将预先构造的 Option 实例列表传递给 OptionParser 构造函数,如下所示:
the OptionParser constructor, as in:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第1,070行: 第867行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>option_list = [
+
<syntaxhighlight lang="python3">option_list = [
     make_option(&quot;-f&quot;, &quot;--filename&quot;,
+
     make_option("-f", "--filename",
                 action=&quot;store&quot;, type=&quot;string&quot;, dest=&quot;filename&quot;),
+
                 action="store", type="string", dest="filename"),
     make_option(&quot;-q&quot;, &quot;--quiet&quot;,
+
     make_option("-q", "--quiet",
                 action=&quot;store_false&quot;, dest=&quot;verbose&quot;),
+
                 action="store_false", dest="verbose"),
 
     ]
 
     ]
parser = OptionParser(option_list=option_list)</pre>
+
parser = OptionParser(option_list=option_list)</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
(<code>make_option()</code> is a factory function for creating Option instances;
+
<code>make_option()</code> 是用于创建 Option 实例的工厂函数;目前它是 Option 构造函数的别名。 [[#module-optparse|optparse]] 的未来版本可能会将 Option 拆分为几个类,而 <code>make_option()</code> 将选择正确的类进行实例化。 不要直接实例化 Option。)
currently it is an alias for the Option constructor. A future version of
 
[[#module-optparse|<code>optparse</code>]] may split Option into several classes, and <code>make_option()</code>
 
will pick the right class to instantiate. Do not instantiate Option directly.)
 
  
  
第1,091行: 第885行:
  
 
<span id="optparse-defining-options"></span>
 
<span id="optparse-defining-options"></span>
=== Defining options ===
+
=== 定义选项 ===
  
Each Option instance represents a set of synonymous command-line option strings,
+
每个 Option 实例代表一组同义的命令行选项字符串,例如 <code>-f</code> <code>--file</code>。 您可以指定任意数量的短选项字符串或长选项字符串,但必须至少指定一个整体选项字符串。
e.g. <code>-f</code> and <code>--file</code>. You can specify any number of short or
 
long option strings, but you must specify at least one overall option string.
 
  
The canonical way to create an <code>Option</code> instance is with the
+
创建 <code>Option</code> 实例的规范方法是使用 [[#optparse.OptionParser|OptionParser]] 的 <code>add_option()</code> 方法。
<code>add_option()</code> method of [[#optparse.OptionParser|<code>OptionParser</code>]].
 
  
 
<dl>
 
<dl>
<dt><code>OptionParser.</code><code>add_option</code><span class="sig-paren">(</span>''<span class="n">option</span>''<span class="sig-paren">)</span><br />
+
<dt><span class="sig-prename descclassname"><span class="pre">OptionParser.</span></span><span class="sig-name descname"><span class="pre">add_option</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">option</span></span>''<span class="sig-paren">)</span><br />
<code>OptionParser.</code><code>add_option</code><span class="sig-paren">(</span>''*opt_str'', ''attr=value'', ''...''<span class="sig-paren">)</span></dt>
+
<span class="sig-prename descclassname"><span class="pre">OptionParser.</span></span><span class="sig-name descname"><span class="pre">add_option</span></span><span class="sig-paren">(</span>''<span class="pre">*opt_str</span>'', ''<span class="pre">attr=value</span>'', ''<span class="pre">...</span>''<span class="sig-paren">)</span></dt>
<dd><p>To define an option with only a short option string:</p>
+
<dd><p>要定义仅包含短选项字符串的选项:</p>
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
  
 
<div class="highlight">
 
<div class="highlight">
  
<pre>parser.add_option(&quot;-f&quot;, attr=value, ...)</pre>
+
<syntaxhighlight lang="python3">parser.add_option("-f", attr=value, ...)</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
<p>And to define an option with only a long option string:</p>
+
<p>并定义一个只有一个长选项字符串的选项:</p>
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
  
 
<div class="highlight">
 
<div class="highlight">
  
<pre>parser.add_option(&quot;--foo&quot;, attr=value, ...)</pre>
+
<syntaxhighlight lang="python3">parser.add_option("--foo", attr=value, ...)</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
<p>The keyword arguments define attributes of the new Option object. The most
+
<p>关键字参数定义了新 Option 对象的属性。 最重要的选项属性是 [[#optparse.Option.action|action]],它在很大程度上决定了哪些其他属性是相关的或必需的。 如果你传递了不相关的选项属性,或者没有传递必需的属性,[[#module-optparse|optparse]] 会引发一个 <code>OptionError</code> 异常来解释你的错误。</p>
important option attribute is [[#optparse.Option.action|<code>action</code>]], and it largely
+
<p>一个选项的 ''action'' 决定了 [[#module-optparse|optparse]] 在命令行上遇到这个选项时会做什么。 硬编码到 [[#module-optparse|optparse]] 中的标准选项操作是:</p>
determines which other attributes are relevant or required. If you pass
 
irrelevant option attributes, or fail to pass required ones, [[#module-optparse|<code>optparse</code>]]
 
raises an <code>OptionError</code> exception explaining your mistake.</p>
 
<p>An option's ''action'' determines what [[#module-optparse|<code>optparse</code>]] does when it encounters
 
this option on the command-line. The standard option actions hard-coded into
 
[[#module-optparse|<code>optparse</code>]] are:</p>
 
 
<dl>
 
<dl>
 
<dt><code>&quot;store&quot;</code></dt>
 
<dt><code>&quot;store&quot;</code></dt>
<dd><p>store this option's argument (default)</p></dd>
+
<dd><p>存储此选项的参数(默认)</p></dd>
 
<dt><code>&quot;store_const&quot;</code></dt>
 
<dt><code>&quot;store_const&quot;</code></dt>
<dd><p>store a constant value</p></dd>
+
<dd><p>存储一个常数值</p></dd>
 
<dt><code>&quot;store_true&quot;</code></dt>
 
<dt><code>&quot;store_true&quot;</code></dt>
<dd><p>store <code>True</code></p></dd>
+
<dd><p>商店 <code>True</code></p></dd>
 
<dt><code>&quot;store_false&quot;</code></dt>
 
<dt><code>&quot;store_false&quot;</code></dt>
<dd><p>store <code>False</code></p></dd>
+
<dd><p>商店 <code>False</code></p></dd>
 
<dt><code>&quot;append&quot;</code></dt>
 
<dt><code>&quot;append&quot;</code></dt>
<dd><p>append this option's argument to a list</p></dd>
+
<dd><p>将此选项的参数附加到列表中</p></dd>
 
<dt><code>&quot;append_const&quot;</code></dt>
 
<dt><code>&quot;append_const&quot;</code></dt>
<dd><p>append a constant value to a list</p></dd>
+
<dd><p>将常量值附加到列表</p></dd>
 
<dt><code>&quot;count&quot;</code></dt>
 
<dt><code>&quot;count&quot;</code></dt>
<dd><p>increment a counter by one</p></dd>
+
<dd><p>将计数器加一</p></dd>
 
<dt><code>&quot;callback&quot;</code></dt>
 
<dt><code>&quot;callback&quot;</code></dt>
<dd><p>call a specified function</p></dd>
+
<dd><p>调用指定的函数</p></dd>
 
<dt><code>&quot;help&quot;</code></dt>
 
<dt><code>&quot;help&quot;</code></dt>
<dd><p>print a usage message including all options and the documentation for them</p></dd></dl>
+
<dd><p>打印使用消息,包括所有选项及其文档</p></dd></dl>
  
<p>(If you don't supply an action, the default is <code>&quot;store&quot;</code>. For this action,
+
<p>(如果您不提供操作,则默认值为 <code>&quot;store&quot;</code>。 对于此操作,您还可以提供 [[#optparse.Option.type|type]] [[#optparse.Option.dest|dest]] 选项属性; 请参阅 [[#optparse-standard-option-actions|标准选项操作]] 。)</p></dd></dl>
you may also supply [[#optparse.Option.type|<code>type</code>]] and [[#optparse.Option.dest|<code>dest</code>]] option
 
attributes; see [[#optparse-standard-option-actions|<span class="std std-ref">Standard option actions</span>]].)</p></dd></dl>
 
  
As you can see, most actions involve storing or updating a value somewhere.
+
如您所见,大多数操作都涉及在某处存储或更新值。 [[#module-optparse|optparse]] 总是为此创建一个特殊的对象,通常称为 <code>options</code>(它恰好是 <code>optparse.Values</code> 的一个实例)。 根据 [[#optparse.Option.dest|dest]](目标)选项属性,选项参数(和各种其他值)被存储为此对象的属性。
[[#module-optparse|<code>optparse</code>]] always creates a special object for this, conventionally called
 
<code>options</code> (it happens to be an instance of <code>optparse.Values</code>). Option
 
arguments (and various other values) are stored as attributes of this object,
 
according to the [[#optparse.Option.dest|<code>dest</code>]] (destination) option attribute.
 
  
For example, when you call
+
例如,当你打电话
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第1,167行: 第946行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>parser.parse_args()</pre>
+
<syntaxhighlight lang="python3">parser.parse_args()</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
one of the first things [[#module-optparse|<code>optparse</code>]] does is create the <code>options</code> object:
+
[[#module-optparse|optparse]] 做的第一件事就是创建 <code>options</code> 对象:
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第1,178行: 第957行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>options = Values()</pre>
+
<syntaxhighlight lang="python3">options = Values()</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
If one of the options in this parser is defined with
+
如果此解析器中的选项之一定义为
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第1,189行: 第968行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>parser.add_option(&quot;-f&quot;, &quot;--file&quot;, action=&quot;store&quot;, type=&quot;string&quot;, dest=&quot;filename&quot;)</pre>
+
<syntaxhighlight lang="python3">parser.add_option("-f", "--file", action="store", type="string", dest="filename")</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
and the command-line being parsed includes any of the following:
+
并且正在解析的命令行包括以下任何一项:
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第1,200行: 第979行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>-ffoo
+
<syntaxhighlight lang="python3">-ffoo
 
-f foo
 
-f foo
 
--file=foo
 
--file=foo
--file foo</pre>
+
--file foo</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
then [[#module-optparse|<code>optparse</code>]], on seeing this option, will do the equivalent of
+
然后[[#module-optparse|optparse]],看到这个选项,会做相当于
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第1,214行: 第993行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>options.filename = &quot;foo&quot;</pre>
+
<syntaxhighlight lang="python3">options.filename = "foo"</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
The [[#optparse.Option.type|<code>type</code>]] and [[#optparse.Option.dest|<code>dest</code>]] option attributes are almost
+
[[#optparse.Option.type|type]] [[#optparse.Option.dest|dest]] 选项属性几乎与 [[#optparse.Option.action|action]] 一样重要,但 [[#optparse.Option.action|action]] 是唯一对 ''有意义的属性所有'' 选项。
as important as [[#optparse.Option.action|<code>action</code>]], but [[#optparse.Option.action|<code>action</code>]] is the only
 
one that makes sense for ''all'' options.
 
  
  
第1,228行: 第1,005行:
  
 
<span id="optparse-option-attributes"></span>
 
<span id="optparse-option-attributes"></span>
=== Option attributes ===
+
=== 选项属性 ===
  
The following option attributes may be passed as keyword arguments to
+
以下选项属性可以作为关键字参数传递给 [[#optparse.OptionParser.add_option|OptionParser.add_option()]]。 如果您传递与特定选项无关的选项属性,或者无法传递必需的选项属性,则 [[#module-optparse|optparse]] 引发 <code>OptionError</code>
[[#optparse.OptionParser.add_option|<code>OptionParser.add_option()</code>]]. If you pass an option attribute that is not
 
relevant to a particular option, or fail to pass a required option attribute,
 
[[#module-optparse|<code>optparse</code>]] raises <code>OptionError</code>.
 
  
 
<dl>
 
<dl>
<dt><code>Option.</code><code>action</code></dt>
+
<dt><span class="sig-prename descclassname"><span class="pre">Option.</span></span><span class="sig-name descname"><span class="pre">action</span></span></dt>
<dd><p>(default: <code>&quot;store&quot;</code>)</p>
+
<dd><p>(默认:<code>&quot;store&quot;</code></p>
<p>Determines [[#module-optparse|<code>optparse</code>]]'s behaviour when this option is seen on the
+
<p>确定在命令行上看到此选项时 [[#module-optparse|optparse]] 的行为; 可用选项记录在 [[#optparse-standard-option-actions|此处]] </p></dd></dl>
command line; the available options are documented [[#optparse-standard-option-actions|<span class="std std-ref">here</span>]].</p></dd></dl>
 
  
 
<dl>
 
<dl>
<dt><code>Option.</code><code>type</code></dt>
+
<dt><span class="sig-prename descclassname"><span class="pre">Option.</span></span><span class="sig-name descname"><span class="pre">type</span></span></dt>
<dd><p>(default: <code>&quot;string&quot;</code>)</p>
+
<dd><p>(默认:<code>&quot;string&quot;</code></p>
<p>The argument type expected by this option (e.g., <code>&quot;string&quot;</code> or <code>&quot;int&quot;</code>);
+
<p>此选项预期的参数类型(例如,<code>&quot;string&quot;</code> <code>&quot;int&quot;</code>); 可用的选项类型记录在 [[#optparse-standard-option-types|此处]] </p></dd></dl>
the available option types are documented [[#optparse-standard-option-types|<span class="std std-ref">here</span>]].</p></dd></dl>
 
  
 
<dl>
 
<dl>
<dt><code>Option.</code><code>dest</code></dt>
+
<dt><span class="sig-prename descclassname"><span class="pre">Option.</span></span><span class="sig-name descname"><span class="pre">dest</span></span></dt>
<dd><p>(default: derived from option strings)</p>
+
<dd><p>(默认:派生自选项字符串)</p>
<p>If the option's action implies writing or modifying a value somewhere, this
+
<p>如果选项的操作意味着在某处写入或修改值,这会告诉 [[#module-optparse|optparse]] 在哪里写入它: [[#optparse.Option.dest|dest]] 命名 [[#module-optparse|optparse 的 <code>options</code> 对象的属性]] 在解析命令行时构建。</p></dd></dl>
tells [[#module-optparse|<code>optparse</code>]] where to write it: [[#optparse.Option.dest|<code>dest</code>]] names an
 
attribute of the <code>options</code> object that [[#module-optparse|<code>optparse</code>]] builds as it parses
 
the command line.</p></dd></dl>
 
  
; <code>Option.</code><code>default</code>
+
; <span class="sig-prename descclassname"><span class="pre">Option.</span></span><span class="sig-name descname"><span class="pre">default</span></span>
: The value to use for this option's destination if the option is not seen on the command line. See also [[#optparse.OptionParser.set_defaults|<code>OptionParser.set_defaults()</code>]].
+
: 如果在命令行上看不到该选项,则用于此选项目标的值。 另见 [[#optparse.OptionParser.set_defaults|OptionParser.set_defaults()]]
  
 
<dl>
 
<dl>
<dt><code>Option.</code><code>nargs</code></dt>
+
<dt><span class="sig-prename descclassname"><span class="pre">Option.</span></span><span class="sig-name descname"><span class="pre">nargs</span></span></dt>
<dd><p>(default: 1)</p>
+
<dd><p>(默认值:1)</p>
<p>How many arguments of type [[#optparse.Option.type|<code>type</code>]] should be consumed when this
+
<p>当看到这个选项时,应该消耗多少类型 [[#optparse.Option.type|type]] 的参数。 如果 &gt; 1,[[#module-optparse|optparse]] 将把一组值存储到 [[#optparse.Option.dest|dest]]</p></dd></dl>
option is seen. If &gt; 1, [[#module-optparse|<code>optparse</code>]] will store a tuple of values to
 
[[#optparse.Option.dest|<code>dest</code>]].</p></dd></dl>
 
  
; <code>Option.</code><code>const</code>
+
; <span class="sig-prename descclassname"><span class="pre">Option.</span></span><span class="sig-name descname"><span class="pre">const</span></span>
: For actions that store a constant value, the constant value to store.
+
: 对于存储常量值的操作,要存储的常量值。
  
; <code>Option.</code><code>choices</code>
+
; <span class="sig-prename descclassname"><span class="pre">Option.</span></span><span class="sig-name descname"><span class="pre">choices</span></span>
: For options of type <code>&quot;choice&quot;</code>, the list of strings the user may choose from.
+
: 对于 <code>&quot;choice&quot;</code> 类型的选项,用户可以选择的字符串列表。
  
; <code>Option.</code><code>callback</code>
+
; <span class="sig-prename descclassname"><span class="pre">Option.</span></span><span class="sig-name descname"><span class="pre">callback</span></span>
: For options with action <code>&quot;callback&quot;</code>, the callable to call when this option is seen. See section [[#optparse-option-callbacks|<span class="std std-ref">Option Callbacks</span>]] for detail on the arguments passed to the callable.
+
: 对于具有动作 <code>&quot;callback&quot;</code> 的选项,当看到此选项时调用的可调用对象。 有关传递给可调用对象的参数的详细信息,请参阅 [[#optparse-option-callbacks|Option Callbacks]] 部分。
  
; <code>Option.</code><code>callback_args</code><br />
+
; <span class="sig-prename descclassname"><span class="pre">Option.</span></span><span class="sig-name descname"><span class="pre">callback_args</span></span><br />
<code>Option.</code><code>callback_kwargs</code>
+
<span class="sig-prename descclassname"><span class="pre">Option.</span></span><span class="sig-name descname"><span class="pre">callback_kwargs</span></span>
: Additional positional and keyword arguments to pass to <code>callback</code> after the four standard callback arguments.
+
: 在四个标准回调参数之后传递给 <code>callback</code> 的附加位置和关键字参数。
  
; <code>Option.</code><code>help</code>
+
; <span class="sig-prename descclassname"><span class="pre">Option.</span></span><span class="sig-name descname"><span class="pre">help</span></span>
: Help text to print for this option when listing all available options after the user supplies a [[#optparse.Option.help|<code>help</code>]] option (such as <code>--help</code>). If no help text is supplied, the option will be listed without help text. To hide this option, use the special value <code>optparse.SUPPRESS_HELP</code>.
+
: 在用户提供 [[#optparse.Option.help|help]] 选项(例如 <code>--help</code>)后列出所有可用选项时,要打印此选项的帮助文本。 如果没有提供帮助文本,选项将在没有帮助文本的情况下列出。 要隐藏此选项,请使用特殊值 <code>optparse.SUPPRESS_HELP</code>
  
 
<dl>
 
<dl>
<dt><code>Option.</code><code>metavar</code></dt>
+
<dt><span class="sig-prename descclassname"><span class="pre">Option.</span></span><span class="sig-name descname"><span class="pre">metavar</span></span></dt>
<dd><p>(default: derived from option strings)</p>
+
<dd><p>(默认:派生自选项字符串)</p>
<p>Stand-in for the option argument(s) to use when printing help text. See
+
<p>打印帮助文本时要使用的选项参数的替代品。 有关示例,请参阅 [[#optparse-tutorial|教程]] 部分。</p></dd></dl>
section [[#optparse-tutorial|<span class="std std-ref">Tutorial</span>]] for an example.</p></dd></dl>
 
  
  
第1,292行: 第1,058行:
  
 
<span id="optparse-standard-option-actions"></span>
 
<span id="optparse-standard-option-actions"></span>
=== Standard option actions ===
+
=== 标准选项操作 ===
  
The various option actions all have slightly different requirements and effects.
+
各种选项操作都有略微不同的要求和效果。 大多数操作都有几个相关的选项属性,您可以指定这些属性来指导 [[#module-optparse|optparse]] 的行为; 一些具有必需的属性,您必须为使用该操作的任何选项指定这些属性。
Most actions have several relevant option attributes which you may specify to
 
guide [[#module-optparse|<code>optparse</code>]]'s behaviour; a few have required attributes, which you
 
must specify for any option using that action.
 
  
 
<ul>
 
<ul>
<li><p><code>&quot;store&quot;</code> [relevant: [[#optparse.Option.type|<code>type</code>]], [[#optparse.Option.dest|<code>dest</code>]],
+
<li><p><code>&quot;store&quot;</code> [相关:[[#optparse.Option.type|type]][[#optparse.Option.dest|dest]][[#optparse.Option.nargs|nargs]][[#optparse.Option.choices|choices]]]</p>
[[#optparse.Option.nargs|<code>nargs</code>]], [[#optparse.Option.choices|<code>choices</code>]]]</p>
+
<p>该选项必须后跟一个参数,该参数根据[[#optparse.Option.type|type]]转换为一个值并存储在[[#optparse.Option.dest|dest]]中。 如果 [[#optparse.Option.nargs|nargs]] &gt; 1,则命令行会消耗多个参数; all 将根据 [[#optparse.Option.type|type]] 转换并作为元组存储到 [[#optparse.Option.dest|dest]]。 请参阅 [[#optparse-standard-option-types|标准选项类型]] 部分。</p>
<p>The option must be followed by an argument, which is converted to a value
+
<p>如果提供 [[#optparse.Option.choices|choices]](字符串列表或元组),则类型默认为 <code>&quot;choice&quot;</code></p>
according to [[#optparse.Option.type|<code>type</code>]] and stored in [[#optparse.Option.dest|<code>dest</code>]]. If
+
<p>如果未提供 [[#optparse.Option.type|type]],则默认为 <code>&quot;string&quot;</code></p>
[[#optparse.Option.nargs|<code>nargs</code>]] &gt; 1, multiple arguments will be consumed from the
+
<p>如果未提供 [[#optparse.Option.dest|dest]],则 [[#module-optparse|optparse]] 从第一个长选项字符串派生目标(例如,<code>--foo-bar</code> 暗示 <code>foo_bar</code>)。 如果没有长选项字符串,[[#module-optparse|optparse]] 从第一个短选项字符串派生目的地(例如,<code>-f</code> 暗示 <code>f</code>)。</p>
command line; all will be converted according to [[#optparse.Option.type|<code>type</code>]] and
+
<p>例子:</p>
stored to [[#optparse.Option.dest|<code>dest</code>]] as a tuple. See the
 
[[#optparse-standard-option-types|<span class="std std-ref">Standard option types</span>]] section.</p>
 
<p>If [[#optparse.Option.choices|<code>choices</code>]] is supplied (a list or tuple of strings), the type
 
defaults to <code>&quot;choice&quot;</code>.</p>
 
<p>If [[#optparse.Option.type|<code>type</code>]] is not supplied, it defaults to <code>&quot;string&quot;</code>.</p>
 
<p>If [[#optparse.Option.dest|<code>dest</code>]] is not supplied, [[#module-optparse|<code>optparse</code>]] derives a destination
 
from the first long option string (e.g., <code>--foo-bar</code> implies
 
<code>foo_bar</code>). If there are no long option strings, [[#module-optparse|<code>optparse</code>]] derives a
 
destination from the first short option string (e.g., <code>-f</code> implies <code>f</code>).</p>
 
<p>Example:</p>
 
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
  
 
<div class="highlight">
 
<div class="highlight">
  
<pre>parser.add_option(&quot;-f&quot;)
+
<syntaxhighlight lang="python3">parser.add_option("-f")
parser.add_option(&quot;-p&quot;, type=&quot;float&quot;, nargs=3, dest=&quot;point&quot;)</pre>
+
parser.add_option("-p", type="float", nargs=3, dest="point")</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
<p>As it parses the command line</p>
+
<p>当它解析命令行时</p>
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
  
 
<div class="highlight">
 
<div class="highlight">
  
<pre>-f foo.txt -p 1 -3.5 4 -fbar.txt</pre>
+
<syntaxhighlight lang="python3">-f foo.txt -p 1 -3.5 4 -fbar.txt</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
<p>[[#module-optparse|<code>optparse</code>]] will set</p>
+
<p>[[#module-optparse|optparse]] 将设置</p>
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
  
 
<div class="highlight">
 
<div class="highlight">
  
<pre>options.f = &quot;foo.txt&quot;
+
<syntaxhighlight lang="python3">options.f = "foo.txt"
 
options.point = (1.0, -3.5, 4.0)
 
options.point = (1.0, -3.5, 4.0)
options.f = &quot;bar.txt&quot;</pre>
+
options.f = "bar.txt"</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div></li>
 
</div></li>
<li><p><code>&quot;store_const&quot;</code> [required: [[#optparse.Option.const|<code>const</code>]]; relevant:
+
<li><p><code>&quot;store_const&quot;</code> [必需:[[#optparse.Option.const|const]]; 相关:[[#optparse.Option.dest|dest]]]</p>
[[#optparse.Option.dest|<code>dest</code>]]]</p>
+
<p>[[#optparse.Option.const|const]] 存储在 [[#optparse.Option.dest|dest]] 中。</p>
<p>The value [[#optparse.Option.const|<code>const</code>]] is stored in [[#optparse.Option.dest|<code>dest</code>]].</p>
+
<p>例子:</p>
<p>Example:</p>
 
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
  
 
<div class="highlight">
 
<div class="highlight">
  
<pre>parser.add_option(&quot;-q&quot;, &quot;--quiet&quot;,
+
<syntaxhighlight lang="python3">parser.add_option("-q", "--quiet",
                   action=&quot;store_const&quot;, const=0, dest=&quot;verbose&quot;)
+
                   action="store_const", const=0, dest="verbose")
parser.add_option(&quot;-v&quot;, &quot;--verbose&quot;,
+
parser.add_option("-v", "--verbose",
                   action=&quot;store_const&quot;, const=1, dest=&quot;verbose&quot;)
+
                   action="store_const", const=1, dest="verbose")
parser.add_option(&quot;--noisy&quot;,
+
parser.add_option("--noisy",
                   action=&quot;store_const&quot;, const=2, dest=&quot;verbose&quot;)</pre>
+
                   action="store_const", const=2, dest="verbose")</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
<p>If <code>--noisy</code> is seen, [[#module-optparse|<code>optparse</code>]] will set</p>
+
<p>如果看到 <code>--noisy</code>,则会设置 [[#module-optparse|optparse]]</p>
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
  
 
<div class="highlight">
 
<div class="highlight">
  
<pre>options.verbose = 2</pre>
+
<syntaxhighlight lang="python3">options.verbose = 2</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div></li>
 
</div></li>
<li><p><code>&quot;store_true&quot;</code> [relevant: [[#optparse.Option.dest|<code>dest</code>]]]</p>
+
<li><p><code>&quot;store_true&quot;</code> [相关:[[#optparse.Option.dest|dest]]]</p>
<p>A special case of <code>&quot;store_const&quot;</code> that stores <code>True</code> to
+
<p><code>&quot;store_const&quot;</code> 的特例,存储 <code>True</code> [[#optparse.Option.dest|dest]]</p></li>
[[#optparse.Option.dest|<code>dest</code>]].</p></li>
+
<li><p><code>&quot;store_false&quot;</code> [相关:[[#optparse.Option.dest|dest]]]</p>
<li><p><code>&quot;store_false&quot;</code> [relevant: [[#optparse.Option.dest|<code>dest</code>]]]</p>
+
<p>类似于 <code>&quot;store_true&quot;</code>,但存储 <code>False</code></p>
<p>Like <code>&quot;store_true&quot;</code>, but stores <code>False</code>.</p>
+
<p>例子:</p>
<p>Example:</p>
 
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
  
 
<div class="highlight">
 
<div class="highlight">
  
<pre>parser.add_option(&quot;--clobber&quot;, action=&quot;store_true&quot;, dest=&quot;clobber&quot;)
+
<syntaxhighlight lang="python3">parser.add_option("--clobber", action="store_true", dest="clobber")
parser.add_option(&quot;--no-clobber&quot;, action=&quot;store_false&quot;, dest=&quot;clobber&quot;)</pre>
+
parser.add_option("--no-clobber", action="store_false", dest="clobber")</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div></li>
 
</div></li>
<li><p><code>&quot;append&quot;</code> [relevant: [[#optparse.Option.type|<code>type</code>]], [[#optparse.Option.dest|<code>dest</code>]],
+
<li><p><code>&quot;append&quot;</code> [相关:[[#optparse.Option.type|type]][[#optparse.Option.dest|dest]][[#optparse.Option.nargs|nargs]][[#optparse.Option.choices|choices]]]</p>
[[#optparse.Option.nargs|<code>nargs</code>]], [[#optparse.Option.choices|<code>choices</code>]]]</p>
+
<p>该选项后必须跟一个参数,该参数附加到 [[#optparse.Option.dest|dest]] 中的列表中。 如果未提供 [[#optparse.Option.dest|dest]] 的默认值,则当 [[#module-optparse|optparse]] 在命令行中首次遇到此选项时,将自动创建一个空列表。 如果 [[#optparse.Option.nargs|nargs]] &gt; 1,则消耗多个参数,并将长度为 [[#optparse.Option.nargs|nargs]] 的元组附加到 [[#optparse.Option.dest|dest]]</p>
<p>The option must be followed by an argument, which is appended to the list in
+
<p>[[#optparse.Option.type|type]] [[#optparse.Option.dest|dest]] 的默认值与 <code>&quot;store&quot;</code> 动作的默认值相同。</p>
[[#optparse.Option.dest|<code>dest</code>]]. If no default value for [[#optparse.Option.dest|<code>dest</code>]] is
+
<p>例子:</p>
supplied, an empty list is automatically created when [[#module-optparse|<code>optparse</code>]] first
 
encounters this option on the command-line. If [[#optparse.Option.nargs|<code>nargs</code>]] &gt; 1,
 
multiple arguments are consumed, and a tuple of length [[#optparse.Option.nargs|<code>nargs</code>]]
 
is appended to [[#optparse.Option.dest|<code>dest</code>]].</p>
 
<p>The defaults for [[#optparse.Option.type|<code>type</code>]] and [[#optparse.Option.dest|<code>dest</code>]] are the same as
 
for the <code>&quot;store&quot;</code> action.</p>
 
<p>Example:</p>
 
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
  
 
<div class="highlight">
 
<div class="highlight">
  
<pre>parser.add_option(&quot;-t&quot;, &quot;--tracks&quot;, action=&quot;append&quot;, type=&quot;int&quot;)</pre>
+
<syntaxhighlight lang="python3">parser.add_option("-t", "--tracks", action="append", type="int")</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
<p>If <code>-t3</code> is seen on the command-line, [[#module-optparse|<code>optparse</code>]] does the equivalent
+
<p>如果在命令行上看到 <code>-t3</code>,则 [[#module-optparse|optparse]] 相当于:</p>
of:</p>
 
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
  
 
<div class="highlight">
 
<div class="highlight">
  
<pre>options.tracks = []
+
<syntaxhighlight lang="python3">options.tracks = []
options.tracks.append(int(&quot;3&quot;))</pre>
+
options.tracks.append(int("3"))</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
<p>If, a little later on, <code>--tracks=4</code> is seen, it does:</p>
+
<p>如果稍后看到 <code>--tracks=4</code>,它会:</p>
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
  
 
<div class="highlight">
 
<div class="highlight">
  
<pre>options.tracks.append(int(&quot;4&quot;))</pre>
+
<syntaxhighlight lang="python3">options.tracks.append(int("4"))</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
<p>The <code>append</code> action calls the <code>append</code> method on the current value of the
+
<p><code>append</code> 操作对选项的当前值调用 <code>append</code> 方法。 这意味着指定的任何默认值都必须具有 <code>append</code> 方法。 这也意味着如果默认值非空,默认元素将出现在选项的解析值中,命令行中的任何值都附加在这些默认值之后:</p>
option. This means that any default value specified must have an <code>append</code>
 
method. It also means that if the default value is non-empty, the default
 
elements will be present in the parsed value for the option, with any values
 
from the command line appended after those default values:</p>
 
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
  
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; parser.add_option(&quot;--files&quot;, action=&quot;append&quot;, default=['~/.mypkg/defaults'])
+
<syntaxhighlight lang="python3">>>> parser.add_option("--files", action="append", default=['~/.mypkg/defaults'])
&gt;&gt;&gt; opts, args = parser.parse_args(['--files', 'overrides.mypkg'])
+
>>> opts, args = parser.parse_args(['--files', 'overrides.mypkg'])
&gt;&gt;&gt; opts.files
+
>>> opts.files
['~/.mypkg/defaults', 'overrides.mypkg']</pre>
+
['~/.mypkg/defaults', 'overrides.mypkg']</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div></li>
 
</div></li>
<li><p><code>&quot;append_const&quot;</code> [required: [[#optparse.Option.const|<code>const</code>]]; relevant:
+
<li><p><code>&quot;append_const&quot;</code> [必需:[[#optparse.Option.const|const]]; 相关:[[#optparse.Option.dest|dest]]]</p>
[[#optparse.Option.dest|<code>dest</code>]]]</p>
+
<p><code>&quot;store_const&quot;</code> 类似,但值 [[#optparse.Option.const|const]] 附加到 [[#optparse.Option.dest|dest]]; 与 <code>&quot;append&quot;</code> 一样,[[#optparse.Option.dest|dest]] 默认为 <code>None</code>,第一次遇到选项时会自动创建一个空列表。</p></li>
<p>Like <code>&quot;store_const&quot;</code>, but the value [[#optparse.Option.const|<code>const</code>]] is appended to
+
<li><p><code>&quot;count&quot;</code> [相关:[[#optparse.Option.dest|dest]]]</p>
[[#optparse.Option.dest|<code>dest</code>]]; as with <code>&quot;append&quot;</code>, [[#optparse.Option.dest|<code>dest</code>]] defaults to
+
<p>增加存储在 [[#optparse.Option.dest|dest]] 的整数。 如果未提供默认值,则 [[#optparse.Option.dest|dest]] 在第一次递增之前设置为零。</p>
<code>None</code>, and an empty list is automatically created the first time the option
+
<p>例子:</p>
is encountered.</p></li>
 
<li><p><code>&quot;count&quot;</code> [relevant: [[#optparse.Option.dest|<code>dest</code>]]]</p>
 
<p>Increment the integer stored at [[#optparse.Option.dest|<code>dest</code>]]. If no default value is
 
supplied, [[#optparse.Option.dest|<code>dest</code>]] is set to zero before being incremented the
 
first time.</p>
 
<p>Example:</p>
 
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
  
 
<div class="highlight">
 
<div class="highlight">
  
<pre>parser.add_option(&quot;-v&quot;, action=&quot;count&quot;, dest=&quot;verbosity&quot;)</pre>
+
<syntaxhighlight lang="python3">parser.add_option("-v", action="count", dest="verbosity")</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
<p>The first time <code>-v</code> is seen on the command line, [[#module-optparse|<code>optparse</code>]] does the
+
<p>第一次在命令行上看到 <code>-v</code>[[#module-optparse|optparse]] 相当于:</p>
equivalent of:</p>
 
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
  
 
<div class="highlight">
 
<div class="highlight">
  
<pre>options.verbosity = 0
+
<syntaxhighlight lang="python3">options.verbosity = 0
options.verbosity += 1</pre>
+
options.verbosity += 1</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
<p>Every subsequent occurrence of <code>-v</code> results in</p>
+
<p>每次出现 <code>-v</code> 都会导致</p>
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
  
 
<div class="highlight">
 
<div class="highlight">
  
<pre>options.verbosity += 1</pre>
+
<syntaxhighlight lang="python3">options.verbosity += 1</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div></li>
 
</div></li>
<li><p><code>&quot;callback&quot;</code> [required: [[#optparse.Option.callback|<code>callback</code>]]; relevant:
+
<li><p><code>&quot;callback&quot;</code> [必填:[[#optparse.Option.callback|回调]]; 相关:[[#optparse.Option.type|type]][[#optparse.Option.nargs|nargs]][[#optparse.Option.callback_args|callback_args]][[#optparse.Option.callback_kwargs|callback_kwargs]]]</p>
[[#optparse.Option.type|<code>type</code>]], [[#optparse.Option.nargs|<code>nargs</code>]], [[#optparse.Option.callback_args|<code>callback_args</code>]],
+
<p>调用[[#optparse.Option.callback|callback]]指定的函数,调用为</p>
[[#optparse.Option.callback_kwargs|<code>callback_kwargs</code>]]]</p>
 
<p>Call the function specified by [[#optparse.Option.callback|<code>callback</code>]], which is called as</p>
 
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
  
 
<div class="highlight">
 
<div class="highlight">
  
<pre>func(option, opt_str, value, parser, *args, **kwargs)</pre>
+
<syntaxhighlight lang="python3">func(option, opt_str, value, parser, *args, **kwargs)</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
<p>See section [[#optparse-option-callbacks|<span class="std std-ref">Option Callbacks</span>]] for more detail.</p></li>
+
<p>有关更多详细信息,请参阅 [[#optparse-option-callbacks|选项回调]] 部分。</p></li>
 
<li><p><code>&quot;help&quot;</code></p>
 
<li><p><code>&quot;help&quot;</code></p>
<p>Prints a complete help message for all the options in the current option
+
<p>打印当前选项解析器中所有选项的完整帮助消息。 帮助消息由传递给 OptionParser 的构造函数的 <code>usage</code> 字符串和传递给每个选项的 [[#optparse.Option.help|help]] 字符串构造而成。</p>
parser. The help message is constructed from the <code>usage</code> string passed to
+
<p>如果没有为选项提供 [[#optparse.Option.help|help]] 字符串,它仍将列在帮助消息中。 要完全省略选项,请使用特殊值 <code>optparse.SUPPRESS_HELP</code></p>
OptionParser's constructor and the [[#optparse.Option.help|<code>help</code>]] string passed to every
+
<p>[[#module-optparse|optparse]] 会自动为所有 OptionParsers 添加一个 [[#optparse.Option.help|help]] 选项,因此您通常不需要创建一个。</p>
option.</p>
+
<p>例子:</p>
<p>If no [[#optparse.Option.help|<code>help</code>]] string is supplied for an option, it will still be
 
listed in the help message. To omit an option entirely, use the special value
 
<code>optparse.SUPPRESS_HELP</code>.</p>
 
<p>[[#module-optparse|<code>optparse</code>]] automatically adds a [[#optparse.Option.help|<code>help</code>]] option to all
 
OptionParsers, so you do not normally need to create one.</p>
 
<p>Example:</p>
 
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
  
 
<div class="highlight">
 
<div class="highlight">
  
<pre>from optparse import OptionParser, SUPPRESS_HELP
+
<syntaxhighlight lang="python3">from optparse import OptionParser, SUPPRESS_HELP
  
 
# usually, a help option is added automatically, but that can
 
# usually, a help option is added automatically, but that can
第1,528行: 第1,252行:
 
parser = OptionParser(add_help_option=False)
 
parser = OptionParser(add_help_option=False)
  
parser.add_option(&quot;-h&quot;, &quot;--help&quot;, action=&quot;help&quot;)
+
parser.add_option("-h", "--help", action="help")
parser.add_option(&quot;-v&quot;, action=&quot;store_true&quot;, dest=&quot;verbose&quot;,
+
parser.add_option("-v", action="store_true", dest="verbose",
                   help=&quot;Be moderately verbose&quot;)
+
                   help="Be moderately verbose")
parser.add_option(&quot;--file&quot;, dest=&quot;filename&quot;,
+
parser.add_option("--file", dest="filename",
                   help=&quot;Input file to read data from&quot;)
+
                   help="Input file to read data from")
parser.add_option(&quot;--secret&quot;, help=SUPPRESS_HELP)</pre>
+
parser.add_option("--secret", help=SUPPRESS_HELP)</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
<p>If [[#module-optparse|<code>optparse</code>]] sees either <code>-h</code> or <code>--help</code> on the command line,
+
<p>如果 [[#module-optparse|optparse]] 在命令行上看到 <code>-h</code> <code>--help</code>,它将向 stdout 打印类似以下帮助消息的内容(假设 <code>sys.argv[0]</code> <code>&quot;foo.py&quot;</code>):</p>
it will print something like the following help message to stdout (assuming
 
<code>sys.argv[0]</code> is <code>&quot;foo.py&quot;</code>):</p>
 
 
<div class="highlight-text notranslate">
 
<div class="highlight-text notranslate">
  
 
<div class="highlight">
 
<div class="highlight">
  
<pre>Usage: foo.py [options]
+
<syntaxhighlight lang="text">Usage: foo.py [options]
  
 
Options:
 
Options:
 
   -h, --help        Show this help message and exit
 
   -h, --help        Show this help message and exit
 
   -v                Be moderately verbose
 
   -v                Be moderately verbose
   --file=FILENAME  Input file to read data from</pre>
+
   --file=FILENAME  Input file to read data from</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
<p>After printing the help message, [[#module-optparse|<code>optparse</code>]] terminates your process with
+
<p>打印帮助信息后,[[#module-optparse|optparse]] <code>sys.exit(0)</code> 终止您的进程。</p></li>
<code>sys.exit(0)</code>.</p></li>
 
 
<li><p><code>&quot;version&quot;</code></p>
 
<li><p><code>&quot;version&quot;</code></p>
<p>Prints the version number supplied to the OptionParser to stdout and exits.
+
<p>将提供给 OptionParser 的版本号打印到 stdout 并退出。 版本号实际上是由OptionParser的<code>print_version()</code>方法格式化打印出来的。 通常仅当 <code>version</code> 参数提供给 OptionParser 构造函数时才相关。 与 [[#optparse.Option.help|help]] 选项一样,您很少会创建 <code>version</code> 选项,因为 [[#module-optparse|optparse]] 会在需要时自动添加它们。</p></li></ul>
The version number is actually formatted and printed by the
 
<code>print_version()</code> method of OptionParser. Generally only relevant if the
 
<code>version</code> argument is supplied to the OptionParser constructor. As with
 
[[#optparse.Option.help|<code>help</code>]] options, you will rarely create <code>version</code> options,
 
since [[#module-optparse|<code>optparse</code>]] automatically adds them when needed.</p></li></ul>
 
  
  
第1,570行: 第1,286行:
  
 
<span id="optparse-standard-option-types"></span>
 
<span id="optparse-standard-option-types"></span>
=== Standard option types ===
+
=== 标准选项类型 ===
  
[[#module-optparse|<code>optparse</code>]] has five built-in option types: <code>&quot;string&quot;</code>, <code>&quot;int&quot;</code>,
+
[[#module-optparse|optparse]] 有五种内置选项类型:<code>&quot;string&quot;</code><code>&quot;int&quot;</code><code>&quot;choice&quot;</code><code>&quot;float&quot;</code> <code>&quot;complex&quot;</code>。 如果您需要添加新的选项类型,请参阅 [[#optparse-extending-optparse|扩展 optparse]] 部分。
<code>&quot;choice&quot;</code>, <code>&quot;float&quot;</code> and <code>&quot;complex&quot;</code>. If you need to add new
 
option types, see section [[#optparse-extending-optparse|<span class="std std-ref">Extending optparse</span>]].
 
  
Arguments to string options are not checked or converted in any way: the text on
+
不以任何方式检查或转换字符串选项的参数:命令行上的文本按原样存储在目标中(或传递给回调)。
the command line is stored in the destination (or passed to the callback) as-is.
 
  
Integer arguments (type <code>&quot;int&quot;</code>) are parsed as follows:
+
整数参数(类型 <code>&quot;int&quot;</code>)解析如下:
  
* if the number starts with <code>0x</code>, it is parsed as a hexadecimal number
+
* 如果数字以<code>0x</code>开头,则解析为十六进制数
* if the number starts with <code>0</code>, it is parsed as an octal number
+
* 如果数字以<code>0</code>开头,则解析为八进制数
* if the number starts with <code>0b</code>, it is parsed as a binary number
+
* 如果数字以<code>0b</code>开头,则解析为二进制数
* otherwise, the number is parsed as a decimal number
+
* 否则,数字被解析为十进制数
  
The conversion is done by calling [[../functions#int|<code>int()</code>]] with the appropriate base (2, 8,
+
转换是通过使用适当的基数(2、8、10 或 16)调用 [[../functions#int|int()]] 来完成的。 如果失败,[[#module-optparse|optparse]] 也会失败,尽管有更有用的错误消息。
10, or 16). If this fails, so will [[#module-optparse|<code>optparse</code>]], although with a more useful
 
error message.
 
  
<code>&quot;float&quot;</code> and <code>&quot;complex&quot;</code> option arguments are converted directly with
+
<code>&quot;float&quot;</code> <code>&quot;complex&quot;</code> 选项参数直接使用 [[../functions#float|float()]] [[../functions#complex|complex()]] 进行转换,具有类似的错误处理。
[[../functions#float|<code>float()</code>]] and [[../functions#complex|<code>complex()</code>]], with similar error-handling.
 
  
<code>&quot;choice&quot;</code> options are a subtype of <code>&quot;string&quot;</code> options. The
+
<code>&quot;choice&quot;</code> 选项是 <code>&quot;string&quot;</code> 选项的子类型。 [[#optparse.Option.choices|choices]] 选项属性(字符串序列)定义了允许的选项参数集。 <code>optparse.check_choice()</code> 将用户提供的选项参数与此主列表进行比较,如果给出无效字符串,则引发 <code>OptionValueError</code>
[[#optparse.Option.choices|<code>choices</code>]] option attribute (a sequence of strings) defines the
 
set of allowed option arguments. <code>optparse.check_choice()</code> compares
 
user-supplied option arguments against this master list and raises
 
<code>OptionValueError</code> if an invalid string is given.
 
  
  
第1,604行: 第1,310行:
  
 
<span id="optparse-parsing-arguments"></span>
 
<span id="optparse-parsing-arguments"></span>
=== Parsing arguments ===
+
=== 解析参数 ===
  
The whole point of creating and populating an OptionParser is to call its
+
创建和填充 OptionParser 的重点是调用它的 <code>parse_args()</code> 方法:
<code>parse_args()</code> method:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第1,613行: 第1,318行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>(options, args) = parser.parse_args(args=None, values=None)</pre>
+
<syntaxhighlight lang="python3">(options, args) = parser.parse_args(args=None, values=None)</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
where the input parameters are
+
其中输入参数是
  
 
; <code>args</code>
 
; <code>args</code>
: the list of arguments to process (default: <code>sys.argv[1:]</code>)
+
: 要处理的参数列表(默认值:<code>sys.argv[1:]</code>
 
; <code>values</code>
 
; <code>values</code>
: an <code>optparse.Values</code> object to store option arguments in (default: a new instance of <code>Values</code>) -- if you give an existing object, the option defaults will not be initialized on it
+
: 一个 <code>optparse.Values</code> 对象来存储选项参数(默认值:<code>Values</code> 的一个新实例)——如果你给一个现有的对象,选项默认值将不会被初始化
  
and the return values are
+
和返回值是
  
 
; <code>options</code>
 
; <code>options</code>
: the same object that was passed in as <code>values</code>, or the optparse.Values instance created by [[#module-optparse|<code>optparse</code>]]
+
: 作为 <code>values</code> 传入的相同对象,或由 [[#module-optparse|optparse]] 创建的 optparse.Values 实例
 
; <code>args</code>
 
; <code>args</code>
: the leftover positional arguments after all options have been processed
+
: 处理完所有选项后剩余的位置参数
  
The most common usage is to supply neither keyword argument. If you supply
+
最常见的用法是不提供关键字参数。 如果您提供 <code>values</code>,它将被重复的 [[../functions#setattr|setattr()]] 调用修改(对于存储到选项目标的每个选项参数大约一个)并由 <code>parse_args()</code> 返回。
<code>values</code>, it will be modified with repeated [[../functions#setattr|<code>setattr()</code>]] calls (roughly one
 
for every option argument stored to an option destination) and returned by
 
<code>parse_args()</code>.
 
  
If <code>parse_args()</code> encounters any errors in the argument list, it calls the
+
如果 <code>parse_args()</code> 在参数列表中遇到任何错误,它会调用 OptionParser <code>error()</code> 方法并带有适当的最终用户错误消息。 这最终会以退出状态 2(命令行错误的传统 Unix 退出状态)终止您的进程。
OptionParser's <code>error()</code> method with an appropriate end-user error message.
 
This ultimately terminates your process with an exit status of 2 (the
 
traditional Unix exit status for command-line errors).
 
  
  
第1,647行: 第1,346行:
  
 
<span id="optparse-querying-manipulating-option-parser"></span>
 
<span id="optparse-querying-manipulating-option-parser"></span>
=== Querying and manipulating your option parser ===
+
=== 查询和操作您的选项解析器 ===
  
The default behavior of the option parser can be customized slightly, and you
+
选项解析器的默认行为可以稍微自定义,您还可以浏览您的选项解析器,看看那里有什么。 OptionParser 提供了几种方法来帮助您:
can also poke around your option parser and see what's there. OptionParser
 
provides several methods to help you out:
 
  
 
<dl>
 
<dl>
<dt><code>OptionParser.</code><code>disable_interspersed_args</code><span class="sig-paren">(</span><span class="sig-paren">)</span></dt>
+
<dt><span class="sig-prename descclassname"><span class="pre">OptionParser.</span></span><span class="sig-name descname"><span class="pre">disable_interspersed_args</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span></dt>
<dd><p>Set parsing to stop on the first non-option. For example, if <code>-a</code> and
+
<dd><p>将解析设置为在第一个非选项上停止。 例如,如果 <code>-a</code> <code>-b</code> 都是不带参数的简单选项,则 [[#module-optparse|optparse]] 通常接受以下语法:</p>
<code>-b</code> are both simple options that take no arguments, [[#module-optparse|<code>optparse</code>]]
 
normally accepts this syntax:</p>
 
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
  
 
<div class="highlight">
 
<div class="highlight">
  
<pre>prog -a arg1 -b arg2</pre>
+
<syntaxhighlight lang="python3">prog -a arg1 -b arg2</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
<p>and treats it as equivalent to</p>
+
<p>并将其视为等价于</p>
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
  
 
<div class="highlight">
 
<div class="highlight">
  
<pre>prog -a -b arg1 arg2</pre>
+
<syntaxhighlight lang="python3">prog -a -b arg1 arg2</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
<p>To disable this feature, call [[#optparse.OptionParser.disable_interspersed_args|<code>disable_interspersed_args()</code>]]. This
+
<p>要禁用此功能,请调用 [[#optparse.OptionParser.disable_interspersed_args|disable_interspersed_args()]]。 这恢复了传统的 Unix 语法,其中选项解析在第一个非选项参数处停止。</p>
restores traditional Unix syntax, where option parsing stops with the first
+
<p>如果您有一个命令处理器运行另一个具有自己的选项的命令,并且您想确保这些选项不会混淆,请使用此选项。 例如,每个命令可能有一组不同的选项。</p></dd></dl>
non-option argument.</p>
 
<p>Use this if you have a command processor which runs another command which has
 
options of its own and you want to make sure these options don't get
 
confused. For example, each command might have a different set of options.</p></dd></dl>
 
  
; <code>OptionParser.</code><code>enable_interspersed_args</code><span class="sig-paren">(</span><span class="sig-paren">)</span>
+
; <span class="sig-prename descclassname"><span class="pre">OptionParser.</span></span><span class="sig-name descname"><span class="pre">enable_interspersed_args</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span>
: Set parsing to not stop on the first non-option, allowing interspersing switches with command arguments. This is the default behavior.
+
: 将解析设置为在第一个非选项上不停止,允许使用命令参数穿插开关。 这是默认行为。
  
; <code>OptionParser.</code><code>get_option</code><span class="sig-paren">(</span>''<span class="n">opt_str</span>''<span class="sig-paren">)</span>
+
; <span class="sig-prename descclassname"><span class="pre">OptionParser.</span></span><span class="sig-name descname"><span class="pre">get_option</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">opt_str</span></span>''<span class="sig-paren">)</span>
: Returns the Option instance with the option string ''opt_str'', or <code>None</code> if no options have that option string.
+
: 如果没有选项具有该选项字符串,则返回带有选项字符串 ''opt_str'' <code>None</code> 的选项实例。
  
; <code>OptionParser.</code><code>has_option</code><span class="sig-paren">(</span>''<span class="n">opt_str</span>''<span class="sig-paren">)</span>
+
; <span class="sig-prename descclassname"><span class="pre">OptionParser.</span></span><span class="sig-name descname"><span class="pre">has_option</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">opt_str</span></span>''<span class="sig-paren">)</span>
: Return <code>True</code> if the OptionParser has an option with option string ''opt_str'' (e.g., <code>-q</code> or <code>--verbose</code>).
+
: 如果 OptionParser 具有带有选项字符串 ''opt_str'' 的选项(例如,<code>-q</code> <code>--verbose</code>),则返回 <code>True</code>。
  
; <code>OptionParser.</code><code>remove_option</code><span class="sig-paren">(</span>''<span class="n">opt_str</span>''<span class="sig-paren">)</span>
+
; <span class="sig-prename descclassname"><span class="pre">OptionParser.</span></span><span class="sig-name descname"><span class="pre">remove_option</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">opt_str</span></span>''<span class="sig-paren">)</span>
: If the [[#optparse.OptionParser|<code>OptionParser</code>]] has an option corresponding to ''opt_str'', that option is removed. If that option provided any other option strings, all of those option strings become invalid. If ''opt_str'' does not occur in any option belonging to this [[#optparse.OptionParser|<code>OptionParser</code>]], raises [[../exceptions#ValueError|<code>ValueError</code>]].
+
: 如果 [[#optparse.OptionParser|OptionParser]] 具有对应于 ''opt_str'' 的选项,则删除该选项。 如果该选项提供了任何其他选项字符串,则所有这些选项字符串都将无效。 如果在属于此 [[#optparse.OptionParser|OptionParser]] 的任何选项中未出现 ''opt_str'',则引发 [[../exceptions#ValueError|ValueError]]
  
  
第1,701行: 第1,392行:
  
 
<span id="optparse-conflicts-between-options"></span>
 
<span id="optparse-conflicts-between-options"></span>
=== Conflicts between options ===
+
=== 选项之间的冲突 ===
  
If you're not careful, it's easy to define options with conflicting option
+
如果您不小心,很容易定义具有冲突选项字符串的选项:
strings:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第1,710行: 第1,400行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>parser.add_option(&quot;-n&quot;, &quot;--dry-run&quot;, ...)
+
<syntaxhighlight lang="python3">parser.add_option("-n", "--dry-run", ...)
 
...
 
...
parser.add_option(&quot;-n&quot;, &quot;--noisy&quot;, ...)</pre>
+
parser.add_option("-n", "--noisy", ...)</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
(This is particularly true if you've defined your own OptionParser subclass with
+
(如果您使用一些标准选项定义了自己的 OptionParser 子类,则尤其如此。)
some standard options.)
 
  
Every time you add an option, [[#module-optparse|<code>optparse</code>]] checks for conflicts with existing
+
每次添加选项时,[[#module-optparse|optparse]] 都会检查与现有选项的冲突。 如果找到,则调用当前的冲突处理机制。 您可以在构造函数中设置冲突处理机制:
options. If it finds any, it invokes the current conflict-handling mechanism.
 
You can set the conflict-handling mechanism either in the constructor:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第1,728行: 第1,415行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>parser = OptionParser(..., conflict_handler=handler)</pre>
+
<syntaxhighlight lang="python3">parser = OptionParser(..., conflict_handler=handler)</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
or with a separate call:
+
或单独调用:
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第1,739行: 第1,426行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>parser.set_conflict_handler(handler)</pre>
+
<syntaxhighlight lang="python3">parser.set_conflict_handler(handler)</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
The available conflict handlers are:
+
可用的冲突处理程序是:
  
 
<blockquote><div>
 
<blockquote><div>
  
; <code>&quot;error&quot;</code> (default)
+
; <code>&quot;error&quot;</code>(默认)
: assume option conflicts are a programming error and raise <code>OptionConflictError</code>
+
: 假设选项冲突是编程错误并引发 <code>OptionConflictError</code>
 
; <code>&quot;resolve&quot;</code>
 
; <code>&quot;resolve&quot;</code>
: resolve option conflicts intelligently (see below)
+
: 智能解决选项冲突(见下文)
  
  
 
</div></blockquote>
 
</div></blockquote>
As an example, let's define an [[#optparse.OptionParser|<code>OptionParser</code>]] that resolves conflicts
+
例如,让我们定义一个 [[#optparse.OptionParser|OptionParser]] 来智能地解决冲突并向其添加冲突选项:
intelligently and add conflicting options to it:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第1,762行: 第1,448行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>parser = OptionParser(conflict_handler=&quot;resolve&quot;)
+
<syntaxhighlight lang="python3">parser = OptionParser(conflict_handler="resolve")
parser.add_option(&quot;-n&quot;, &quot;--dry-run&quot;, ..., help=&quot;do no harm&quot;)
+
parser.add_option("-n", "--dry-run", ..., help="do no harm")
parser.add_option(&quot;-n&quot;, &quot;--noisy&quot;, ..., help=&quot;be noisy&quot;)</pre>
+
parser.add_option("-n", "--noisy", ..., help="be noisy")</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
At this point, [[#module-optparse|<code>optparse</code>]] detects that a previously-added option is already
+
此时,[[#module-optparse|optparse]] 检测到之前添加的选项已经在使用 <code>-n</code> 选项字符串。 由于 <code>conflict_handler</code> <code>&quot;resolve&quot;</code>,它通过从较早选项的选项字符串列表中删除 <code>-n</code> 来解决这种情况。 现在 <code>--dry-run</code> 是用户激活该选项的唯一方法。 如果用户寻求帮助,帮助消息将反映:
using the <code>-n</code> option string. Since <code>conflict_handler</code> is <code>&quot;resolve&quot;</code>,
 
it resolves the situation by removing <code>-n</code> from the earlier option's list of
 
option strings. Now <code>--dry-run</code> is the only way for the user to activate
 
that option. If the user asks for help, the help message will reflect that:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第1,779行: 第1,461行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>Options:
+
<syntaxhighlight lang="python3">Options:
 
   --dry-run    do no harm
 
   --dry-run    do no harm
 
   ...
 
   ...
   -n, --noisy  be noisy</pre>
+
   -n, --noisy  be noisy</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
It's possible to whittle away the option strings for a previously-added option
+
可以删除先前添加的选项的选项字符串,直到没有剩下的选项字符串,并且用户无法从命令行调用该选项。 在这种情况下, [[#module-optparse|optparse]] 会完全删除该选项,因此它不会出现在帮助文本或其他任何地方。 继续我们现有的 OptionParser:
until there are none left, and the user has no way of invoking that option from
 
the command-line. In that case, [[#module-optparse|<code>optparse</code>]] removes that option completely,
 
so it doesn't show up in help text or anywhere else. Carrying on with our
 
existing OptionParser:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第1,797行: 第1,475行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>parser.add_option(&quot;--dry-run&quot;, ..., help=&quot;new dry-run option&quot;)</pre>
+
<syntaxhighlight lang="python3">parser.add_option("--dry-run", ..., help="new dry-run option")</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
At this point, the original <code>-n</code>/<code>--dry-run</code> option is no longer
+
此时,原来的 <code>-n</code>/<code>--dry-run</code> 选项已不可访问,于是 [[#module-optparse|optparse]] 将其移除,留下此帮助文本:
accessible, so [[#module-optparse|<code>optparse</code>]] removes it, leaving this help text:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第1,809行: 第1,486行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>Options:
+
<syntaxhighlight lang="python3">Options:
 
   ...
 
   ...
 
   -n, --noisy  be noisy
 
   -n, --noisy  be noisy
   --dry-run    new dry-run option</pre>
+
   --dry-run    new dry-run option</syntaxhighlight>
  
 
</div>
 
</div>
第1,822行: 第1,499行:
  
 
<span id="optparse-cleanup"></span>
 
<span id="optparse-cleanup"></span>
=== Cleanup ===
+
=== 清理 ===
  
OptionParser instances have several cyclic references. This should not be a
+
OptionParser 实例有几个循环引用。 这对于 Python 的垃圾收集器来说应该不是问题,但是您可能希望在完成后通过在 OptionParser 上调用 <code>destroy()</code> 来显式地中断循环引用。 这在可从 OptionParser 访问大型对象图的长时间运行的应用程序中特别有用。
problem for Python's garbage collector, but you may wish to break the cyclic
 
references explicitly by calling <code>destroy()</code> on your
 
OptionParser once you are done with it. This is particularly useful in
 
long-running applications where large object graphs are reachable from your
 
OptionParser.
 
  
  
第1,836行: 第1,508行:
  
 
<span id="optparse-other-methods"></span>
 
<span id="optparse-other-methods"></span>
=== Other methods ===
+
=== 其他方法 ===
  
OptionParser supports several other public methods:
+
OptionParser 支持其他几种公共方法:
  
; <code>OptionParser.</code><code>set_usage</code><span class="sig-paren">(</span>''<span class="n">usage</span>''<span class="sig-paren">)</span>
+
; <span class="sig-prename descclassname"><span class="pre">OptionParser.</span></span><span class="sig-name descname"><span class="pre">set_usage</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">usage</span></span>''<span class="sig-paren">)</span>
: Set the usage string according to the rules described above for the <code>usage</code> constructor keyword argument. Passing <code>None</code> sets the default usage string; use <code>optparse.SUPPRESS_USAGE</code> to suppress a usage message.
+
: 根据上述规则为 <code>usage</code> 构造函数关键字参数设置用法字符串。 传递 <code>None</code> 设置默认使用字符串; 使用 <code>optparse.SUPPRESS_USAGE</code> 抑制使用消息。
  
; <code>OptionParser.</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">OptionParser.</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 the usage message for the current program (<code>self.usage</code>) to ''file'' (default stdout). Any occurrence of the string <code>%prog</code> in <code>self.usage</code> is replaced with the name of the current program. Does nothing if <code>self.usage</code> is empty or not defined.
+
: 将当前程序 (<code>self.usage</code>) 的使用信息打印到 ''file''(默认标准输出)。 <code>self.usage</code> 中出现的任何字符串 <code>%prog</code> 都将替换为当前程序的名称。 如果 <code>self.usage</code> 为空或未定义,则不执行任何操作。
  
; <code>OptionParser.</code><code>get_usage</code><span class="sig-paren">(</span><span class="sig-paren">)</span>
+
; <span class="sig-prename descclassname"><span class="pre">OptionParser.</span></span><span class="sig-name descname"><span class="pre">get_usage</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span>
: Same as [[#optparse.OptionParser.print_usage|<code>print_usage()</code>]] but returns the usage string instead of printing it.
+
: [[#optparse.OptionParser.print_usage|print_usage()]] 相同,但返回用法字符串而不是打印它。
  
 
<dl>
 
<dl>
<dt><code>OptionParser.</code><code>set_defaults</code><span class="sig-paren">(</span>''dest=value'', ''...''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-prename descclassname"><span class="pre">OptionParser.</span></span><span class="sig-name descname"><span class="pre">set_defaults</span></span><span class="sig-paren">(</span>''<span class="pre">dest=value</span>'', ''<span class="pre">...</span>''<span class="sig-paren">)</span></dt>
<dd><p>Set default values for several option destinations at once. Using
+
<dd><p>一次为多个选项目的地设置默认值。 使用 [[#optparse.OptionParser.set_defaults|set_defaults()]] 是设置选项默认值的首选方式,因为多个选项可以共享相同的目的地。 例如,如果多个“模式”选项都设置了相同的目的地,则其中任何一个都可以设置默认值,最后一个获胜:</p>
[[#optparse.OptionParser.set_defaults|<code>set_defaults()</code>]] is the preferred way to set default values for options,
 
since multiple options can share the same destination. For example, if
 
several &quot;mode&quot; options all set the same destination, any one of them can set
 
the default, and the last one wins:</p>
 
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
  
 
<div class="highlight">
 
<div class="highlight">
  
<pre>parser.add_option(&quot;--advanced&quot;, action=&quot;store_const&quot;,
+
<syntaxhighlight lang="python3">parser.add_option("--advanced", action="store_const",
                   dest=&quot;mode&quot;, const=&quot;advanced&quot;,
+
                   dest="mode", const="advanced",
                   default=&quot;novice&quot;)    # overridden below
+
                   default="novice")    # overridden below
parser.add_option(&quot;--novice&quot;, action=&quot;store_const&quot;,
+
parser.add_option("--novice", action="store_const",
                   dest=&quot;mode&quot;, const=&quot;novice&quot;,
+
                   dest="mode", const="novice",
                   default=&quot;advanced&quot;)  # overrides above setting</pre>
+
                   default="advanced")  # overrides above setting</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
<p>To avoid this confusion, use [[#optparse.OptionParser.set_defaults|<code>set_defaults()</code>]]:</p>
+
<p>为避免这种混淆,请使用 [[#optparse.OptionParser.set_defaults|set_defaults()]]</p>
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
  
 
<div class="highlight">
 
<div class="highlight">
  
<pre>parser.set_defaults(mode=&quot;advanced&quot;)
+
<syntaxhighlight lang="python3">parser.set_defaults(mode="advanced")
parser.add_option(&quot;--advanced&quot;, action=&quot;store_const&quot;,
+
parser.add_option("--advanced", action="store_const",
                   dest=&quot;mode&quot;, const=&quot;advanced&quot;)
+
                   dest="mode", const="advanced")
parser.add_option(&quot;--novice&quot;, action=&quot;store_const&quot;,
+
parser.add_option("--novice", action="store_const",
                   dest=&quot;mode&quot;, const=&quot;novice&quot;)</pre>
+
                   dest="mode", const="novice")</syntaxhighlight>
  
 
</div>
 
</div>
第1,892行: 第1,560行:
  
 
<span id="optparse-option-callbacks"></span>
 
<span id="optparse-option-callbacks"></span>
== Option Callbacks ==
+
== 期权回调 ==
  
When [[#module-optparse|<code>optparse</code>]]'s built-in actions and types aren't quite enough for your
+
[[#module-optparse|optparse]] 的内置操作和类型不足以满足您的需求时,您有两种选择:扩展 [[#module-optparse|optparse]] 或定义回调选项。 扩展 [[#module-optparse|optparse]] 更通用,但对于很多简单的情况来说太过分了。 通常,您只需要一个简单的回调即可。
needs, you have two choices: extend [[#module-optparse|<code>optparse</code>]] or define a callback option.
 
Extending [[#module-optparse|<code>optparse</code>]] is more general, but overkill for a lot of simple
 
cases. Quite often a simple callback is all you need.
 
  
There are two steps to defining a callback option:
+
定义回调选项有两个步骤:
  
* define the option itself using the <code>&quot;callback&quot;</code> action
+
* 使用 <code>&quot;callback&quot;</code> 操作定义选项本身
* write the callback; this is a function (or method) that takes at least four arguments, as described below
+
* 编写回调; 这是一个函数(或方法),它至少需要四个参数,如下所述
  
 
<div id="defining-a-callback-option" class="section">
 
<div id="defining-a-callback-option" class="section">
  
 
<span id="optparse-defining-callback-option"></span>
 
<span id="optparse-defining-callback-option"></span>
=== Defining a callback option ===
+
=== 定义回调选项 ===
  
As always, the easiest way to define a callback option is by using the
+
与往常一样,定义回调选项的最简单方法是使用 [[#optparse.OptionParser.add_option|OptionParser.add_option()]] 方法。 除了 [[#optparse.Option.action|action]],您必须指定的唯一选项属性是 <code>callback</code>,要调用的函数:
[[#optparse.OptionParser.add_option|<code>OptionParser.add_option()</code>]] method. Apart from [[#optparse.Option.action|<code>action</code>]], the
 
only option attribute you must specify is <code>callback</code>, the function to call:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第1,917行: 第1,580行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>parser.add_option(&quot;-c&quot;, action=&quot;callback&quot;, callback=my_callback)</pre>
+
<syntaxhighlight lang="python3">parser.add_option("-c", action="callback", callback=my_callback)</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
<code>callback</code> is a function (or other callable object), so you must have already
+
<code>callback</code> 是一个函数(或其他可调用对象),因此您在创建此回调选项时必须已经定义了 <code>my_callback()</code>。 在这个简单的例子中,[[#module-optparse|optparse]] 甚至不知道 <code>-c</code> 是否接受任何参数,这通常意味着该选项不接受任何参数——仅仅存在 <code>-c</code> 在命令行是它需要知道的全部。 但是,在某些情况下,您可能希望回调使用任意数量的命令行参数。 这就是编写回调变得棘手的地方; 本节稍后将对其进行介绍。
defined <code>my_callback()</code> when you create this callback option. In this simple
 
case, [[#module-optparse|<code>optparse</code>]] doesn't even know if <code>-c</code> takes any arguments,
 
which usually means that the option takes no arguments---the mere presence of
 
<code>-c</code> on the command-line is all it needs to know. In some
 
circumstances, though, you might want your callback to consume an arbitrary
 
number of command-line arguments. This is where writing callbacks gets tricky;
 
it's covered later in this section.
 
  
[[#module-optparse|<code>optparse</code>]] always passes four particular arguments to your callback, and it
+
[[#module-optparse|optparse]] 总是向你的回调传递四个特定的参数,如果你通过 [[#optparse.Option.callback_args|callback_args]] [[#optparse.Option.callback_kwargs|callback_kwargs]] 指定它们,它只会传递额外的参数。 因此,最小的回调函数签名是:
will only pass additional arguments if you specify them via
 
[[#optparse.Option.callback_args|<code>callback_args</code>]] and [[#optparse.Option.callback_kwargs|<code>callback_kwargs</code>]]. Thus, the
 
minimal callback function signature is:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第1,940行: 第1,593行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>def my_callback(option, opt, value, parser):</pre>
+
<syntaxhighlight lang="python3">def my_callback(option, opt, value, parser):</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
The four arguments to a callback are described below.
+
回调的四个参数如下所述。
  
There are several other option attributes that you can supply when you define a
+
在定义回调选项时,您还可以提供其他几个选项属性:
callback option:
 
  
 
; [[#optparse.Option.type|<code>type</code>]]
 
; [[#optparse.Option.type|<code>type</code>]]
: has its usual meaning: as with the <code>&quot;store&quot;</code> or <code>&quot;append&quot;</code> actions, it instructs [[#module-optparse|<code>optparse</code>]] to consume one argument and convert it to [[#optparse.Option.type|<code>type</code>]]. Rather than storing the converted value(s) anywhere, though, [[#module-optparse|<code>optparse</code>]] passes it to your callback function.
+
: 具有其通常的含义:与 <code>&quot;store&quot;</code> <code>&quot;append&quot;</code> 操作一样,它指示 [[#module-optparse|optparse]] 使用一个参数并将其转换为 [[#optparse.Option.type|type]]。 但是,[[#module-optparse|optparse]] 不是将转换后的值存储在任何地方,而是将其传递给您的回调函数。
 
; [[#optparse.Option.nargs|<code>nargs</code>]]
 
; [[#optparse.Option.nargs|<code>nargs</code>]]
: also has its usual meaning: if it is supplied and &gt; 1, [[#module-optparse|<code>optparse</code>]] will consume [[#optparse.Option.nargs|<code>nargs</code>]] arguments, each of which must be convertible to [[#optparse.Option.type|<code>type</code>]]. It then passes a tuple of converted values to your callback.
+
: 也有其通常的含义:如果提供并且 &gt; 1,[[#module-optparse|optparse]] 将消耗 [[#optparse.Option.nargs|nargs]] 参数,每个参数都必须可转换为 [[#optparse.Option.type|type]]。 然后它将转换后的值的元组传递给您的回调。
 
; [[#optparse.Option.callback_args|<code>callback_args</code>]]
 
; [[#optparse.Option.callback_args|<code>callback_args</code>]]
: a tuple of extra positional arguments to pass to the callback
+
: 传递给回调的额外位置参数的元组
 
; [[#optparse.Option.callback_kwargs|<code>callback_kwargs</code>]]
 
; [[#optparse.Option.callback_kwargs|<code>callback_kwargs</code>]]
: a dictionary of extra keyword arguments to pass to the callback
+
: 传递给回调的额外关键字参数字典
  
  
第1,964行: 第1,616行:
  
 
<span id="optparse-how-callbacks-called"></span>
 
<span id="optparse-how-callbacks-called"></span>
=== How callbacks are called ===
+
=== 如何调用回调 ===
  
All callbacks are called as follows:
+
所有回调的调用方式如下:
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第1,972行: 第1,624行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>func(option, opt_str, value, parser, *args, **kwargs)</pre>
+
<syntaxhighlight lang="python3">func(option, opt_str, value, parser, *args, **kwargs)</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
where
+
在哪里
  
 
; <code>option</code>
 
; <code>option</code>
: is the Option instance that's calling the callback
+
: 是调用回调的 Option 实例
 
; <code>opt_str</code>
 
; <code>opt_str</code>
: is the option string seen on the command-line that's triggering the callback. (If an abbreviated long option was used, <code>opt_str</code> will be the full, canonical option string---e.g. if the user puts <code>--foo</code> on the command-line as an abbreviation for <code>--foobar</code>, then <code>opt_str</code> will be <code>&quot;--foobar&quot;</code>.)
+
: 是在命令行上看到的触发回调的选项字符串。 (如果使用了缩写的 long 选项,<code>opt_str</code> 将是完整的、规范的选项字符串——例如 如果用户在命令行中将 <code>--foo</code> 作为 <code>--foobar</code> 的缩写,则 <code>opt_str</code> 将是 <code>&quot;--foobar&quot;</code>。)
 
; <code>value</code>
 
; <code>value</code>
: is the argument to this option seen on the command-line. [[#module-optparse|<code>optparse</code>]] will only expect an argument if [[#optparse.Option.type|<code>type</code>]] is set; the type of <code>value</code> will be the type implied by the option's type. If [[#optparse.Option.type|<code>type</code>]] for this option is <code>None</code> (no argument expected), then <code>value</code> will be <code>None</code>. If [[#optparse.Option.nargs|<code>nargs</code>]] &gt; 1, <code>value</code> will be a tuple of values of the appropriate type.
+
: 是在命令行上看到的此选项的参数。 [[#module-optparse|optparse]] 仅在设置了 [[#optparse.Option.type|type]] 时才需要一个参数; <code>value</code> 的类型将是选项类型隐含的类型。 如果此选项的 [[#optparse.Option.type|type]] <code>None</code>(预期无参数),则 <code>value</code> 将为 <code>None</code>。 如果 [[#optparse.Option.nargs|nargs]] &gt; 1,<code>value</code> 将是适当类型的值的元组。
 
; <code>parser</code>
 
; <code>parser</code>
: is the OptionParser instance driving the whole thing, mainly useful because you can access some other interesting data through its instance attributes:
+
: 是驱动整个事情的 OptionParser 实例,主要是因为你可以通过它的实例属性访问一些其他有趣的数据:
 
;; <code>parser.largs</code>
 
;; <code>parser.largs</code>
;: the current list of leftover arguments, ie. arguments that have been consumed but are neither options nor option arguments. Feel free to modify <code>parser.largs</code>, e.g. by adding more arguments to it. (This list will become <code>args</code>, the second return value of <code>parse_args()</code>.)
+
;: 剩余参数的当前列表,即。 已使用但既不是选项也不是选项参数的参数。 随意修改<code>parser.largs</code>,例如 通过向它添加更多参数。 (这个列表会变成<code>args</code><code>parse_args()</code>的第二个返回值。)
 
;; <code>parser.rargs</code>
 
;; <code>parser.rargs</code>
;: the current list of remaining arguments, ie. with <code>opt_str</code> and <code>value</code> (if applicable) removed, and only the arguments following them still there. Feel free to modify <code>parser.rargs</code>, e.g. by consuming more arguments.
+
;: 剩余参数的当前列表,即。 删除了 <code>opt_str</code> <code>value</code>(如果适用),只有它们后面的参数仍然存在。 随意修改<code>parser.rargs</code>,例如 通过消耗更多参数。
 
;; <code>parser.values</code>
 
;; <code>parser.values</code>
;: the object where option values are by default stored (an instance of optparse.OptionValues). This lets callbacks use the same mechanism as the rest of [[#module-optparse|<code>optparse</code>]] for storing option values; you don't need to mess around with globals or closures. You can also access or modify the value(s) of any options already encountered on the command-line.
+
;: 默认情况下存储选项值的对象(optparse.OptionValues 的一个实例)。 这让回调使用与 [[#module-optparse|optparse]] 的其余部分相同的机制来存储选项值; 你不需要搞乱全局变量或闭包。 您还可以访问或修改已在命令行中遇到的任何选项的值。
 
; <code>args</code>
 
; <code>args</code>
: is a tuple of arbitrary positional arguments supplied via the [[#optparse.Option.callback_args|<code>callback_args</code>]] option attribute.
+
: 是通过 [[#optparse.Option.callback_args|callback_args]] 选项属性提供的任意位置参数的元组。
 
; <code>kwargs</code>
 
; <code>kwargs</code>
: is a dictionary of arbitrary keyword arguments supplied via [[#optparse.Option.callback_kwargs|<code>callback_kwargs</code>]].
+
: 是通过 [[#optparse.Option.callback_kwargs|callback_kwargs]] 提供的任意关键字参数的字典。
  
  
第2,003行: 第1,655行:
  
 
<span id="optparse-raising-errors-in-callback"></span>
 
<span id="optparse-raising-errors-in-callback"></span>
=== Raising errors in a callback ===
+
=== 在回调中引发错误 ===
  
The callback function should raise <code>OptionValueError</code> if there are any
+
如果选项或其参数有任何问题,回调函数应该引发 <code>OptionValueError</code>[[#module-optparse|optparse]] 捕获并终止程序,打印您提供给 stderr 的错误消息。 您的消息应该清晰、简洁、准确,并提及错误的选项。 否则,用户将很难弄清楚他们做错了什么。
problems with the option or its argument(s). [[#module-optparse|<code>optparse</code>]] catches this and
 
terminates the program, printing the error message you supply to stderr. Your
 
message should be clear, concise, accurate, and mention the option at fault.
 
Otherwise, the user will have a hard time figuring out what they did wrong.
 
  
  
第2,016行: 第1,664行:
  
 
<span id="optparse-callback-example-1"></span>
 
<span id="optparse-callback-example-1"></span>
=== Callback example 1: trivial callback ===
+
=== 回调示例 1:普通回调 ===
  
Here's an example of a callback option that takes no arguments, and simply
+
下面是一个不带参数的回调选项的例子,只记录选项被看到:
records that the option was seen:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第2,025行: 第1,672行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>def record_foo_seen(option, opt_str, value, parser):
+
<syntaxhighlight lang="python3">def record_foo_seen(option, opt_str, value, parser):
 
     parser.values.saw_foo = True
 
     parser.values.saw_foo = True
  
parser.add_option(&quot;--foo&quot;, action=&quot;callback&quot;, callback=record_foo_seen)</pre>
+
parser.add_option("--foo", action="callback", callback=record_foo_seen)</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
Of course, you could do that with the <code>&quot;store_true&quot;</code> action.
+
当然,您可以使用 <code>&quot;store_true&quot;</code> 操作来做到这一点。
  
  
第2,040行: 第1,687行:
  
 
<span id="optparse-callback-example-2"></span>
 
<span id="optparse-callback-example-2"></span>
=== Callback example 2: check option order ===
+
=== 回调示例2:检查选项顺序 ===
  
Here's a slightly more interesting example: record the fact that <code>-a</code> is
+
这是一个稍微有趣的例子:记录看到 <code>-a</code> 的事实,但如果它在命令行中出现在 <code>-b</code> 之后,则爆炸。
seen, but blow up if it comes after <code>-b</code> in the command-line.
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第2,049行: 第1,695行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>def check_order(option, opt_str, value, parser):
+
<syntaxhighlight lang="python3">def check_order(option, opt_str, value, parser):
 
     if parser.values.b:
 
     if parser.values.b:
         raise OptionValueError(&quot;can't use -a after -b&quot;)
+
         raise OptionValueError("can't use -a after -b")
 
     parser.values.a = 1
 
     parser.values.a = 1
 
...
 
...
parser.add_option(&quot;-a&quot;, action=&quot;callback&quot;, callback=check_order)
+
parser.add_option("-a", action="callback", callback=check_order)
parser.add_option(&quot;-b&quot;, action=&quot;store_true&quot;, dest=&quot;b&quot;)</pre>
+
parser.add_option("-b", action="store_true", dest="b")</syntaxhighlight>
  
 
</div>
 
</div>
第2,065行: 第1,711行:
  
 
<span id="optparse-callback-example-3"></span>
 
<span id="optparse-callback-example-3"></span>
=== Callback example 3: check option order (generalized) ===
+
=== 回调示例 3:检查选项顺序(广义) ===
  
If you want to re-use this callback for several similar options (set a flag, but
+
如果你想为几个类似的选项重用这个回调(设置一个标志,但如果 <code>-b</code> 已经被看到就会爆炸),它需要一些工作:错误消息和它设置的标志必须概括。
blow up if <code>-b</code> has already been seen), it needs a bit of work: the error
 
message and the flag that it sets must be generalized.
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第2,075行: 第1,719行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>def check_order(option, opt_str, value, parser):
+
<syntaxhighlight lang="python3">def check_order(option, opt_str, value, parser):
 
     if parser.values.b:
 
     if parser.values.b:
         raise OptionValueError(&quot;can't use %s after -b&quot; % opt_str)
+
         raise OptionValueError("can't use %s after -b" % opt_str)
 
     setattr(parser.values, option.dest, 1)
 
     setattr(parser.values, option.dest, 1)
 
...
 
...
parser.add_option(&quot;-a&quot;, action=&quot;callback&quot;, callback=check_order, dest='a')
+
parser.add_option("-a", action="callback", callback=check_order, dest='a')
parser.add_option(&quot;-b&quot;, action=&quot;store_true&quot;, dest=&quot;b&quot;)
+
parser.add_option("-b", action="store_true", dest="b")
parser.add_option(&quot;-c&quot;, action=&quot;callback&quot;, callback=check_order, dest='c')</pre>
+
parser.add_option("-c", action="callback", callback=check_order, dest='c')</syntaxhighlight>
  
 
</div>
 
</div>
第2,092行: 第1,736行:
  
 
<span id="optparse-callback-example-4"></span>
 
<span id="optparse-callback-example-4"></span>
=== Callback example 4: check arbitrary condition ===
+
=== 回调示例4:检查任意条件 ===
  
Of course, you could put any condition in there---you're not limited to checking
+
当然,您可以在其中放置任何条件——您不仅限于检查已定义选项的值。 例如,如果您有不应该在满月时调用的选项,您所要做的就是:
the values of already-defined options. For example, if you have options that
 
should not be called when the moon is full, all you have to do is this:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第2,102行: 第1,744行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>def check_moon(option, opt_str, value, parser):
+
<syntaxhighlight lang="python3">def check_moon(option, opt_str, value, parser):
 
     if is_moon_full():
 
     if is_moon_full():
         raise OptionValueError(&quot;%s option invalid when moon is full&quot;
+
         raise OptionValueError("%s option invalid when moon is full"
 
                               % opt_str)
 
                               % opt_str)
 
     setattr(parser.values, option.dest, 1)
 
     setattr(parser.values, option.dest, 1)
 
...
 
...
parser.add_option(&quot;--foo&quot;,
+
parser.add_option("--foo",
                   action=&quot;callback&quot;, callback=check_moon, dest=&quot;foo&quot;)</pre>
+
                   action="callback", callback=check_moon, dest="foo")</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
(The definition of <code>is_moon_full()</code> is left as an exercise for the reader.)
+
<code>is_moon_full()</code> 的定义留给读者作为练习。)
  
  
第2,121行: 第1,763行:
  
 
<span id="optparse-callback-example-5"></span>
 
<span id="optparse-callback-example-5"></span>
=== Callback example 5: fixed arguments ===
+
=== 回调示例 5:固定参数 ===
  
Things get slightly more interesting when you define callback options that take
+
当您定义采用固定数量参数的回调选项时,事情会变得稍微有趣一些。 指定回调选项采用参数类似于定义 <code>&quot;store&quot;</code> <code>&quot;append&quot;</code> 选项:如果您定义 [[#optparse.Option.type|type]],则该选项采用一个必须可转换为该参数的参数类型; 如果您进一步定义 [[#optparse.Option.nargs|nargs]],则该选项采用 [[#optparse.Option.nargs|nargs]] 参数。
a fixed number of arguments. Specifying that a callback option takes arguments
 
is similar to defining a <code>&quot;store&quot;</code> or <code>&quot;append&quot;</code> option: if you define
 
[[#optparse.Option.type|<code>type</code>]], then the option takes one argument that must be
 
convertible to that type; if you further define [[#optparse.Option.nargs|<code>nargs</code>]], then the
 
option takes [[#optparse.Option.nargs|<code>nargs</code>]] arguments.
 
  
Here's an example that just emulates the standard <code>&quot;store&quot;</code> action:
+
这是一个仅模拟标准 <code>&quot;store&quot;</code> 操作的示例:
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第2,136行: 第1,773行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>def store_value(option, opt_str, value, parser):
+
<syntaxhighlight lang="python3">def store_value(option, opt_str, value, parser):
 
     setattr(parser.values, option.dest, value)
 
     setattr(parser.values, option.dest, value)
 
...
 
...
parser.add_option(&quot;--foo&quot;,
+
parser.add_option("--foo",
                   action=&quot;callback&quot;, callback=store_value,
+
                   action="callback", callback=store_value,
                   type=&quot;int&quot;, nargs=3, dest=&quot;foo&quot;)</pre>
+
                   type="int", nargs=3, dest="foo")</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
Note that [[#module-optparse|<code>optparse</code>]] takes care of consuming 3 arguments and converting
+
请注意, [[#module-optparse|optparse]] 负责使用 3 个参数并将它们转换为整数; 您所要做的就是存储它们。 (或者其他什么;显然你不需要这个例子的回调。)
them to integers for you; all you have to do is store them. (Or whatever;
 
obviously you don't need a callback for this example.)
 
  
  
第2,155行: 第1,790行:
  
 
<span id="optparse-callback-example-6"></span>
 
<span id="optparse-callback-example-6"></span>
=== Callback example 6: variable arguments ===
+
=== 回调示例 6:可变参数 ===
  
Things get hairy when you want an option to take a variable number of arguments.
+
当您想要一个选项来接受可变数量的参数时,事情就会变得棘手。 对于这种情况,您必须编写回调,因为 [[#module-optparse|optparse]] 不为其提供任何内置功能。 而且您必须处理 [[#module-optparse|optparse]] 通常为您处理的传统 Unix 命令行解析的某些复杂问题。 特别是,回调应该为裸 <code>--</code> <code>-</code> 参数实现常规规则:
For this case, you must write a callback, as [[#module-optparse|<code>optparse</code>]] doesn't provide any
 
built-in capabilities for it. And you have to deal with certain intricacies of
 
conventional Unix command-line parsing that [[#module-optparse|<code>optparse</code>]] normally handles for
 
you. In particular, callbacks should implement the conventional rules for bare
 
<code>--</code> and <code>-</code> arguments:
 
  
* either <code>--</code> or <code>-</code> can be option arguments
+
* <code>--</code> <code>-</code> 可以是选项参数
* bare <code>--</code> (if not the argument to some option): halt command-line processing and discard the <code>--</code>
+
* <code>--</code>(如果不是某个选项的参数):停止命令行处理并丢弃 <code>--</code>
* bare <code>-</code> (if not the argument to some option): halt command-line processing but keep the <code>-</code> (append it to <code>parser.largs</code>)
+
* <code>-</code>(如果不是某个选项的参数):停止命令行处理但保留 <code>-</code>(将其附加到 <code>parser.largs</code>
  
If you want an option that takes a variable number of arguments, there are
+
如果您想要一个带有可变数量参数的选项,则需要担心几个微妙而棘手的问题。 您选择的确切实现将基于您愿意为应用程序做出的权衡(这就是 [[#module-optparse|optparse]] 不直接支持此类事情的原因)。
several subtle, tricky issues to worry about. The exact implementation you
 
choose will be based on which trade-offs you're willing to make for your
 
application (which is why [[#module-optparse|<code>optparse</code>]] doesn't support this sort of thing
 
directly).
 
  
Nevertheless, here's a stab at a callback for an option with variable
+
尽管如此,这里还是一个带有可变参数的选项的回调:
arguments:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第2,181行: 第1,806行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>def vararg_callback(option, opt_str, value, parser):
+
<syntaxhighlight lang="python3">def vararg_callback(option, opt_str, value, parser):
 
     assert value is None
 
     assert value is None
 
     value = []
 
     value = []
第2,194行: 第1,819行:
 
     for arg in parser.rargs:
 
     for arg in parser.rargs:
 
         # stop on --foo like options
 
         # stop on --foo like options
         if arg[:2] == &quot;--&quot; and len(arg) &gt; 2:
+
         if arg[:2] == "--" and len(arg) > 2:
 
             break
 
             break
 
         # stop on -a, but not on -3 or -3.0
 
         # stop on -a, but not on -3 or -3.0
         if arg[:1] == &quot;-&quot; and len(arg) &gt; 1 and not floatable(arg):
+
         if arg[:1] == "-" and len(arg) > 1 and not floatable(arg):
 
             break
 
             break
 
         value.append(arg)
 
         value.append(arg)
第2,205行: 第1,830行:
  
 
...
 
...
parser.add_option(&quot;-c&quot;, &quot;--callback&quot;, dest=&quot;vararg_attr&quot;,
+
parser.add_option("-c", "--callback", dest="vararg_attr",
                   action=&quot;callback&quot;, callback=vararg_callback)</pre>
+
                   action="callback", callback=vararg_callback)</syntaxhighlight>
  
 
</div>
 
</div>
第2,218行: 第1,843行:
  
 
<span id="optparse-extending-optparse"></span>
 
<span id="optparse-extending-optparse"></span>
== Extending [[#module-optparse|<code>optparse</code>]] ==
+
== 扩展 optparse ==
  
Since the two major controlling factors in how [[#module-optparse|<code>optparse</code>]] interprets
+
由于 [[#module-optparse|optparse]] 如何解释命令行选项的两个主要控制因素是每个选项的动作和类型,因此最可能的扩展方向是添加新动作和新类型。
command-line options are the action and type of each option, the most likely
 
direction of extension is to add new actions and new types.
 
  
 
<div id="adding-new-types" class="section">
 
<div id="adding-new-types" class="section">
  
 
<span id="optparse-adding-new-types"></span>
 
<span id="optparse-adding-new-types"></span>
=== Adding new types ===
+
=== 添加新类型 ===
  
To add new types, you need to define your own subclass of [[#module-optparse|<code>optparse</code>]]'s
+
要添加新类型,您需要定义自己的 [[#module-optparse|optparse]] <code>Option</code> 类的子类。 这个类有几个定义 [[#module-optparse|optparse]] 类型的属性:[[#optparse.Option.TYPES|TYPES]] [[#optparse.Option.TYPE_CHECKER|TYPE_CHECKER]]
<code>Option</code> class. This class has a couple of attributes that define
 
[[#module-optparse|<code>optparse</code>]]'s types: [[#optparse.Option.TYPES|<code>TYPES</code>]] and [[#optparse.Option.TYPE_CHECKER|<code>TYPE_CHECKER</code>]].
 
  
; <code>Option.</code><code>TYPES</code>
+
; <span class="sig-prename descclassname"><span class="pre">Option.</span></span><span class="sig-name descname"><span class="pre">TYPES</span></span>
: A tuple of type names; in your subclass, simply define a new tuple [[#optparse.Option.TYPES|<code>TYPES</code>]] that builds on the standard one.
+
: 类型名称的元组; 在您的子类中,只需定义一个基于标准元组的新元组 [[#optparse.Option.TYPES|TYPES]]
  
 
<dl>
 
<dl>
<dt><code>Option.</code><code>TYPE_CHECKER</code></dt>
+
<dt><span class="sig-prename descclassname"><span class="pre">Option.</span></span><span class="sig-name descname"><span class="pre">TYPE_CHECKER</span></span></dt>
<dd><p>A dictionary mapping type names to type-checking functions. A type-checking
+
<dd><p>将类型名称映射到类型检查函数的字典。 类型检查函数具有以下签名:</p>
function has the following signature:</p>
 
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
  
 
<div class="highlight">
 
<div class="highlight">
  
<pre>def check_mytype(option, opt, value)</pre>
+
<syntaxhighlight lang="python3">def check_mytype(option, opt, value)</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
<p>where <code>option</code> is an <code>Option</code> instance, <code>opt</code> is an option string
+
<p>其中 <code>option</code> 是一个 <code>Option</code> 实例,<code>opt</code> 是一个选项字符串(例如,<code>-f</code>),而 <code>value</code> 是来自必须检查并转换为所需类型的命令行。 <code>check_mytype()</code> 应该返回一个假设类型 <code>mytype</code> 的对象。 类型检查函数返回的值将在 <code>OptionParser.parse_args()</code> 返回的 OptionValues 实例中结束,或者作为 <code>value</code> 参数传递给回调。</p>
(e.g., <code>-f</code>), and <code>value</code> is the string from the command line that must
+
<p>如果遇到任何问题,您的类型检查函数应该引发 <code>OptionValueError</code><code>OptionValueError</code> 接受单个字符串参数,该参数按原样传递给 [[#optparse.OptionParser|OptionParser]] <code>error()</code> 方法,该方法依次添加程序名称和字符串 [ X168X] 并在终止进程之前将所有内容打印到 stderr。</p></dd></dl>
be checked and converted to your desired type. <code>check_mytype()</code> should
 
return an object of the hypothetical type <code>mytype</code>. The value returned by
 
a type-checking function will wind up in the OptionValues instance returned
 
by <code>OptionParser.parse_args()</code>, or be passed to a callback as the
 
<code>value</code> parameter.</p>
 
<p>Your type-checking function should raise <code>OptionValueError</code> if it
 
encounters any problems. <code>OptionValueError</code> takes a single string
 
argument, which is passed as-is to [[#optparse.OptionParser|<code>OptionParser</code>]]'s <code>error()</code>
 
method, which in turn prepends the program name and the string <code>&quot;error:&quot;</code>
 
and prints everything to stderr before terminating the process.</p></dd></dl>
 
  
Here's a silly example that demonstrates adding a <code>&quot;complex&quot;</code> option type to
+
这是一个愚蠢的示例,演示了在命令行上添加 <code>&quot;complex&quot;</code> 选项类型以解析 Python 样式的复数。 (这比以前更傻了,因为 [[#module-optparse|optparse]] 1.3 添加了对复数的内置支持,但没关系。)
parse Python-style complex numbers on the command line. (This is even sillier
 
than it used to be, because [[#module-optparse|<code>optparse</code>]] 1.3 added built-in support for
 
complex numbers, but never mind.)
 
  
First, the necessary imports:
+
一、必要的进口:
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第2,273行: 第1,880行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>from copy import copy
+
<syntaxhighlight lang="python3">from copy import copy
from optparse import Option, OptionValueError</pre>
+
from optparse import Option, OptionValueError</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
You need to define your type-checker first, since it's referred to later (in the
+
您需要首先定义您的类型检查器,因为它稍后会被引用(在您的 Option 子类的 [[#optparse.Option.TYPE_CHECKER|TYPE_CHECKER]] 类属性中):
[[#optparse.Option.TYPE_CHECKER|<code>TYPE_CHECKER</code>]] class attribute of your Option subclass):
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第2,286行: 第1,892行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>def check_complex(option, opt, value):
+
<syntaxhighlight lang="python3">def check_complex(option, opt, value):
 
     try:
 
     try:
 
         return complex(value)
 
         return complex(value)
 
     except ValueError:
 
     except ValueError:
 
         raise OptionValueError(
 
         raise OptionValueError(
             &quot;option %s: invalid complex value: %r&quot; % (opt, value))</pre>
+
             "option %s: invalid complex value: %r" % (opt, value))</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
Finally, the Option subclass:
+
最后,Option 子类:
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第2,302行: 第1,908行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>class MyOption (Option):
+
<syntaxhighlight lang="python3">class MyOption (Option):
     TYPES = Option.TYPES + (&quot;complex&quot;,)
+
     TYPES = Option.TYPES + ("complex",)
 
     TYPE_CHECKER = copy(Option.TYPE_CHECKER)
 
     TYPE_CHECKER = copy(Option.TYPE_CHECKER)
     TYPE_CHECKER[&quot;complex&quot;] = check_complex</pre>
+
     TYPE_CHECKER["complex"] = check_complex</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
(If we didn't make a [[../copy#module-copy|<code>copy()</code>]] of [[#optparse.Option.TYPE_CHECKER|<code>Option.TYPE_CHECKER</code>]], we would end
+
(如果我们不制作 [[#optparse.Option.TYPE_CHECKER|Option.TYPE_CHECKER]] 的 [[../copy#module-copy|copy()]],我们最终会修改 [[#module-optparse|optparse]] [[#optparse.Option.TYPE_CHECKER|TYPE_CHECKER]] 属性的选项类。 这是 Python,除了礼貌和常识之外,没有什么能阻止你这样做。)
up modifying the [[#optparse.Option.TYPE_CHECKER|<code>TYPE_CHECKER</code>]] attribute of [[#module-optparse|<code>optparse</code>]]'s
 
Option class. This being Python, nothing stops you from doing that except good
 
manners and common sense.)
 
  
That's it! Now you can write a script that uses the new option type just like
+
就是这样! 现在您可以编写一个使用新选项类型的脚本,就像任何其他基于 [[#module-optparse|optparse]] 的脚本一样,除了您必须指示您的 OptionParser 使用 MyOption 而不是 Option:
any other [[#module-optparse|<code>optparse</code>]]-based script, except you have to instruct your
 
OptionParser to use MyOption instead of Option:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第2,323行: 第1,924行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>parser = OptionParser(option_class=MyOption)
+
<syntaxhighlight lang="python3">parser = OptionParser(option_class=MyOption)
parser.add_option(&quot;-c&quot;, type=&quot;complex&quot;)</pre>
+
parser.add_option("-c", type="complex")</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
Alternately, you can build your own option list and pass it to OptionParser; if
+
或者,您可以构建自己的选项列表并将其传递给 OptionParser; 如果不使用上述方式 <code>add_option()</code> ,则不需要告诉 OptionParser 使用哪个选项类:
you don't use <code>add_option()</code> in the above way, you don't need to tell
 
OptionParser which option class to use:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第2,337行: 第1,936行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>option_list = [MyOption(&quot;-c&quot;, action=&quot;store&quot;, type=&quot;complex&quot;, dest=&quot;c&quot;)]
+
<syntaxhighlight lang="python3">option_list = [MyOption("-c", action="store", type="complex", dest="c")]
parser = OptionParser(option_list=option_list)</pre>
+
parser = OptionParser(option_list=option_list)</syntaxhighlight>
  
 
</div>
 
</div>
第2,348行: 第1,947行:
  
 
<span id="optparse-adding-new-actions"></span>
 
<span id="optparse-adding-new-actions"></span>
=== Adding new actions ===
+
=== 添加新动作 ===
  
Adding new actions is a bit trickier, because you have to understand that
+
添加新动作有点棘手,因为您必须了解 [[#module-optparse|optparse]] 对动作有几个分类:
[[#module-optparse|<code>optparse</code>]] has a couple of classifications for actions:
 
  
; &quot;store&quot; actions
+
; “存储”操作
: actions that result in [[#module-optparse|<code>optparse</code>]] storing a value to an attribute of the current OptionValues instance; these options require a [[#optparse.Option.dest|<code>dest</code>]] attribute to be supplied to the Option constructor.
+
: 导致 [[#module-optparse|optparse]] 将值存储到当前 OptionValues 实例的属性的操作; 这些选项需要将 [[#optparse.Option.dest|dest]] 属性提供给 Option 构造函数。
; &quot;typed&quot; actions
+
; “类型化”操作
: actions that take a value from the command line and expect it to be of a certain type; or rather, a string that can be converted to a certain type. These options require a [[#optparse.Option.type|<code>type</code>]] attribute to the Option constructor.
+
: 从命令行获取值并期望它是某种类型的操作; 或者更确切地说,可以转换为某种类型的字符串。 这些选项需要 Option 构造函数的 [[#optparse.Option.type|type]] 属性。
  
These are overlapping sets: some default &quot;store&quot; actions are <code>&quot;store&quot;</code>,
+
这些是重叠的集合:一些默认的“存储”动作是 <code>&quot;store&quot;</code><code>&quot;store_const&quot;</code><code>&quot;append&quot;</code> <code>&quot;count&quot;</code>,而默认的“类型”动作是 [ X147X]、<code>&quot;append&quot;</code> <code>&quot;callback&quot;</code>
<code>&quot;store_const&quot;</code>, <code>&quot;append&quot;</code>, and <code>&quot;count&quot;</code>, while the default &quot;typed&quot;
 
actions are <code>&quot;store&quot;</code>, <code>&quot;append&quot;</code>, and <code>&quot;callback&quot;</code>.
 
  
When you add an action, you need to categorize it by listing it in at least one
+
当你添加一个动作时,你需要通过将它列在 Option 的以下类属性中的至少一个中来对其进行分类(都是字符串列表):
of the following class attributes of Option (all are lists of strings):
 
  
; <code>Option.</code><code>ACTIONS</code>
+
; <span class="sig-prename descclassname"><span class="pre">Option.</span></span><span class="sig-name descname"><span class="pre">ACTIONS</span></span>
: All actions must be listed in ACTIONS.
+
: 所有操作都必须在 ACTIONS 中列出。
  
; <code>Option.</code><code>STORE_ACTIONS</code>
+
; <span class="sig-prename descclassname"><span class="pre">Option.</span></span><span class="sig-name descname"><span class="pre">STORE_ACTIONS</span></span>
: &quot;store&quot; actions are additionally listed here.
+
: 此处还列出了“商店”操作。
  
; <code>Option.</code><code>TYPED_ACTIONS</code>
+
; <span class="sig-prename descclassname"><span class="pre">Option.</span></span><span class="sig-name descname"><span class="pre">TYPED_ACTIONS</span></span>
: &quot;typed&quot; actions are additionally listed here.
+
: 此处还列出了“类型”操作。
  
; <code>Option.</code><code>ALWAYS_TYPED_ACTIONS</code>
+
; <span class="sig-prename descclassname"><span class="pre">Option.</span></span><span class="sig-name descname"><span class="pre">ALWAYS_TYPED_ACTIONS</span></span>
: Actions that always take a type (i.e. whose options always take a value) are additionally listed here. The only effect of this is that [[#module-optparse|<code>optparse</code>]] assigns the default type, <code>&quot;string&quot;</code>, to options with no explicit type whose action is listed in [[#optparse.Option.ALWAYS_TYPED_ACTIONS|<code>ALWAYS_TYPED_ACTIONS</code>]].
+
: 总是采用某种类型的操作(即 其选项始终采用一个值)在此处另外列出。 这样做的唯一影响是 [[#module-optparse|optparse]] 将默认类型 <code>&quot;string&quot;</code> 分配给没有显式类型的选项,其操作在 [[#optparse.Option.ALWAYS_TYPED_ACTIONS|ALWAYS_TYPED_ACTIONS]] 中列出。
  
In order to actually implement your new action, you must override Option's
+
为了实际实现您的新操作,您必须覆盖 Option <code>take_action()</code> 方法并添加一个可识别您的操作的案例。
<code>take_action()</code> method and add a case that recognizes your action.
 
  
For example, let's add an <code>&quot;extend&quot;</code> action. This is similar to the standard
+
例如,让我们添加一个 <code>&quot;extend&quot;</code> 动作。 这类似于标准的 <code>&quot;append&quot;</code> 操作,但不是从命令行获取单个值并将其附加到现有列表中,<code>&quot;extend&quot;</code> 将在单个逗号分隔中获取多个值字符串,并用它们扩展现有列表。 也就是说,如果 <code>--names</code> <code>&quot;string&quot;</code> 类型的 <code>&quot;extend&quot;</code> 选项,则命令行
<code>&quot;append&quot;</code> action, but instead of taking a single value from the command-line
 
and appending it to an existing list, <code>&quot;extend&quot;</code> will take multiple values in
 
a single comma-delimited string, and extend an existing list with them. That
 
is, if <code>--names</code> is an <code>&quot;extend&quot;</code> option of type <code>&quot;string&quot;</code>, the command
 
line
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第2,391行: 第1,980行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>--names=foo,bar --names blah --names ding,dong</pre>
+
<syntaxhighlight lang="python3">--names=foo,bar --names blah --names ding,dong</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
would result in a list
+
将导致一个列表
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第2,402行: 第1,991行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>[&quot;foo&quot;, &quot;bar&quot;, &quot;blah&quot;, &quot;ding&quot;, &quot;dong&quot;]</pre>
+
<syntaxhighlight lang="python3">["foo", "bar", "blah", "ding", "dong"]</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
Again we define a subclass of Option:
+
我们再次定义 Option 的子类:
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第2,413行: 第2,002行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>class MyOption(Option):
+
<syntaxhighlight lang="python3">class MyOption(Option):
  
     ACTIONS = Option.ACTIONS + (&quot;extend&quot;,)
+
     ACTIONS = Option.ACTIONS + ("extend",)
     STORE_ACTIONS = Option.STORE_ACTIONS + (&quot;extend&quot;,)
+
     STORE_ACTIONS = Option.STORE_ACTIONS + ("extend",)
     TYPED_ACTIONS = Option.TYPED_ACTIONS + (&quot;extend&quot;,)
+
     TYPED_ACTIONS = Option.TYPED_ACTIONS + ("extend",)
     ALWAYS_TYPED_ACTIONS = Option.ALWAYS_TYPED_ACTIONS + (&quot;extend&quot;,)
+
     ALWAYS_TYPED_ACTIONS = Option.ALWAYS_TYPED_ACTIONS + ("extend",)
  
 
     def take_action(self, action, dest, opt, value, values, parser):
 
     def take_action(self, action, dest, opt, value, values, parser):
         if action == &quot;extend&quot;:
+
         if action == "extend":
             lvalue = value.split(&quot;,&quot;)
+
             lvalue = value.split(",")
 
             values.ensure_value(dest, []).extend(lvalue)
 
             values.ensure_value(dest, []).extend(lvalue)
 
         else:
 
         else:
 
             Option.take_action(
 
             Option.take_action(
                 self, action, dest, opt, value, values, parser)</pre>
+
                 self, action, dest, opt, value, values, parser)</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
Features of note:
+
笔记特点:
  
 
<ul>
 
<ul>
<li><p><code>&quot;extend&quot;</code> both expects a value on the command-line and stores that value
+
<li><p><code>&quot;extend&quot;</code> 都需要命令行上的值并将该值存储在某处,因此它同时出现在 [[#optparse.Option.STORE_ACTIONS|STORE_ACTIONS]] [[#optparse.Option.TYPED_ACTIONS|TYPED_ACTIONS]] 中。</p></li>
somewhere, so it goes in both [[#optparse.Option.STORE_ACTIONS|<code>STORE_ACTIONS</code>]] and
+
<li><p>为确保 [[#module-optparse|optparse]] <code>&quot;string&quot;</code> 的默认类型分配给 <code>&quot;extend&quot;</code> 动作,我们也将 <code>&quot;extend&quot;</code> 动作放在 [[#optparse.Option.ALWAYS_TYPED_ACTIONS|ALWAYS_TYPED_ACTIONS]] .</p></li>
[[#optparse.Option.TYPED_ACTIONS|<code>TYPED_ACTIONS</code>]].</p></li>
+
<li><p><code>MyOption.take_action()</code> 仅实现了这一新动作,并将控制权交还给 <code>Option.take_action()</code> 以进行标准的 [[#module-optparse|optparse]] 动作。</p></li>
<li><p>to ensure that [[#module-optparse|<code>optparse</code>]] assigns the default type of <code>&quot;string&quot;</code> to
+
<li><p><code>values</code> optparse_parser.Values 类的一个实例,它提供了非常有用的 <code>ensure_value()</code> 方法。 <code>ensure_value()</code> 本质上是 [[../functions#getattr|getattr()]] 带安全阀; 它被称为</p>
<code>&quot;extend&quot;</code> actions, we put the <code>&quot;extend&quot;</code> action in
 
[[#optparse.Option.ALWAYS_TYPED_ACTIONS|<code>ALWAYS_TYPED_ACTIONS</code>]] as well.</p></li>
 
<li><p><code>MyOption.take_action()</code> implements just this one new action, and passes
 
control back to <code>Option.take_action()</code> for the standard [[#module-optparse|<code>optparse</code>]]
 
actions.</p></li>
 
<li><p><code>values</code> is an instance of the optparse_parser.Values class, which provides
 
the very useful <code>ensure_value()</code> method. <code>ensure_value()</code> is
 
essentially [[../functions#getattr|<code>getattr()</code>]] with a safety valve; it is called as</p>
 
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
  
 
<div class="highlight">
 
<div class="highlight">
  
<pre>values.ensure_value(attr, value)</pre>
+
<syntaxhighlight lang="python3">values.ensure_value(attr, value)</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
<p>If the <code>attr</code> attribute of <code>values</code> doesn't exist or is <code>None</code>, then
+
<p>如果<code>values</code><code>attr</code>属性不存在或者是<code>None</code>,则ensure_value()首先将其设置为<code>value</code>,然后返回'value。 这对于像 <code>&quot;extend&quot;</code><code>&quot;append&quot;</code> <code>&quot;count&quot;</code> 这样的动作非常方便,所有这些动作都在一个变量中累积数据并期望该变量是某种类型(列表对于前两个,对于后者是一个整数)。 使用 <code>ensure_value()</code> 意味着使用您的操作的脚本不必担心为相关选项目的地设置默认值; 他们可以将默认值保留为 <code>None</code>,而 <code>ensure_value()</code> 会在需要时负责将其正确处理。</p></li></ul>
ensure_value() first sets it to <code>value</code>, and then returns 'value. This is
+
 
very handy for actions like <code>&quot;extend&quot;</code>, <code>&quot;append&quot;</code>, and <code>&quot;count&quot;</code>, all
 
of which accumulate data in a variable and expect that variable to be of a
 
certain type (a list for the first two, an integer for the latter). Using
 
<code>ensure_value()</code> means that scripts using your action don't have to worry
 
about setting a default value for the option destinations in question; they
 
can just leave the default as <code>None</code> and <code>ensure_value()</code> will take care of
 
getting it right when it's needed.</p></li></ul>
 
  
 +
</div>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
 +
<div class="clearer">
 +
 +
  
 
</div>
 
</div>
  
[[Category:Python 3.9 中文文档]]
+
[[Category:Python 3.9 文档]]

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

optparse — 命令行选项解析器

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

Deprecated since version 3.2: The optparse 模块已弃用,不会进一步开发; argparse 模块将继续开发。



optparse 是一个比旧的 getopt 模块更方便、灵活和强大的命令行选项解析库。 optparse 使用更具声明性的命令行解析风格:创建 OptionParser 的实例,用选项填充它,然后解析命令行。 optparse 允许用户在传统的 GNU/POSIX 语法中指定选项,并额外为您生成用法和帮助消息。

这是在简单脚本中使用 optparse 的示例:

from optparse import OptionParser
...
parser = OptionParser()
parser.add_option("-f", "--file", dest="filename",
                  help="write report to FILE", metavar="FILE")
parser.add_option("-q", "--quiet",
                  action="store_false", dest="verbose", default=True,
                  help="don't print status messages to stdout")

(options, args) = parser.parse_args()

使用这几行代码,您的脚本用户现在可以在命令行上执行“常规操作”,例如:

<yourscript> --file=outfile -q

在解析命令行时,optparse 根据用户提供的命令行值设置 parse_args() 返回的 options 对象的属性。 当 parse_args() 解析此命令行返回时,options.filename 将是 "outfile",而 options.verbose 将是 Falseoptparse 支持长选项和短选项,允许将短选项合并在一起,并允许选项以多种方式与其参数相关联。 因此,以下命令行都等效于上面的示例:

<yourscript> -f outfile --quiet
<yourscript> --quiet --file outfile
<yourscript> -q -foutfile
<yourscript> -qfoutfile

此外,用户可以运行以下之一

<yourscript> -h
<yourscript> --help

optparse 将打印出脚本选项的简要摘要:

Usage: <yourscript> [options]

Options:
  -h, --help            show this help message and exit
  -f FILE, --file=FILE  write report to FILE
  -q, --quiet           don't print status messages to stdout

其中 yourscript 的值在运行时确定(通常来自 sys.argv[0])。

背景

optparse 被明确设计为鼓励使用简单的、传统的命令行界面创建程序。 为此,它仅支持在 Unix 下常规使用的最常见的命令行语法和语义。 如果您不熟悉这些约定,请阅读本节以熟悉它们。

术语

争论

在命令行上输入的字符串,并由 shell 传递给 execl()execv()。 在 Python 中,参数是 sys.argv[1:] 的元素(sys.argv[0] 是正在执行的程序的名称)。 Unix shell 也使用术语“单词”。

有时需要替换除 sys.argv[1:] 以外的参数列表,因此您应该将“参数”读作“sys.argv[1:] 的元素,或作为 sys.argv[1:]”。

选项

用于提供额外信息以指导或自定义程序执行的参数。 选项有许多不同的语法; 传统的 Unix 语法是一个连字符(“-”)后跟一个字母,例如 -x-F。 此外,传统的 Unix 语法允许将多个选项合并为一个参数,例如 -x -F 相当于 -xF。 GNU 项目引入了 -- 后跟一系列连字符分隔的单词,例如 --file--dry-run。 这些是 optparse 提供的仅有的两个选项语法。

世界上看到的其他一些选项语法包括:

  • 一个连字符后跟几个字母,例如 -pf(这是 不是 与合并为单个参数的多个选项相同)

  • 一个连字符后跟一个完整的词,例如 -file(这在技术上等同于前面的语法,但它们通常不会出现在同一个程序中)

  • 一个加号后跟一个字母,或几个字母,或一个词,例如 +f+rgb

  • 斜线后跟一个字母、几个字母或一个词,例如 /f/file

optparse 不支持这些选项语法,并且永远不会支持。 这是故意的:前三个在任何环境中都是非标准的,最后一个只有在您专门针对 VMS、MS-DOS 和/或 Windows 时才有意义。

选项参数

跟随选项的参数与该选项密切相关,并在该选项存在时从参数列表中使用。 使用 optparse,选项参数可以在与其选项分开的参数中:

-f foo
--file foo

或包含在同一参数中:

-ffoo
--file=foo

通常,给定的选项要么接受一个参数,要么不接受。 很多人想要一个“可选的选项参数”功能,这意味着如果他们看到一些选项会接受一个参数,如果他们没有则不会。 这有点有争议,因为它使解析模棱两可:如果 -a 接受一个可选参数而 -b 完全是另一个选项,我们如何解释 -ab? 由于这种歧义,optparse 不支持此功能。

位置论证

解析选项后参数列表中剩余的内容,即 在选项及其参数被解析并从参数列表中删除之后。

必选选项

必须在命令行上提供的选项; 请注意,“必需选项”一词在英语中自相矛盾。 optparse 不会阻止您实现所需的选项,但也不会给您太多帮助。

例如,考虑这个假设的命令行:

prog -v --report report.txt foo bar

-v--report 都是选项。 假设 --report 接受一个参数,report.txt 是一个选项参数。 foobar 是位置参数。


什么是选项?

选项用于提供额外信息以调整或自定义程序的执行。 如果不清楚,选项通常是 optional。 程序应该能够在没有任何选项的情况下正常运行。 (从 Unix 或 GNU 工具集中随机选择一个程序。 它可以在没有任何选项的情况下运行并且仍然有意义吗? 主要的例外是 findtardd——所有这些都是变异的古怪,因其非标准的语法和令人困惑的界面而受到了正确的批评。)

许多人希望他们的程序具有“必需的选项”。 想想看。 如果它是必需的,那么它是 不是可选的 ! 如果有一条信息是您的程序成功运行所绝对需要的,这就是位置参数的用途。

作为良好的命令行界面设计的一个例子,考虑用于复制文件的不起眼的 cp 实用程序。 在不提供目的地和至少一个来源的情况下尝试复制文件没有多大意义。 因此,如果不带参数运行 cp 会失败。 但是,它具有灵活、有用的语法,根本不需要任何选项:

cp SOURCE DEST
cp SOURCE ... DEST-DIR

你可以走得很远。 大多数 cp 实现提供了一系列选项来精确调整文件的复制方式:您可以保留模式和修改时间、避免跟随符号链接、在破坏现有文件之前询问等。 但这一切都不会分散 cp 的核心任务,即将一个文件复制到另一个文件,或将多个文件复制到另一个目录。


什么是位置参数?

位置参数用于您的程序绝对需要运行的那些信息。

一个好的用户界面应该有尽可能少的绝对要求。 如果你的程序需要 17 条不同的信息才能成功运行,那么如何从用户那里获得这些信息并不重要——大多数人会在成功运行程序之前放弃并走开. 无论用户界面是命令行、配置文件还是 GUI,这都适用:如果您对用户提出那么多要求,他们中的大多数都会简单地放弃。

简而言之,尽量减少绝对需要用户提供的信息量——尽可能使用合理的默认值。 当然,您还希望使您的程序具有相当的灵活性。 这就是选项的用途。 同样,它们是配置文件中的条目、GUI 的“首选项”对话框中的小部件还是命令行选项都无关紧要——你实现的选项越多,你的程序就越灵活,也就越复杂它的实现变成了。 当然,太多的灵活性也有缺点。 太多的选项会让用户不知所措,并使您的代码更难维护。


教程

虽然 optparse 非常灵活和强大,但在大多数情况下使用起来也很简单。 本节涵盖了任何基于 optparse 的程序通用的代码模式。

首先,需要导入OptionParser类; 然后,在主程序的早期,创建一个 OptionParser 实例:

from optparse import OptionParser
...
parser = OptionParser()

然后您可以开始定义选项。 基本语法是:

parser.add_option(opt_str, ...,
                  attr=value, ...)

每个选项都有一个或多个选项字符串,例如 -f--file,还有几个选项属性告诉 optparse 期望什么以及遇到该选项时要做什么在命令行上。

通常,每个选项都有一个短选项字符串和一个长选项字符串,例如:

parser.add_option("-f", "--file", ...)

您可以随意定义任意数量的短选项字符串和任意数量的长选项字符串(包括零),只要总体上至少有一个选项字符串即可。

传递给 OptionParser.add_option() 的选项字符串实际上是该调用定义的选项的标签。 为简洁起见,我们会经常在命令行中提到遇到一个选项; 实际上,optparse 遇到 option strings 并从中查找选项。

定义所有选项后,指示 optparse 解析程序的命令行:

(options, args) = parser.parse_args()

(如果您愿意,可以将自定义参数列表传递给 parse_args(),但这很少需要:默认情况下它使用 sys.argv[1:]。)

parse_args() 返回两个值:

  • options,一个包含所有选项值的对象——例如 如果 --file 采用单个字符串参数,则 options.file 将是用户提供的文件名,如果用户未提供该选项,则 None
  • args,解析选项后剩余的位置参数列表

本教程部分仅涵盖四个最重要的选项属性:actiontypedest(目的地)和 help。 其中,action是最基本的。

了解选项操作

Actions 告诉 optparse 当它在命令行上遇到一个选项时要做什么。 有一组固定的动作硬编码到 optparse 中; 添加新操作是 扩展 optparse 部分中介绍的高级主题。 大多数操作告诉 optparse 将值存储在某个变量中 - 例如,从命令行获取字符串并将其存储在 options 的属性中。

如果不指定选项操作,optparse 默认为 store


店铺动作

最常见的选项动作是 store,它告诉 optparse 取下一个参数(或当前参数的剩余部分),确保它是正确的类型,并将其存储到您选择的目的地。

例如:

parser.add_option("-f", "--file",
                  action="store", type="string", dest="filename")

现在让我们编写一个假命令行并要求 optparse 解析它:

args = ["-f", "foo.txt"]
(options, args) = parser.parse_args(args)

optparse 看到选项字符串 -f 时,它会消耗下一个参数 foo.txt,并将其存储在 options.filename 中。 因此,在调用 parse_args() 之后,options.filename"foo.txt"

optparse 支持的其他一些选项类型是 intfloat。 这是一个需要整数参数的选项:

parser.add_option("-n", type="int", dest="num")

请注意,此选项没有长选项字符串,这是完全可以接受的。 此外,没有明确的操作,因为默认值为 store

让我们解析另一个假命令行。 这一次,我们将把 option 参数直接与 option 相对:由于 -n42(一个参数)等价于 -n 42(两个参数),代码

(options, args) = parser.parse_args(["-n42"])
print(options.num)

将打印 42

如果不指定类型,optparse 假定为 string。 结合默认操作是 store 的事实,这意味着我们的第一个示例可以更短:

parser.add_option("-f", "--file", dest="filename")

如果您不提供目的地,optparse 会从选项字符串中找出合理的默认值:如果第一个长选项字符串是 --foo-bar,则默认目的地是 foo_bar ]。 如果没有长选项字符串,optparse 会查看第一个短选项字符串:-f 的默认目标是 f

optparse 还包括内置的 complex 类型。 添加类型在 扩展 optparse 部分中有介绍。


处理布尔(标志)选项

标记选项——在看到特定选项时将变量设置为 true 或 false——非常常见。 optparse 通过两个单独的动作支持它们,store_truestore_false。 例如,您可能有一个 verbose 标志,用 -v 打开,用 -q 关闭:

parser.add_option("-v", action="store_true", dest="verbose")
parser.add_option("-q", action="store_false", dest="verbose")

在这里,我们有两个具有相同目的地的不同选项,这完全没问题。 (这只是意味着你在设置默认值时必须小心一点——见下文。)

optparse在命令行遇到-v时,将options.verbose设置为True; 当遇到-q时,将options.verbose设置为False


其他行为

optparse 支持的其他一些操作是:

"store_const"
存储一个常数值
"append"
将此选项的参数附加到列表中
"count"
将计数器加一
"callback"
调用指定的函数

这些在 参考指南 部分和 选项回调 部分中有介绍。


默认值

上述所有示例都涉及在看到某些命令行选项时设置一些变量(“目标”)。 如果从未见过这些选项会怎样? 由于我们没有提供任何默认值,它们都设置为 None。 这通常很好,但有时您需要更多控制。 optparse 允许您为每个目标提供默认值,该值在解析命令行之前分配。

首先,考虑冗长/安静的例子。 如果我们想让 optparseverbose 设置为 True 除非看到 -q,那么我们可以这样做:

parser.add_option("-v", action="store_true", dest="verbose", default=True)
parser.add_option("-q", action="store_false", dest="verbose")

由于默认值适用于 destination 而不是任何特定选项,并且这两个选项恰好具有相同的目标,这完全等效:

parser.add_option("-v", action="store_true", dest="verbose")
parser.add_option("-q", action="store_false", dest="verbose", default=True)

考虑一下:

parser.add_option("-v", action="store_true", dest="verbose", default=False)
parser.add_option("-q", action="store_false", dest="verbose", default=True)

同样,verbose 的默认值将是 True:为任何特定目的地提供的最后一个默认值是重要的。

一个更清晰的指定默认值的方法是OptionParser的set_defaults()方法,你可以在调用parse_args()之前随时调用它:

parser.set_defaults(verbose=True)
parser.add_option(...)
(options, args) = parser.parse_args()

和以前一样,为给定选项目标指定的最后一个值是最重要的值。 为清楚起见,请尝试使用一种方法或另一种设置默认值的方法,而不是同时使用两种方法。


生成帮助

optparse 自动生成帮助和使用文本的能力对于创建用户友好的命令行界面非常有用。 您所要做的就是为每个选项提供一个 help 值,并且可以选择为整个程序提供一个简短的使用消息。 这是一个填充了用户友好(记录)选项的 OptionParser:

usage = "usage: %prog [options] arg1 arg2"
parser = OptionParser(usage=usage)
parser.add_option("-v", "--verbose",
                  action="store_true", dest="verbose", default=True,
                  help="make lots of noise [default]")
parser.add_option("-q", "--quiet",
                  action="store_false", dest="verbose",
                  help="be vewwy quiet (I'm hunting wabbits)")
parser.add_option("-f", "--filename",
                  metavar="FILE", help="write output to FILE")
parser.add_option("-m", "--mode",
                  default="intermediate",
                  help="interaction mode: novice, intermediate, "
                       "or expert [default: %default]")

如果 optparse 在命令行上遇到 -h--help,或者如果您只是调用 parser.print_help(),它会将以下内容打印到标准输出:

Usage: <yourscript> [options] arg1 arg2

Options:
  -h, --help            show this help message and exit
  -v, --verbose         make lots of noise [default]
  -q, --quiet           be vewwy quiet (I'm hunting wabbits)
  -f FILE, --filename=FILE
                        write output to FILE
  -m MODE, --mode=MODE  interaction mode: novice, intermediate, or
                        expert [default: intermediate]

(如果帮助输出是由帮助选项触发的,则在打印帮助文本后 optparse 退出。)

这里有很多事情可以帮助 optparse 生成最好的帮助消息:

  • 该脚本定义了自己的使用消息:

    usage = "usage: %prog [options] arg1 arg2"

    optparse 将用法字符串中的 %prog 扩展为当前程序的名称,即 os.path.basename(sys.argv[0])。 然后在详细选项帮助之前打印扩展的字符串。

    如果您不提供用法字符串,optparse 使用平淡但合理的默认值:"Usage: %prog [options]",如果您的脚本不采用任何位置参数,这很好。

  • 每个选项都定义了一个帮助字符串,并且不用担心换行——optparse 负责换行并使帮助输出看起来不错。

  • 带值的选项在其自动生成的帮助消息中表明这一事实,例如 对于“模式”选项:

    -m MODE, --mode=MODE

    这里,“MODE”被称为元变量:它代表用户应该提供给 -m/--mode 的参数。 默认情况下,optparse 将目标变量名称转换为大写并将其用于元变量。 有时,这不是您想要的——例如,--filename 选项显式设置 metavar="FILE",从而导致此自动生成的选项描述:

    -f FILE, --filename=FILE

    不过,这不仅仅是节省空间的重要原因:手动编写的帮助文本使用元变量 FILE 来提示用户,因为半正式语法 -f FILE 和非正式语义描述“将输出写入文件”。 这是一种简单但有效的方法,可以使您的帮助文本更清晰,对最终用户更有用。

  • 具有默认值的选项可以在帮助字符串中包含 %default - optparse 将替换为选项默认值的 str()。 如果选项没有默认值(或默认值为 None),则 %default 扩展为 none

分组选项

在处理多个选项时,可以方便地将这些选项分组以获得更好的帮助输出。 一个 OptionParser 可以包含多个选项组,每个选项组可以包含多个选项。

使用类 OptionGroup 获得选项组:

class optparse.OptionGroup(parser, title, description=None)
在哪里
  • parser 是组将插入到的 OptionParser 实例
  • 标题是组标题
  • description,可选,是对组的详细描述

OptionGroup 继承自 OptionContainer(如 OptionParser),因此 add_option() 方法可用于向组添加选项。

声明所有选项后,使用 OptionParser 方法 add_option_group() 将组添加到先前定义的解析器。

继续上一节中定义的解析器,向解析器添加 OptionGroup 很容易:

group = OptionGroup(parser, "Dangerous Options",
                    "Caution: use these options at your own risk.  "
                    "It is believed that some of them bite.")
group.add_option("-g", action="store_true", help="Group option.")
parser.add_option_group(group)

这将导致以下帮助输出:

Usage: <yourscript> [options] arg1 arg2

Options:
  -h, --help            show this help message and exit
  -v, --verbose         make lots of noise [default]
  -q, --quiet           be vewwy quiet (I'm hunting wabbits)
  -f FILE, --filename=FILE
                        write output to FILE
  -m MODE, --mode=MODE  interaction mode: novice, intermediate, or
                        expert [default: intermediate]

  Dangerous Options:
    Caution: use these options at your own risk.  It is believed that some
    of them bite.

    -g                  Group option.

更完整的示例可能涉及使用多个组:仍然扩展前一个示例:

group = OptionGroup(parser, "Dangerous Options",
                    "Caution: use these options at your own risk.  "
                    "It is believed that some of them bite.")
group.add_option("-g", action="store_true", help="Group option.")
parser.add_option_group(group)

group = OptionGroup(parser, "Debug Options")
group.add_option("-d", "--debug", action="store_true",
                 help="Print debug information")
group.add_option("-s", "--sql", action="store_true",
                 help="Print all SQL statements executed")
group.add_option("-e", action="store_true", help="Print every action done")
parser.add_option_group(group)

这导致以下输出:

Usage: <yourscript> [options] arg1 arg2

Options:
  -h, --help            show this help message and exit
  -v, --verbose         make lots of noise [default]
  -q, --quiet           be vewwy quiet (I'm hunting wabbits)
  -f FILE, --filename=FILE
                        write output to FILE
  -m MODE, --mode=MODE  interaction mode: novice, intermediate, or expert
                        [default: intermediate]

  Dangerous Options:
    Caution: use these options at your own risk.  It is believed that some
    of them bite.

    -g                  Group option.

  Debug Options:
    -d, --debug         Print debug information
    -s, --sql           Print all SQL statements executed
    -e                  Print every action done

另一个有趣的方法,特别是在以编程方式使用选项组时:

OptionParser.get_option_group(opt_str)
返回短或长选项字符串 opt_strOptionGroup(例如 '-o''--option') 属于。 如果没有这样的 OptionGroup,则返回 None


打印版本字符串

与简要用法字符串类似,optparse 也可以为您的程序打印版本字符串。 您必须将字符串作为 version 参数提供给 OptionParser:

parser = OptionParser(usage="%prog [-f] [-q]", version="%prog 1.0")

%prog 像在 usage 中一样展开。 除此之外,version 可以包含任何你喜欢的东西。 当您提供它时, optparse 会自动向您的解析器添加一个 --version 选项。 如果它在命令行上遇到此选项,它会扩展您的 version 字符串(通过替换 %prog),将其打印到标准输出,然后退出。

例如,如果您的脚本名为 /usr/bin/foo

$ /usr/bin/foo --version
foo 1.0

可以使用以下两种方法打印和获取 version 字符串:

OptionParser.print_version(file=None)
将当前程序 (self.version) 的版本信息打印到 file(默认标准输出)。 与 print_usage() 一样,self.version 中出现的任何 %prog 都将替换为当前程序的名称。 如果 self.version 为空或未定义,则不执行任何操作。
OptionParser.get_version()
print_version() 相同,但返回版本字符串而不是打印它。


optparse 如何处理错误

optparse 必须担心两大类错误:程序员错误和用户错误。 程序员错误通常是对 OptionParser.add_option() 的错误调用,例如 无效的选项字符串、未知的选项属性、缺少选项属性等。 这些以通常的方式处理:引发异常(optparse.OptionErrorTypeError)并让程序崩溃。

处理用户错误更为重要,因为无论您的代码多么稳定,它们都一定会发生。 optparse 可以自动检测一些用户错误,例如错误的选项参数(传递 -n 4x 其中 -n 需要一个整数参数),缺少参数(-n 在命令行的末尾,其中 -n 接受任何类型的参数)。 此外,您可以调用 OptionParser.error() 来表示应用程序定义的错误条件:

(options, args) = parser.parse_args()
...
if options.a and options.b:
    parser.error("options -a and -b are mutually exclusive")

在任何一种情况下,optparse 都以相同的方式处理错误:它将程序的使用消息和错误消息打印到标准错误,并以错误状态 2 退出。

考虑上面的第一个示例,其中用户将 4x 传递给一个接受整数的选项:

$ /usr/bin/foo -n 4x
Usage: foo [options]

foo: error: option -n: invalid integer value: '4x'

或者,用户根本无法传递值:

$ /usr/bin/foo -n
Usage: foo [options]

foo: error: -n option requires an argument

optparse 生成的错误消息注意总是提及错误中涉及的选项; 从您的应用程序代码调用 OptionParser.error() 时一定要这样做。

如果 optparse 的默认错误处理行为不适合您的需要,您需要继承 OptionParser 并覆盖其 exit() 和/或 error() 方法。


把这一切放在一起

以下是基于 optparse 的脚本通常的样子:

from optparse import OptionParser
...
def main():
    usage = "usage: %prog [options] arg"
    parser = OptionParser(usage)
    parser.add_option("-f", "--file", dest="filename",
                      help="read data from FILENAME")
    parser.add_option("-v", "--verbose",
                      action="store_true", dest="verbose")
    parser.add_option("-q", "--quiet",
                      action="store_false", dest="verbose")
    ...
    (options, args) = parser.parse_args()
    if len(args) != 1:
        parser.error("incorrect number of arguments")
    if options.verbose:
        print("reading %s..." % options.filename)
    ...

if __name__ == "__main__":
    main()

参考指南

创建解析器

使用 optparse 的第一步是创建一个 OptionParser 实例。

class optparse.OptionParser(...)
OptionParser 构造函数没有必需的参数,但有一些可选的关键字参数。 您应该始终将它们作为关键字参数传递,即 不要依赖声明参数的顺序。
usage(默认:"%prog [options]"
当您的程序运行不正确或带有帮助选项时要打印的使用摘要。 当 optparse 打印用法字符串时,它会将 %prog 扩展为 os.path.basename(sys.argv[0])(如果您传递了该关键字参数,则扩展为 prog)。 要禁止使用消息,请传递特殊值 optparse.SUPPRESS_USAGE
option_list(默认:[]
用于填充解析器的 Option 对象列表。 option_list 中的选项添加在 standard_option_list 中的任何选项之后(可由 OptionParser 子类设置的类属性),但在任何版本或帮助选项之前。 已弃用; 改为在创建解析器后使用 add_option()
option_class(默认值:optparse.Option)
add_option() 中向解析器添加选项时使用的类。
version(默认:None
当用户提供版本选项时要打印的版本字符串。 如果您为 version 提供真值,optparse 会自动添加带有单个选项字符串 --version 的版本选项。 子串 %prog 的扩展方式与 usage 相同。
conflict_handler(默认:"error"
指定将具有冲突选项字符串的选项添加到解析器时要执行的操作; 参见章节 选项之间的冲突
description(默认:None
一段文字,简要概述您的程序。 optparse 重新格式化此段落以适应当前终端宽度并在用户请求帮助时打印它(在 usage 之后,但在选项列表之前)。
formatter(默认:新的 IndentedHelpFormatter
optparse.HelpFormatter 的一个实例,用于打印帮助文本。 optparse 为此提供了两个具体的类:IndentedHelpFormatter 和 TitledHelpFormatter。
add_help_option(默认:True
如果为 true,optparse 将向解析器添加一个帮助选项(带有选项字符串 -h--help)。
prog
usageversion 中扩展 %prog 而不是 os.path.basename(sys.argv[0]) 时使用的字符串。
epilog(默认:None
在选项帮助之后打印的一段帮助文本。


填充解析器

有几种方法可以用选项填充解析器。 首选方法是使用 OptionParser.add_option(),如 Tutorial 部分所示。 add_option() 可以通过以下两种方式之一调用:

  • 传递给它一个 Option 实例(由 make_option() 返回)
  • make_option() 可接受的位置和关键字参数的任意组合传递给它(即传递给 Option 构造函数),它将为您创建 Option 实例

另一种选择是将预先构造的 Option 实例列表传递给 OptionParser 构造函数,如下所示:

option_list = [
    make_option("-f", "--filename",
                action="store", type="string", dest="filename"),
    make_option("-q", "--quiet",
                action="store_false", dest="verbose"),
    ]
parser = OptionParser(option_list=option_list)

make_option() 是用于创建 Option 实例的工厂函数;目前它是 Option 构造函数的别名。 optparse 的未来版本可能会将 Option 拆分为几个类,而 make_option() 将选择正确的类进行实例化。 不要直接实例化 Option。)


定义选项

每个 Option 实例代表一组同义的命令行选项字符串,例如 -f--file。 您可以指定任意数量的短选项字符串或长选项字符串,但必须至少指定一个整体选项字符串。

创建 Option 实例的规范方法是使用 OptionParseradd_option() 方法。

OptionParser.add_option(option)
OptionParser.add_option(*opt_str, attr=value, ...)

要定义仅包含短选项字符串的选项:

parser.add_option("-f", attr=value, ...)

并定义一个只有一个长选项字符串的选项:

parser.add_option("--foo", attr=value, ...)

关键字参数定义了新 Option 对象的属性。 最重要的选项属性是 action,它在很大程度上决定了哪些其他属性是相关的或必需的。 如果你传递了不相关的选项属性,或者没有传递必需的属性,optparse 会引发一个 OptionError 异常来解释你的错误。

一个选项的 action 决定了 optparse 在命令行上遇到这个选项时会做什么。 硬编码到 optparse 中的标准选项操作是:

"store"

存储此选项的参数(默认)

"store_const"

存储一个常数值

"store_true"

商店 True

"store_false"

商店 False

"append"

将此选项的参数附加到列表中

"append_const"

将常量值附加到列表

"count"

将计数器加一

"callback"

调用指定的函数

"help"

打印使用消息,包括所有选项及其文档

(如果您不提供操作,则默认值为 "store"。 对于此操作,您还可以提供 typedest 选项属性; 请参阅 标准选项操作 。)

如您所见,大多数操作都涉及在某处存储或更新值。 optparse 总是为此创建一个特殊的对象,通常称为 options(它恰好是 optparse.Values 的一个实例)。 根据 dest(目标)选项属性,选项参数(和各种其他值)被存储为此对象的属性。

例如,当你打电话

parser.parse_args()

optparse 做的第一件事就是创建 options 对象:

options = Values()

如果此解析器中的选项之一定义为

parser.add_option("-f", "--file", action="store", type="string", dest="filename")

并且正在解析的命令行包括以下任何一项:

-ffoo
-f foo
--file=foo
--file foo

然后optparse,看到这个选项,会做相当于

options.filename = "foo"

typedest 选项属性几乎与 action 一样重要,但 action 是唯一对 有意义的属性所有 选项。


选项属性

以下选项属性可以作为关键字参数传递给 OptionParser.add_option()。 如果您传递与特定选项无关的选项属性,或者无法传递必需的选项属性,则 optparse 引发 OptionError

Option.action

(默认:"store"

确定在命令行上看到此选项时 optparse 的行为; 可用选项记录在 此处

Option.type

(默认:"string"

此选项预期的参数类型(例如,"string""int"); 可用的选项类型记录在 此处

Option.dest

(默认:派生自选项字符串)

如果选项的操作意味着在某处写入或修改值,这会告诉 optparse 在哪里写入它: dest 命名 optparse 的 options 对象的属性 在解析命令行时构建。

Option.default
如果在命令行上看不到该选项,则用于此选项目标的值。 另见 OptionParser.set_defaults()
Option.nargs

(默认值:1)

当看到这个选项时,应该消耗多少类型 type 的参数。 如果 > 1,optparse 将把一组值存储到 dest

Option.const
对于存储常量值的操作,要存储的常量值。
Option.choices
对于 "choice" 类型的选项,用户可以选择的字符串列表。
Option.callback
对于具有动作 "callback" 的选项,当看到此选项时调用的可调用对象。 有关传递给可调用对象的参数的详细信息,请参阅 Option Callbacks 部分。
Option.callback_args

Option.callback_kwargs

在四个标准回调参数之后传递给 callback 的附加位置和关键字参数。
Option.help
在用户提供 help 选项(例如 --help)后列出所有可用选项时,要打印此选项的帮助文本。 如果没有提供帮助文本,选项将在没有帮助文本的情况下列出。 要隐藏此选项,请使用特殊值 optparse.SUPPRESS_HELP
Option.metavar

(默认:派生自选项字符串)

打印帮助文本时要使用的选项参数的替代品。 有关示例,请参阅 教程 部分。


标准选项操作

各种选项操作都有略微不同的要求和效果。 大多数操作都有几个相关的选项属性,您可以指定这些属性来指导 optparse 的行为; 一些具有必需的属性,您必须为使用该操作的任何选项指定这些属性。

  • "store" [相关:typedestnargschoices]

    该选项必须后跟一个参数,该参数根据type转换为一个值并存储在dest中。 如果 nargs > 1,则命令行会消耗多个参数; all 将根据 type 转换并作为元组存储到 dest。 请参阅 标准选项类型 部分。

    如果提供 choices(字符串列表或元组),则类型默认为 "choice"

    如果未提供 type,则默认为 "string"

    如果未提供 dest,则 optparse 从第一个长选项字符串派生目标(例如,--foo-bar 暗示 foo_bar)。 如果没有长选项字符串,optparse 从第一个短选项字符串派生目的地(例如,-f 暗示 f)。

    例子:

    parser.add_option("-f")
    parser.add_option("-p", type="float", nargs=3, dest="point")

    当它解析命令行时

    -f foo.txt -p 1 -3.5 4 -fbar.txt

    optparse 将设置

    options.f = "foo.txt"
    options.point = (1.0, -3.5, 4.0)
    options.f = "bar.txt"
  • "store_const" [必需:const; 相关:dest]

    const 存储在 dest 中。

    例子:

    parser.add_option("-q", "--quiet",
                      action="store_const", const=0, dest="verbose")
    parser.add_option("-v", "--verbose",
                      action="store_const", const=1, dest="verbose")
    parser.add_option("--noisy",
                      action="store_const", const=2, dest="verbose")

    如果看到 --noisy,则会设置 optparse

    options.verbose = 2
  • "store_true" [相关:dest]

    "store_const" 的特例,存储 Truedest

  • "store_false" [相关:dest]

    类似于 "store_true",但存储 False

    例子:

    parser.add_option("--clobber", action="store_true", dest="clobber")
    parser.add_option("--no-clobber", action="store_false", dest="clobber")
  • "append" [相关:typedestnargschoices]

    该选项后必须跟一个参数,该参数附加到 dest 中的列表中。 如果未提供 dest 的默认值,则当 optparse 在命令行中首次遇到此选项时,将自动创建一个空列表。 如果 nargs > 1,则消耗多个参数,并将长度为 nargs 的元组附加到 dest

    typedest 的默认值与 "store" 动作的默认值相同。

    例子:

    parser.add_option("-t", "--tracks", action="append", type="int")

    如果在命令行上看到 -t3,则 optparse 相当于:

    options.tracks = []
    options.tracks.append(int("3"))

    如果稍后看到 --tracks=4,它会:

    options.tracks.append(int("4"))

    append 操作对选项的当前值调用 append 方法。 这意味着指定的任何默认值都必须具有 append 方法。 这也意味着如果默认值非空,默认元素将出现在选项的解析值中,命令行中的任何值都附加在这些默认值之后:

    >>> parser.add_option("--files", action="append", default=['~/.mypkg/defaults'])
    >>> opts, args = parser.parse_args(['--files', 'overrides.mypkg'])
    >>> opts.files
    ['~/.mypkg/defaults', 'overrides.mypkg']
  • "append_const" [必需:const; 相关:dest]

    "store_const" 类似,但值 const 附加到 dest; 与 "append" 一样,dest 默认为 None,第一次遇到选项时会自动创建一个空列表。

  • "count" [相关:dest]

    增加存储在 dest 的整数。 如果未提供默认值,则 dest 在第一次递增之前设置为零。

    例子:

    parser.add_option("-v", action="count", dest="verbosity")

    第一次在命令行上看到 -voptparse 相当于:

    options.verbosity = 0
    options.verbosity += 1

    每次出现 -v 都会导致

    options.verbosity += 1
  • "callback" [必填:回调; 相关:typenargscallback_argscallback_kwargs]

    调用callback指定的函数,调用为

    func(option, opt_str, value, parser, *args, **kwargs)

    有关更多详细信息,请参阅 选项回调 部分。

  • "help"

    打印当前选项解析器中所有选项的完整帮助消息。 帮助消息由传递给 OptionParser 的构造函数的 usage 字符串和传递给每个选项的 help 字符串构造而成。

    如果没有为选项提供 help 字符串,它仍将列在帮助消息中。 要完全省略选项,请使用特殊值 optparse.SUPPRESS_HELP

    optparse 会自动为所有 OptionParsers 添加一个 help 选项,因此您通常不需要创建一个。

    例子:

    from optparse import OptionParser, SUPPRESS_HELP
    
    # usually, a help option is added automatically, but that can
    # be suppressed using the add_help_option argument
    parser = OptionParser(add_help_option=False)
    
    parser.add_option("-h", "--help", action="help")
    parser.add_option("-v", action="store_true", dest="verbose",
                      help="Be moderately verbose")
    parser.add_option("--file", dest="filename",
                      help="Input file to read data from")
    parser.add_option("--secret", help=SUPPRESS_HELP)

    如果 optparse 在命令行上看到 -h--help,它将向 stdout 打印类似以下帮助消息的内容(假设 sys.argv[0]"foo.py"):

    Usage: foo.py [options]
    
    Options:
      -h, --help        Show this help message and exit
      -v                Be moderately verbose
      --file=FILENAME   Input file to read data from

    打印帮助信息后,optparsesys.exit(0) 终止您的进程。

  • "version"

    将提供给 OptionParser 的版本号打印到 stdout 并退出。 版本号实际上是由OptionParser的print_version()方法格式化打印出来的。 通常仅当 version 参数提供给 OptionParser 构造函数时才相关。 与 help 选项一样,您很少会创建 version 选项,因为 optparse 会在需要时自动添加它们。


标准选项类型

optparse 有五种内置选项类型:"string""int""choice""float""complex"。 如果您需要添加新的选项类型,请参阅 扩展 optparse 部分。

不以任何方式检查或转换字符串选项的参数:命令行上的文本按原样存储在目标中(或传递给回调)。

整数参数(类型 "int")解析如下:

  • 如果数字以0x开头,则解析为十六进制数
  • 如果数字以0开头,则解析为八进制数
  • 如果数字以0b开头,则解析为二进制数
  • 否则,数字被解析为十进制数

转换是通过使用适当的基数(2、8、10 或 16)调用 int() 来完成的。 如果失败,optparse 也会失败,尽管有更有用的错误消息。

"float""complex" 选项参数直接使用 float()complex() 进行转换,具有类似的错误处理。

"choice" 选项是 "string" 选项的子类型。 choices 选项属性(字符串序列)定义了允许的选项参数集。 optparse.check_choice() 将用户提供的选项参数与此主列表进行比较,如果给出无效字符串,则引发 OptionValueError


解析参数

创建和填充 OptionParser 的重点是调用它的 parse_args() 方法:

(options, args) = parser.parse_args(args=None, values=None)

其中输入参数是

args
要处理的参数列表(默认值:sys.argv[1:]
values
一个 optparse.Values 对象来存储选项参数(默认值:Values 的一个新实例)——如果你给一个现有的对象,选项默认值将不会被初始化

和返回值是

options
作为 values 传入的相同对象,或由 optparse 创建的 optparse.Values 实例
args
处理完所有选项后剩余的位置参数

最常见的用法是不提供关键字参数。 如果您提供 values,它将被重复的 setattr() 调用修改(对于存储到选项目标的每个选项参数大约一个)并由 parse_args() 返回。

如果 parse_args() 在参数列表中遇到任何错误,它会调用 OptionParser 的 error() 方法并带有适当的最终用户错误消息。 这最终会以退出状态 2(命令行错误的传统 Unix 退出状态)终止您的进程。


查询和操作您的选项解析器

选项解析器的默认行为可以稍微自定义,您还可以浏览您的选项解析器,看看那里有什么。 OptionParser 提供了几种方法来帮助您:

OptionParser.disable_interspersed_args()

将解析设置为在第一个非选项上停止。 例如,如果 -a-b 都是不带参数的简单选项,则 optparse 通常接受以下语法:

prog -a arg1 -b arg2

并将其视为等价于

prog -a -b arg1 arg2

要禁用此功能,请调用 disable_interspersed_args()。 这恢复了传统的 Unix 语法,其中选项解析在第一个非选项参数处停止。

如果您有一个命令处理器运行另一个具有自己的选项的命令,并且您想确保这些选项不会混淆,请使用此选项。 例如,每个命令可能有一组不同的选项。

OptionParser.enable_interspersed_args()
将解析设置为在第一个非选项上不停止,允许使用命令参数穿插开关。 这是默认行为。
OptionParser.get_option(opt_str)
如果没有选项具有该选项字符串,则返回带有选项字符串 opt_strNone 的选项实例。
OptionParser.has_option(opt_str)
如果 OptionParser 具有带有选项字符串 opt_str 的选项(例如,-q--verbose),则返回 True
OptionParser.remove_option(opt_str)
如果 OptionParser 具有对应于 opt_str 的选项,则删除该选项。 如果该选项提供了任何其他选项字符串,则所有这些选项字符串都将无效。 如果在属于此 OptionParser 的任何选项中未出现 opt_str,则引发 ValueError


选项之间的冲突

如果您不小心,很容易定义具有冲突选项字符串的选项:

parser.add_option("-n", "--dry-run", ...)
...
parser.add_option("-n", "--noisy", ...)

(如果您使用一些标准选项定义了自己的 OptionParser 子类,则尤其如此。)

每次添加选项时,optparse 都会检查与现有选项的冲突。 如果找到,则调用当前的冲突处理机制。 您可以在构造函数中设置冲突处理机制:

parser = OptionParser(..., conflict_handler=handler)

或单独调用:

parser.set_conflict_handler(handler)

可用的冲突处理程序是:

"error"(默认)
假设选项冲突是编程错误并引发 OptionConflictError
"resolve"
智能解决选项冲突(见下文)


例如,让我们定义一个 OptionParser 来智能地解决冲突并向其添加冲突选项:

parser = OptionParser(conflict_handler="resolve")
parser.add_option("-n", "--dry-run", ..., help="do no harm")
parser.add_option("-n", "--noisy", ..., help="be noisy")

此时,optparse 检测到之前添加的选项已经在使用 -n 选项字符串。 由于 conflict_handler"resolve",它通过从较早选项的选项字符串列表中删除 -n 来解决这种情况。 现在 --dry-run 是用户激活该选项的唯一方法。 如果用户寻求帮助,帮助消息将反映:

Options:
  --dry-run     do no harm
  ...
  -n, --noisy   be noisy

可以删除先前添加的选项的选项字符串,直到没有剩下的选项字符串,并且用户无法从命令行调用该选项。 在这种情况下, optparse 会完全删除该选项,因此它不会出现在帮助文本或其他任何地方。 继续我们现有的 OptionParser:

parser.add_option("--dry-run", ..., help="new dry-run option")

此时,原来的 -n/--dry-run 选项已不可访问,于是 optparse 将其移除,留下此帮助文本:

Options:
  ...
  -n, --noisy   be noisy
  --dry-run     new dry-run option

清理

OptionParser 实例有几个循环引用。 这对于 Python 的垃圾收集器来说应该不是问题,但是您可能希望在完成后通过在 OptionParser 上调用 destroy() 来显式地中断循环引用。 这在可从 OptionParser 访问大型对象图的长时间运行的应用程序中特别有用。


其他方法

OptionParser 支持其他几种公共方法:

OptionParser.set_usage(usage)
根据上述规则为 usage 构造函数关键字参数设置用法字符串。 传递 None 设置默认使用字符串; 使用 optparse.SUPPRESS_USAGE 抑制使用消息。
OptionParser.print_usage(file=None)
将当前程序 (self.usage) 的使用信息打印到 file(默认标准输出)。 self.usage 中出现的任何字符串 %prog 都将替换为当前程序的名称。 如果 self.usage 为空或未定义,则不执行任何操作。
OptionParser.get_usage()
print_usage() 相同,但返回用法字符串而不是打印它。
OptionParser.set_defaults(dest=value, ...)

一次为多个选项目的地设置默认值。 使用 set_defaults() 是设置选项默认值的首选方式,因为多个选项可以共享相同的目的地。 例如,如果多个“模式”选项都设置了相同的目的地,则其中任何一个都可以设置默认值,最后一个获胜:

parser.add_option("--advanced", action="store_const",
                  dest="mode", const="advanced",
                  default="novice")    # overridden below
parser.add_option("--novice", action="store_const",
                  dest="mode", const="novice",
                  default="advanced")  # overrides above setting

为避免这种混淆,请使用 set_defaults()

parser.set_defaults(mode="advanced")
parser.add_option("--advanced", action="store_const",
                  dest="mode", const="advanced")
parser.add_option("--novice", action="store_const",
                  dest="mode", const="novice")


期权回调

optparse 的内置操作和类型不足以满足您的需求时,您有两种选择:扩展 optparse 或定义回调选项。 扩展 optparse 更通用,但对于很多简单的情况来说太过分了。 通常,您只需要一个简单的回调即可。

定义回调选项有两个步骤:

  • 使用 "callback" 操作定义选项本身
  • 编写回调; 这是一个函数(或方法),它至少需要四个参数,如下所述

定义回调选项

与往常一样,定义回调选项的最简单方法是使用 OptionParser.add_option() 方法。 除了 action,您必须指定的唯一选项属性是 callback,要调用的函数:

parser.add_option("-c", action="callback", callback=my_callback)

callback 是一个函数(或其他可调用对象),因此您在创建此回调选项时必须已经定义了 my_callback()。 在这个简单的例子中,optparse 甚至不知道 -c 是否接受任何参数,这通常意味着该选项不接受任何参数——仅仅存在 -c 在命令行是它需要知道的全部。 但是,在某些情况下,您可能希望回调使用任意数量的命令行参数。 这就是编写回调变得棘手的地方; 本节稍后将对其进行介绍。

optparse 总是向你的回调传递四个特定的参数,如果你通过 callback_argscallback_kwargs 指定它们,它只会传递额外的参数。 因此,最小的回调函数签名是:

def my_callback(option, opt, value, parser):

回调的四个参数如下所述。

在定义回调选项时,您还可以提供其他几个选项属性:

type
具有其通常的含义:与 "store""append" 操作一样,它指示 optparse 使用一个参数并将其转换为 type。 但是,optparse 不是将转换后的值存储在任何地方,而是将其传递给您的回调函数。
nargs
也有其通常的含义:如果提供并且 > 1,optparse 将消耗 nargs 参数,每个参数都必须可转换为 type。 然后它将转换后的值的元组传递给您的回调。
callback_args
传递给回调的额外位置参数的元组
callback_kwargs
传递给回调的额外关键字参数字典


如何调用回调

所有回调的调用方式如下:

func(option, opt_str, value, parser, *args, **kwargs)

在哪里

option
是调用回调的 Option 实例
opt_str
是在命令行上看到的触发回调的选项字符串。 (如果使用了缩写的 long 选项,opt_str 将是完整的、规范的选项字符串——例如 如果用户在命令行中将 --foo 作为 --foobar 的缩写,则 opt_str 将是 "--foobar"。)
value
是在命令行上看到的此选项的参数。 optparse 仅在设置了 type 时才需要一个参数; value 的类型将是选项类型隐含的类型。 如果此选项的 typeNone(预期无参数),则 value 将为 None。 如果 nargs > 1,value 将是适当类型的值的元组。
parser
是驱动整个事情的 OptionParser 实例,主要是因为你可以通过它的实例属性访问一些其他有趣的数据:
parser.largs
剩余参数的当前列表,即。 已使用但既不是选项也不是选项参数的参数。 随意修改parser.largs,例如 通过向它添加更多参数。 (这个列表会变成argsparse_args()的第二个返回值。)
parser.rargs
剩余参数的当前列表,即。 删除了 opt_strvalue(如果适用),只有它们后面的参数仍然存在。 随意修改parser.rargs,例如 通过消耗更多参数。
parser.values
默认情况下存储选项值的对象(optparse.OptionValues 的一个实例)。 这让回调使用与 optparse 的其余部分相同的机制来存储选项值; 你不需要搞乱全局变量或闭包。 您还可以访问或修改已在命令行中遇到的任何选项的值。
args
是通过 callback_args 选项属性提供的任意位置参数的元组。
kwargs
是通过 callback_kwargs 提供的任意关键字参数的字典。


在回调中引发错误

如果选项或其参数有任何问题,回调函数应该引发 OptionValueErroroptparse 捕获并终止程序,打印您提供给 stderr 的错误消息。 您的消息应该清晰、简洁、准确,并提及错误的选项。 否则,用户将很难弄清楚他们做错了什么。


回调示例 1:普通回调

下面是一个不带参数的回调选项的例子,只记录选项被看到:

def record_foo_seen(option, opt_str, value, parser):
    parser.values.saw_foo = True

parser.add_option("--foo", action="callback", callback=record_foo_seen)

当然,您可以使用 "store_true" 操作来做到这一点。


回调示例2:检查选项顺序

这是一个稍微有趣的例子:记录看到 -a 的事实,但如果它在命令行中出现在 -b 之后,则爆炸。

def check_order(option, opt_str, value, parser):
    if parser.values.b:
        raise OptionValueError("can't use -a after -b")
    parser.values.a = 1
...
parser.add_option("-a", action="callback", callback=check_order)
parser.add_option("-b", action="store_true", dest="b")

回调示例 3:检查选项顺序(广义)

如果你想为几个类似的选项重用这个回调(设置一个标志,但如果 -b 已经被看到就会爆炸),它需要一些工作:错误消息和它设置的标志必须概括。

def check_order(option, opt_str, value, parser):
    if parser.values.b:
        raise OptionValueError("can't use %s after -b" % opt_str)
    setattr(parser.values, option.dest, 1)
...
parser.add_option("-a", action="callback", callback=check_order, dest='a')
parser.add_option("-b", action="store_true", dest="b")
parser.add_option("-c", action="callback", callback=check_order, dest='c')

回调示例4:检查任意条件

当然,您可以在其中放置任何条件——您不仅限于检查已定义选项的值。 例如,如果您有不应该在满月时调用的选项,您所要做的就是:

def check_moon(option, opt_str, value, parser):
    if is_moon_full():
        raise OptionValueError("%s option invalid when moon is full"
                               % opt_str)
    setattr(parser.values, option.dest, 1)
...
parser.add_option("--foo",
                  action="callback", callback=check_moon, dest="foo")

is_moon_full() 的定义留给读者作为练习。)


回调示例 5:固定参数

当您定义采用固定数量参数的回调选项时,事情会变得稍微有趣一些。 指定回调选项采用参数类似于定义 "store""append" 选项:如果您定义 type,则该选项采用一个必须可转换为该参数的参数类型; 如果您进一步定义 nargs,则该选项采用 nargs 参数。

这是一个仅模拟标准 "store" 操作的示例:

def store_value(option, opt_str, value, parser):
    setattr(parser.values, option.dest, value)
...
parser.add_option("--foo",
                  action="callback", callback=store_value,
                  type="int", nargs=3, dest="foo")

请注意, optparse 负责使用 3 个参数并将它们转换为整数; 您所要做的就是存储它们。 (或者其他什么;显然你不需要这个例子的回调。)


回调示例 6:可变参数

当您想要一个选项来接受可变数量的参数时,事情就会变得棘手。 对于这种情况,您必须编写回调,因为 optparse 不为其提供任何内置功能。 而且您必须处理 optparse 通常为您处理的传统 Unix 命令行解析的某些复杂问题。 特别是,回调应该为裸 --- 参数实现常规规则:

  • --- 可以是选项参数
  • --(如果不是某个选项的参数):停止命令行处理并丢弃 --
  • -(如果不是某个选项的参数):停止命令行处理但保留 -(将其附加到 parser.largs

如果您想要一个带有可变数量参数的选项,则需要担心几个微妙而棘手的问题。 您选择的确切实现将基于您愿意为应用程序做出的权衡(这就是 optparse 不直接支持此类事情的原因)。

尽管如此,这里还是一个带有可变参数的选项的回调:

def vararg_callback(option, opt_str, value, parser):
    assert value is None
    value = []

    def floatable(str):
        try:
            float(str)
            return True
        except ValueError:
            return False

    for arg in parser.rargs:
        # stop on --foo like options
        if arg[:2] == "--" and len(arg) > 2:
            break
        # stop on -a, but not on -3 or -3.0
        if arg[:1] == "-" and len(arg) > 1 and not floatable(arg):
            break
        value.append(arg)

    del parser.rargs[:len(value)]
    setattr(parser.values, option.dest, value)

...
parser.add_option("-c", "--callback", dest="vararg_attr",
                  action="callback", callback=vararg_callback)

扩展 optparse

由于 optparse 如何解释命令行选项的两个主要控制因素是每个选项的动作和类型,因此最可能的扩展方向是添加新动作和新类型。

添加新类型

要添加新类型,您需要定义自己的 optparseOption 类的子类。 这个类有几个定义 optparse 类型的属性:TYPESTYPE_CHECKER

Option.TYPES
类型名称的元组; 在您的子类中,只需定义一个基于标准元组的新元组 TYPES
Option.TYPE_CHECKER

将类型名称映射到类型检查函数的字典。 类型检查函数具有以下签名:

def check_mytype(option, opt, value)

其中 option 是一个 Option 实例,opt 是一个选项字符串(例如,-f),而 value 是来自必须检查并转换为所需类型的命令行。 check_mytype() 应该返回一个假设类型 mytype 的对象。 类型检查函数返回的值将在 OptionParser.parse_args() 返回的 OptionValues 实例中结束,或者作为 value 参数传递给回调。

如果遇到任何问题,您的类型检查函数应该引发 OptionValueErrorOptionValueError 接受单个字符串参数,该参数按原样传递给 OptionParsererror() 方法,该方法依次添加程序名称和字符串 [ X168X] 并在终止进程之前将所有内容打印到 stderr。

这是一个愚蠢的示例,演示了在命令行上添加 "complex" 选项类型以解析 Python 样式的复数。 (这比以前更傻了,因为 optparse 1.3 添加了对复数的内置支持,但没关系。)

一、必要的进口:

from copy import copy
from optparse import Option, OptionValueError

您需要首先定义您的类型检查器,因为它稍后会被引用(在您的 Option 子类的 TYPE_CHECKER 类属性中):

def check_complex(option, opt, value):
    try:
        return complex(value)
    except ValueError:
        raise OptionValueError(
            "option %s: invalid complex value: %r" % (opt, value))

最后,Option 子类:

class MyOption (Option):
    TYPES = Option.TYPES + ("complex",)
    TYPE_CHECKER = copy(Option.TYPE_CHECKER)
    TYPE_CHECKER["complex"] = check_complex

(如果我们不制作 Option.TYPE_CHECKERcopy(),我们最终会修改 optparseTYPE_CHECKER 属性的选项类。 这是 Python,除了礼貌和常识之外,没有什么能阻止你这样做。)

就是这样! 现在您可以编写一个使用新选项类型的脚本,就像任何其他基于 optparse 的脚本一样,除了您必须指示您的 OptionParser 使用 MyOption 而不是 Option:

parser = OptionParser(option_class=MyOption)
parser.add_option("-c", type="complex")

或者,您可以构建自己的选项列表并将其传递给 OptionParser; 如果不使用上述方式 add_option() ,则不需要告诉 OptionParser 使用哪个选项类:

option_list = [MyOption("-c", action="store", type="complex", dest="c")]
parser = OptionParser(option_list=option_list)

添加新动作

添加新动作有点棘手,因为您必须了解 optparse 对动作有几个分类:

“存储”操作
导致 optparse 将值存储到当前 OptionValues 实例的属性的操作; 这些选项需要将 dest 属性提供给 Option 构造函数。
“类型化”操作
从命令行获取值并期望它是某种类型的操作; 或者更确切地说,可以转换为某种类型的字符串。 这些选项需要 Option 构造函数的 type 属性。

这些是重叠的集合:一些默认的“存储”动作是 "store""store_const""append""count",而默认的“类型”动作是 [ X147X]、"append""callback"

当你添加一个动作时,你需要通过将它列在 Option 的以下类属性中的至少一个中来对其进行分类(都是字符串列表):

Option.ACTIONS
所有操作都必须在 ACTIONS 中列出。
Option.STORE_ACTIONS
此处还列出了“商店”操作。
Option.TYPED_ACTIONS
此处还列出了“类型”操作。
Option.ALWAYS_TYPED_ACTIONS
总是采用某种类型的操作(即 其选项始终采用一个值)在此处另外列出。 这样做的唯一影响是 optparse 将默认类型 "string" 分配给没有显式类型的选项,其操作在 ALWAYS_TYPED_ACTIONS 中列出。

为了实际实现您的新操作,您必须覆盖 Option 的 take_action() 方法并添加一个可识别您的操作的案例。

例如,让我们添加一个 "extend" 动作。 这类似于标准的 "append" 操作,但不是从命令行获取单个值并将其附加到现有列表中,"extend" 将在单个逗号分隔中获取多个值字符串,并用它们扩展现有列表。 也就是说,如果 --names"string" 类型的 "extend" 选项,则命令行

--names=foo,bar --names blah --names ding,dong

将导致一个列表

["foo", "bar", "blah", "ding", "dong"]

我们再次定义 Option 的子类:

class MyOption(Option):

    ACTIONS = Option.ACTIONS + ("extend",)
    STORE_ACTIONS = Option.STORE_ACTIONS + ("extend",)
    TYPED_ACTIONS = Option.TYPED_ACTIONS + ("extend",)
    ALWAYS_TYPED_ACTIONS = Option.ALWAYS_TYPED_ACTIONS + ("extend",)

    def take_action(self, action, dest, opt, value, values, parser):
        if action == "extend":
            lvalue = value.split(",")
            values.ensure_value(dest, []).extend(lvalue)
        else:
            Option.take_action(
                self, action, dest, opt, value, values, parser)

笔记特点:

  • "extend" 都需要命令行上的值并将该值存储在某处,因此它同时出现在 STORE_ACTIONSTYPED_ACTIONS 中。

  • 为确保 optparse"string" 的默认类型分配给 "extend" 动作,我们也将 "extend" 动作放在 ALWAYS_TYPED_ACTIONS 中.

  • MyOption.take_action() 仅实现了这一新动作,并将控制权交还给 Option.take_action() 以进行标准的 optparse 动作。

  • values 是 optparse_parser.Values 类的一个实例,它提供了非常有用的 ensure_value() 方法。 ensure_value() 本质上是 getattr() 带安全阀; 它被称为

    values.ensure_value(attr, value)

    如果valuesattr属性不存在或者是None,则ensure_value()首先将其设置为value,然后返回'value。 这对于像 "extend""append""count" 这样的动作非常方便,所有这些动作都在一个变量中累积数据并期望该变量是某种类型(列表对于前两个,对于后者是一个整数)。 使用 ensure_value() 意味着使用您的操作的脚本不必担心为相关选项目的地设置默认值; 他们可以将默认值保留为 None,而 ensure_value() 会在需要时负责将其正确处理。