optparse
— Parser for command line options命令行选项的分析器¶
Source code: Lib/optparse.py
Deprecated since version 3.2: The optparse
module is deprecated and will not be developed further; development will continue with the argparse
module.optparse
模块已弃用,将不再进一步开发;argparse
模块将继续开发。
optparse
is a more convenient, flexible, and powerful library for parsing command-line options than the old 是一个比旧的getopt
module. getopt
模块更方便、更灵活、更强大的用于解析命令行选项的库。optparse
uses a more declarative style of command-line parsing: you create an instance of 使用更具声明性的命令行解析风格:创建OptionParser
, populate it with options, and parse the command line. OptionParser
的实例,用选项填充它,并解析命令行。optparse
allows users to specify options in the conventional GNU/POSIX syntax, and additionally generates usage and help messages for you.允许用户在常规GNU/POSIX语法中指定选项,并为您生成用法和帮助消息。
Here’s an example of using 下面是一个在简单脚本中使用optparse
in a simple script: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()
With these few lines of code, users of your script can now do the “usual thing” on the command-line, for example:通过这几行代码,脚本的用户现在可以在命令行上执行“常规操作”,例如:
<yourscript> --file=outfile -q
As it parses the command line, 在解析命令行时,optparse
sets attributes of the options
object returned by parse_args()
based on user-supplied command-line values. optparse
根据用户提供的命令行值设置parse_args()
返回的options
对象的属性。When 当parse_args()
returns from parsing this command line, options.filename
will be "outfile"
and options.verbose
will be False
. parse_args()
解析此命令行返回时,options.filename
将为"outfile"
,options.verbose
将为False
。optparse
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:因此,以下命令行都与上述示例等效:
<yourscript> -f outfile --quiet
<yourscript> --quiet --file outfile
<yourscript> -q -foutfile
<yourscript> -qfoutfile
Additionally, users can run one of the following此外,用户可以运行以下操作之一
<yourscript> -h
<yourscript> --help
and optparse
will print out a brief summary of your script’s options: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
where the value of yourscript is determined at runtime (normally from 其中yourscript的值是在运行时确定的(通常来自sys.argv[0]
).sys.argv[0]
)。
Background背景¶
optparse
was explicitly designed to encourage the creation of programs with straightforward, conventional command-line interfaces. 被明确设计为鼓励使用直接的常规命令行界面创建程序。To that end, it supports only the most common command-line syntax and semantics conventionally used under Unix. 为此,它只支持Unix下常用的最常见的命令行语法和语义。If you are unfamiliar with these conventions, read this section to acquaint yourself with them.如果您不熟悉这些约定,请阅读本节以熟悉它们。
Terminology术语¶
- argument
a string entered on the command-line, and passed by the shell to在命令行上输入的字符串,并由shell传递给execl()
orexecv()
.execl()
或execv()
。In Python, arguments are elements of在Python中,参数是sys.argv[1:]
(sys.argv[0]
is the name of the program being executed).sys.argv[1:]
的元素(sys.argv[0]
是正在执行的程序的名称)。Unix shells also use the term “word”.Unix shell也使用术语“单词”。It is occasionally desirable to substitute an argument list other than有时需要替换sys.argv[1:]
, so you should read “argument” as “an element ofsys.argv[1:]
, or of some other list provided as a substitute forsys.argv[1:]
”.sys.argv[1:]
以外的参数列表,因此您应该将“argument”读为sys.argv[1:]
的元素,或作为sys.argv[1:]
的替代项提供的其他列表的元素。- option
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 (“-”) followed by a single letter, e.g.选项有许多不同的语法;传统的Unix语法是连字符(“-”)后跟一个字母,例如-x
or-F
.-x
或-F
。Also, traditional Unix syntax allows multiple options to be merged into a single argument, e.g.此外,传统的Unix语法允许将多个选项合并为一个参数,例如-x -F
is equivalent to-xF
.-x -F
等同于-xF
。The GNU project introducedGNU项目引入了一系列连字符--
followed by a series of hyphen-separated words, e.g.--file
or--dry-run
.--
分隔的单词,例如--file
或--dry-run
。These are the only two option syntaxes provided by这是optparse
.optparse
提供的仅有的两种选项语法。Some other option syntaxes that the world has seen include:世界上看到的一些其他选项语法包括:a hyphen followed by a few letters, e.g.连字符后跟几个字母,例如-pf
(this is not the same as multiple options merged into a single argument)-pf
(这与将多个选项合并为一个参数不同)a hyphen followed by a whole word, e.g.连字符后跟一个完整的单词,例如-file
(this is technically equivalent to the previous syntax, but they aren’t usually seen in the same program)-file
(这在技术上等同于前面的语法,但通常不会在同一程序中看到)a plus sign followed by a single letter, or a few letters, or a word, e.g.一个加号后跟一个字母,或几个字母,或一个单词,例如+f
,+rgb
+f
,+rgb
a slash followed by a letter, or a few letters, or a word, e.g.一个斜杠后跟一个字母,或几个字母,或一个单词,例如/f
,/file
/f
,/file
These option syntaxes are not supported byoptparse
, and they never will be.optparse
不支持这些选项语法,而且永远不会支持。This is deliberate: the first three are non-standard on any environment, and the last only makes sense if you’re exclusively targeting VMS, MS-DOS, and/or Windows.这是故意的:前三个在任何环境下都是非标准的,只有当您专门针对VMS、MS-DOS和/或Windows时,最后一个才有意义。option argument选项自变量an argument that follows an option, is closely associated with that option, and is consumed from the argument list when that option is.选项后面的参数,与该选项密切相关,并且在该选项存在时从参数列表中消耗。With使用optparse
, option arguments may either be in a separate argument from their option:optparse
,选项参数可以位于与其选项独立的参数中:-f foo
--file fooor included in the same argument:或包含在同一参数中:-ffoo
--file=fooTypically, a given option either takes an argument or it doesn’t.通常,给定的选项要么有一个参数,要么没有。Lots of people want an “optional option arguments” feature, meaning that some options will take an argument if they see it, and won’t if they don’t.很多人都想要一个“可选选项参数”功能,这意味着有些选项如果看到了参数就会接受,如果没有,就不会接受。This is somewhat controversial, because it makes parsing ambiguous: if这有点争议,因为它使解析变得模棱两可:如果-a
takes an optional argument and-b
is another option entirely, how do we interpret-ab
?-a
采用可选参数,-b
完全是另一个选项,我们如何解释-ab
?Because of this ambiguity,由于这种歧义,optparse
does not support this feature.optparse
不支持此功能。positional argument位置自变量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.解析选项后,参数列表中剩余的内容,即解析选项及其参数并将其从参数列表中删除后。required option必需的选项an option that must be supplied on the command-line; note that the phrase “required option” is self-contradictory in English.必须在命令行上提供的选项;注意,短语“required option”在英语中是自相矛盾的。optparse
doesn’t prevent you from implementing required options, but doesn’t give you much help at it either.不会阻止您实现所需的选项,但也不会给您带来太多帮助。
For example, consider this hypothetical command-line:例如,考虑以下假设的命令行:
prog -v --report report.txt foo bar
-v
and --report
are both options. -v
和--report
都是选项。Assuming that 假设--report
takes one argument, report.txt
is an option argument. --report
有一个参数,report.txt
是一个选项参数。foo
and bar
are positional arguments.foo
和bar
是位置参数。
What are options for?有哪些选项?¶
Options are used to provide extra information to tune or customize the execution 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. (从Unix或GNU工具集中选择一个随机程序。Can it run without any options at all and still make sense? 它能在没有任何选择的情况下运行并且仍然有意义吗?The main exceptions are 主要的例外是find
, tar
, and dd
—all of which are mutant oddballs that have been rightly criticized for their non-standard syntax and confusing interfaces.)find
、tar
和dd
,所有这些都是变异的怪球,因为它们不标准的语法和令人困惑的接口而受到了正确的批评。)
Lots of people want their programs to have “required options”. 许多人希望他们的程序有“必需的选项”。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 作为良好的命令行界面设计的一个示例,可以考虑用于复制文件的简单cp
utility, for copying files. cp
实用程序。It doesn’t make much sense to try to copy files without supplying a destination and at least one source. 在不提供目标和至少一个源的情况下尝试复制文件没有多大意义。Hence, 因此,如果在没有参数的情况下运行cp
fails if you run it with no arguments. cp
,则会失败。However, it has a flexible, useful syntax that does not require any options at all:然而,它有一个灵活、有用的语法,根本不需要任何选项:
cp SOURCE DEST
cp SOURCE ... DEST-DIR
You can get pretty far with just that. 你可以做到这一点。Most 大多数cp
implementations provide a 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. cp
实现提供了一系列选项来精确调整文件的复制方式:您可以保留模式和修改时间,避免使用符号链接,在删除现有文件之前询问,等等。But none of this distracts from the core mission of 但这些都没有分散cp
, which is to copy either one file to another, or several files to another directory.cp
的核心任务,即将一个文件复制到另一个文件,或将几个文件复制到其他目录。
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 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. 如果您的程序需要17条不同的信息才能成功运行,那么如何从用户那里获得这些信息并不重要,大多数人会在成功运行程序之前放弃并走开。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.无论用户界面是命令行、配置文件还是GUI,这一点都适用:如果你对用户提出了那么多要求,大多数用户都会放弃。
In short, try to minimize the amount of information that users are absolutely 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 “Preferences” 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. 同样,无论它们是配置文件中的条目、GUI的“首选项”对话框中的小部件,还是命令行选项,您实现的选项越多,程序就越灵活,实现也就越复杂。Too much flexibility has drawbacks as well, of course;
too many options can overwhelm users and make your code much harder to maintain.当然,过于灵活也有缺点;太多的选项会让用户不堪重负,使代码更难维护。
Tutorial教程¶
While 虽然optparse
is quite flexible and powerful, it’s also straightforward to use in most cases. optparse
非常灵活和强大,但在大多数情况下也很容易使用。This section covers the code patterns that are common to any 本节介绍了任何基于optparse
-based program.optparse
的程序通用的代码模式。
First, you need to import the OptionParser class; then, early in the main program, create an OptionParser instance:首先,您需要导入OptionParser类;然后,在主程序的早期,创建一个OptionParser实例:
from optparse import OptionParser
...
parser = OptionParser()
Then you can start defining options. 然后可以开始定义选项。The basic syntax is:基本语法为:
parser.add_option(opt_str, ...,
attr=value, ...)
Each option has one or more option strings, such as 每个选项都有一个或多个选项字符串,例如-f
or --file
, and several option attributes that tell optparse
what to expect and what to do when it encounters that option on the command line.-f
或--file
,以及几个选项属性,这些属性告诉optparse
在命令行上遇到该选项时应该做什么以及应该做什么。
Typically, each option will have one short option string and one long option string, e.g.:通常,每个选项都有一个短选项字符串和一个长选项字符串,例如:
parser.add_option("-f", "--file", ...)
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 传递给OptionParser.add_option()
are effectively labels for the option defined by that call. OptionParser.add_option()
的选项字符串实际上是该调用定义的选项的标签。For brevity, we will frequently refer to encountering an option on the command line; in reality, 为了简洁起见,我们将经常提到在命令行上遇到一个选项;实际上,optparse
encounters option strings and looks up options from them.optparse
遇到选项字符串并从中查找选项。
Once all of your options are defined, instruct 定义所有选项后,指示optparse
to parse your program’s command line:optparse
解析程序的命令行:
(options, args) = parser.parse_args()
(If you like, you can pass a custom argument list to (如果愿意,可以将自定义参数列表传递给parse_args()
, but that’s rarely necessary: by default it uses sys.argv[1:]
.)parse_args()
,但这很少是必要的:默认情况下,它使用sys.argv[1:]
。)
parse_args()
returns two values:返回两个值:
options
, an object containing values for all of your options—e.g. if--file
takes a single string argument, thenoptions.file
will be the filename supplied by the user, orNone
if the user did not supply that optionoptions
,一个包含所有选项值的对象,例如。如果--file
采用单个字符串参数,则options.file
将是用户提供的文件名,如果用户未提供该选项,则为None
args
, the list of positional arguments leftover after parsing options,解析选项后剩余的位置参数列表
This tutorial section only covers the four most important option attributes: 本教程部分仅介绍四个最重要的选项属性:action
, type
, dest
(destination), and help
. action
、type
、dest
(目标)和help
。Of these, 其中,action
is the most fundamental.action
是最根本的。
Understanding option actions了解选项操作¶
Actions tell 操作告诉optparse
what to do when it encounters an option on the command line. optparse
在命令行上遇到选项时要做什么。There is a fixed set of actions hard-coded into 有一组固定的操作硬编码到optparse
; adding new actions is an advanced topic covered in section Extending optparse. optparse
中;添加新操作是扩展optparse一节中涉及的高级主题。Most actions tell 大多数操作告诉optparse
to store a value in some variable—for example, take a string from the command line and store it in an attribute of options
.optparse
将值存储在某个变量中。例如,从命令行获取字符串并将其存储在options
属性中。
If you don’t specify an option action, 如果不指定选项操作,optparse
defaults to store
.optparse
默认为store
。
The store action存储操作¶
The most common option action is 最常见的选项操作是store
, which tells optparse
to take 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.store
,它告诉optparse
获取下一个参数(或当前参数的其余部分),确保其类型正确,并将其存储到您选择的目标位置。
For example:例如:
parser.add_option("-f", "--file",
action="store", type="string", dest="filename")
Now let’s make up a fake command line and ask 现在,让我们编一个假的命令行,让optparse
to parse it:optparse
解析它:
args = ["-f", "foo.txt"]
(options, args) = parser.parse_args(args)
When 当optparse
sees the option string -f
, it consumes the next argument, foo.txt
, and stores it in options.filename
. optparse
看到选项字符串-f
时,它将使用下一个参数foo.txt
,并将其存储在options.filename
中。So, after this call to 因此,在调用parse_args()
, options.filename
is "foo.txt"
.parse_args()
之后,options.filename
为"foo.txt"
。
Some other option types supported by optparse
are int
and float
. optparse
支持的其他一些选项类型是int
和float
。Here’s an option that expects an integer argument:下面是一个需要整数参数的选项:
parser.add_option("-n", type="int", dest="num")
Note that this option has no long option string, which is perfectly acceptable. 请注意,此选项没有长选项字符串,这是完全可以接受的。Also, there’s no explicit action, since the default is 此外,由于默认值为store
.store
,因此没有显式操作。
Let’s parse another fake command-line. 让我们解析另一个伪命令行。This time, we’ll jam the option argument right up against the option: since 这一次,我们将把option参数与option对齐:由于-n42
(one argument) is equivalent to -n 42
(two arguments), the code-n42
(一个参数)相当于-n 42
(两个参数),代码
(options, args) = parser.parse_args(["-n42"])
print(options.num)
will print 将打印42
.42
。
If you don’t specify a type, 如果不指定类型,optparse
assumes string
. optparse
将采用string
。Combined with the fact that the default action is 再加上默认操作是store
, that means our first example can be a lot shorter:store
,这意味着第一个示例可以更短:
parser.add_option("-f", "--file", dest="filename")
If you don’t supply a destination, 如果不提供目标,optparse
figures out a sensible default from the option strings: if the first long option string is --foo-bar
, then the default destination is foo_bar
. optparse
会从选项字符串中找出一个合理的默认值:如果第一个长选项字符串是--foo-bar
,那么默认目标是foo_bar
。If there are no long option strings, 如果没有长选项字符串,optparse
looks at the first short option string: the default destination for -f
is f
.optparse
将查看第一个短选项字符串:-f
的默认目标是f
。
optparse
also includes the built-in 还包括内置complex
type. complex
类型。Adding types is covered in section Extending optparse.扩展optparse一节介绍了添加类型。
Handling boolean (flag) option处理布尔值(标志)选项¶
Flag options—set a variable to true or false when a particular option is seen—are quite common. 当看到特定选项时,标志选项将变量设置为true
或false
是非常常见的。optparse
supports them with two separate actions, 通过两个单独的操作store_true
and store_false
. store_true
和store_false
支持它们。For example, you might have a 例如,您可能有一个verbose
flag that is turned on with -v
and off with -q
:verbose
标志,它用-v
打开,用-q
关闭:
parser.add_option("-v", action="store_true", dest="verbose")
parser.add_option("-q", action="store_false", dest="verbose")
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 当optparse
encounters -v
on the command line, it sets options.verbose
to True
; when it encounters -q
, options.verbose
is set to False
.optparse
在命令行上遇到-v
时,它将options.verbose
设置为True
;当遇到-q
时,options.verbose
设置为False
。
Other actions其他操作¶
Some other actions supported by optparse
are:optparse
支持的其他一些操作包括:
"store_const"
store a constant value存储常量值"append"
append this option’s argument to a list将此选项的参数附加到列表"count"
increment a counter by one计数器加1"callback"
call a specified function调用指定的函数
These are covered in section Reference Guide, and section Option Callbacks.这些内容在参考指南和选项回调一节中介绍。
Default values默认值¶
All of the above examples involve setting some variable (the “destination”) when 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 因为我们没有提供任何默认值,所以它们都设置为None
. None
。This is usually fine, but sometimes you want more control. 这通常很好,但有时你需要更多的控制。optparse
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 如果我们希望optparse
to set verbose
to True
unless -q
is seen, then we can do this:optparse
将verbose
设置为True
,除非看到-q
,那么我们可以这样做:
parser.add_option("-v", action="store_true", dest="verbose", default=True)
parser.add_option("-q", action="store_false", dest="verbose")
Since default values apply to the destination rather than to any particular option, and these two options happen to have the same destination, this is exactly equivalent:由于默认值适用于目标,而不是任何特定选项,并且这两个选项恰好具有相同的目标,因此这是完全等效的:
parser.add_option("-v", action="store_true", dest="verbose")
parser.add_option("-q", action="store_false", dest="verbose", default=True)
Consider this:考虑一下:
parser.add_option("-v", action="store_true", dest="verbose", default=False)
parser.add_option("-q", action="store_false", dest="verbose", default=True)
Again, the default value for 同样,verbose
will be True
: the last default value supplied for any particular destination is the one that counts.verbose
的默认值将为True
:为任何特定目标提供的最后一个默认值都是有意义的值。
A clearer way to specify default values is the 指定默认值的更清晰的方法是OptionParser的set_defaults()
method of OptionParser, which you can call at any time before calling parse_args()
:set_defaults()
方法,您可以在调用parse_args()
之前随时调用该方法:
parser.set_defaults(verbose=True)
parser.add_option(...)
(options, args) = parser.parse_args()
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.为了清楚起见,请尝试使用一种或另一种设置默认值的方法,而不是同时使用这两种方法。
Generating help生成帮助¶
optparse
’s ability to generate help and usage text automatically is useful for creating user-friendly command-line interfaces. optparse
自动生成帮助和用法文本的能力对于创建用户友好的命令行界面非常有用。All you have to do is supply a 您所要做的就是为每个选项提供一个help
value for each option, and optionally a short usage message for your whole program. help
值,并可选地为整个程序提供一条简短的用法消息。Here’s an OptionParser populated with user-friendly (documented) options:下面是一个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]")
If 如果optparse
encounters either -h
or --help
on the command-line, or if you just call parser.print_help()
, it prints the following to standard output: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]
(If the help output is triggered by a help option, (如果帮助输出由帮助选项触发,optparse
exits after printing the help text.)optparse
将在打印帮助文本后退出。)
There’s a lot going on here to help 这里有很多帮助optparse
generate the best possible help message:optparse
生成最佳帮助消息:
the script defines its own usage message:脚本定义自己的使用消息:usage = "usage: %prog [options] arg1 arg2"
optparse
expands将用法字符串中的%prog
in the usage string to the name of the current program, i.e.os.path.basename(sys.argv[0])
.%prog
扩展为当前程序的名称,即os.path.basename(sys.argv[0])
。The expanded string is then printed before the detailed option help.然后在详细选项帮助之前打印展开的字符串。If you don’t supply a usage string,如果不提供用法字符串,optparse
uses a bland but sensible default:"Usage: %prog [options]"
, which is fine if your script doesn’t take any positional arguments.optparse
将使用一个平淡但合理的默认值:"Usage: %prog [options]"
,如果脚本不接受任何位置参数,这是很好的。every option defines a help string, and doesn’t worry about line-wrapping—每个选项都定义了一个帮助字符串,而不必担心换行。optparse
takes care of wrapping lines and making the help output look good.optparse
负责换行并使帮助输出看起来很好。options that take a value indicate this fact in their automatically-generated help message, e.g. for the “mode” option:取值的选项在其自动生成的帮助消息中指示这一事实,例如,对于“模式”选项:-m MODE, --mode=MODE
Here, “MODE” is called the meta-variable: it stands for the argument that the user is expected to supply to这里,“MODE”被称为元变量:它代表用户希望提供给-m
/--mode
.-m
/--mode
的参数。By default,默认情况下,optparse
converts the destination variable name to uppercase and uses that for the meta-variable.optparse
将目标变量名称转换为大写,并将其用于元变量。Sometimes, that’s not what you want—for example, the有时,这不是您想要的。例如,--filename
option explicitly setsmetavar="FILE"
, resulting in this automatically-generated option description:--filename
选项显式地设置metavar="FILE"
,从而生成自动生成的选项描述:-f FILE, --filename=FILE
This is important for more than just saving space, though: the manually written help text uses the meta-variable这不仅仅是为了节省空间,这一点很重要:手动编写的帮助文本使用元变量FILE
to clue the user in that there’s a connection between the semi-formal syntax-f FILE
and the informal semantic description “write output to FILE”.FILE
来提示用户,半正式语法-f FILE
和非正式语义描述“将输出写入FILE”之间存在联系。This is a simple but effective way to make your help text a lot clearer and more useful for end users.这是一种简单但有效的方法,可以使帮助文本更清晰,对最终用户更有用。options that have a default value can include具有默认值的选项可以在帮助字符串中包含%default
in the help string—optparse
will replace it withstr()
of the option’s default value.%default
。optparse
将用选项默认值的str()
替换它。If an option has no default value (or the default value is如果选项没有默认值(或默认值为None
),%default
expands tonone
.None
),%default
将扩展为none
。
Grouping Options分组选项¶
When dealing with many options, it is convenient to group these options for better help output. 在处理许多选项时,将这些选项分组以获得更好的帮助输出是很方便的。An OptionParser
can contain several option groups, each of which can contain several options.OptionParser
可以包含多个选项组,每个选项组可以包含几个选项。
An option group is obtained using the class 使用OptionGroup
:OptionGroup
类获得选项组:
-
class
optparse.
OptionGroup
(parser, title, description=None)¶ where
parser is theparser是组将插入其中的OptionParser
instance the group will be inserted in toOptionParser
实例title is the group titletitle是组标题description, optional, is a long description of the groupdescription(可选)是组的详细描述
OptionGroup
inherits from 继承自OptionContainer
(like OptionParser
) and so the add_option()
method can be used to add an option to the group.OptionContainer
(如OptionParser
),因此可以使用add_option()
方法将选项添加到组中。
Once all the options are declared, using the 声明所有选项后,使用OptionParser
method add_option_group()
the group is added to the previously defined parser.OptionParser
方法add_option_group()
将组添加到先前定义的解析器中。
Continuing with the parser defined in the previous section, adding an 继续上一节中定义的解析器,向解析器添加OptionGroup
to a parser is easy: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)
This would result in the following help output:这将导致以下帮助输出:
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.
A bit more complete example might involve using more than one group: still extending the previous example:一个更完整的示例可能涉及使用多个组:仍然扩展前面的示例:
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)
that results in the following output:这将导致以下输出:
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
Another interesting method, in particular when working programmatically with option groups is:另一个有趣的方法,特别是在以编程方式处理选项组时,是:
-
OptionParser.
get_option_group
(opt_str)¶ Return the返回短或长选项字符串opt_str(例如OptionGroup
to which the short or long option string opt_str (e.g.'-o'
or'--option'
) belongs.'-o'
或'--option'
)所属的OptionGroup
。If there’s no such如果没有这样的OptionGroup
, returnNone
.OptionGroup
,则返回None
。
Printing a version string打印版本字符串¶
Similar to the brief usage string, 与简短用法字符串类似,optparse
can also print a version string for your program. optparse
也可以为程序打印版本字符串。You have to supply the string as the 您必须将字符串作为version
argument to OptionParser:version
参数提供给OptionParser:
parser = OptionParser(usage="%prog [-f] [-q]", version="%prog 1.0")
%prog
is expanded just like it is in usage
. %prog
就像在usage
中一样被扩展。Apart from that, 除此之外,version
can contain anything you like. version
可以包含任何您喜欢的内容。When you supply it, 当您提供它时,optparse
automatically adds a --version
option to your parser. optparse
会自动向解析器添加--version
选项。If it encounters this option on the command line, it expands your 如果它在命令行上遇到此选项,它将扩展version
string (by replacing %prog
), prints it to stdout, and exits.version
字符串(通过替换%prog
),将其打印到stdout,然后退出。
For example, if your script is called 例如,如果脚本名为/usr/bin/foo
:/usr/bin/foo
:
$ /usr/bin/foo --version
foo 1.0
The following two methods can be used to print and get the 以下两种方法可用于打印和获取version
string:version
字符串:
-
OptionParser.
print_version
(file=None)¶ Print the version message for the current program (将当前程序的版本消息(self.version
) to file (default stdout).self.version
)打印到file(默认stdout)。As with与print_usage()
, any occurrence of%prog
inself.version
is replaced with the name of the current program.print_usage()
一样,self.version
中%prog
的任何出现都将替换为当前程序的名称。Does nothing if如果self.version
is empty or undefined.self.version
为空或未定义,则不执行任何操作。
-
OptionParser.
get_version
()¶ Same as与print_version()
but returns the version string instead of printing it.print_version()
相同,但返回版本字符串而不是打印。
How optparse
handles errorsoptparse
如何处理错误¶
optparse
handles errorsThere are two broad classes of errors that optparse
has to worry about: programmer errors and user errors. optparse
需要担心两大类错误:程序员错误和用户错误。Programmer errors are usually erroneous calls to 程序员错误通常是对OptionParser.add_option()
, e.g. invalid option strings, unknown option attributes, missing option attributes, etc. OptionParser.add_option()
的错误调用,例如,无效的选项字符串、未知的选项属性、缺少的选项属性等。These are dealt with in the usual way: raise an exception (either 这些错误以通常的方式处理:引发异常(optparse.OptionError
or TypeError
) and let the program crash.optparse.OptionError
或TypeError
)并让程序崩溃。
Handling user errors is much more important, since they are guaranteed to happen no matter how stable your code is. 处理用户错误要重要得多,因为无论您的代码多么稳定,它们都会发生。optparse
can automatically detect some user errors, such as bad option arguments (passing -n 4x
where -n
takes an integer argument), missing arguments (-n
at the end of the command line, where -n
takes an argument of any type). optparse
可以自动检测一些用户错误,例如错误的选项参数(传递-n 4x
,其中-n
采用整数参数)、缺少参数(命令行末尾的-n
,其中-n
使用任何类型的参数)。Also, you can call 此外,您还可以调用OptionParser.error()
to signal an application-defined error condition:OptionParser.error()
来发出应用程序定义的错误条件信号:
(options, args) = parser.parse_args()
...
if options.a and options.b:
parser.error("options -a and -b are mutually exclusive")
In either case, 无论哪种情况,optparse
handles the error the same way: it prints the program’s usage message and an error message to standard error and exits with error status 2.optparse
都以相同的方式处理错误:它将程序的使用消息和错误消息打印为标准错误,并以错误状态2退出。
Consider the first example above, where the user passes 考虑上面的第一个示例,其中用户将4x
to an option that takes an integer:4x
传递给一个整数选项:
$ /usr/bin/foo -n 4x
Usage: foo [options]
foo: error: option -n: invalid integer value: '4x'
Or, where the user fails to pass a value at all:或者,如果用户根本无法传递值:
$ /usr/bin/foo -n
Usage: foo [options]
foo: error: -n option requires an argument
optparse
-generated error messages take care always to mention the option involved in the error; be sure to do the same when calling 生成的错误消息总是注意提及错误中涉及的选项;在从应用程序代码调用OptionParser.error()
from your application code.OptionParser.error()
时,请务必执行同样的操作。
If 如果optparse
’s default error-handling behaviour does not suit your needs, you’ll need to subclass OptionParser and override its exit()
and/or error()
methods.optparse
的默认错误处理行为不符合您的需要,则需要将OptionParser
子类化并重写其exit()
和/或error()
方法。
Putting it all together把这一切放在一起¶
Here’s what 以下是基于optparse
-based scripts usually look like: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()
Reference Guide参考指南¶
Creating the parser创建解析器¶
The first step in using 使用optparse
is to create an OptionParser instance.optparse
的第一步是创建OptionParser实例。
-
class
optparse.
OptionParser
(...)¶ The OptionParser constructor has no required arguments, but a number of optional keyword arguments.OptionParser构造函数没有必需的参数,但有一些可选的关键字参数。You should always pass them as keyword arguments, i.e. do not rely on the order in which the arguments are declared.您应该始终将它们作为关键字参数传递,即不要依赖参数的声明顺序。usage
(default:"%prog [options]"
)The usage summary to print when your program is run incorrectly or with a help option.程序运行错误或带有帮助选项时要打印的使用情况摘要。When当optparse
prints the usage string, it expands%prog
toos.path.basename(sys.argv[0])
(or toprog
if you passed that keyword argument).optparse
打印用法字符串时,它将%prog
扩展为os.path.basename(sys.argv[0])
(如果传递了关键字参数,则扩展为prog
)。To suppress a usage message, pass the special value要抑制使用消息,请传递特殊值optparse.SUPPRESS_USAGE
.optparse.SUPPRESS_USAGE
。option_list
(default:[]
)A list of Option objects to populate the parser with.用于填充解析器的Option对象列表。The options inoption_list
are added after any options instandard_option_list
(a class attribute that may be set by OptionParser subclasses), but before any version or help options.option_list
中的选项添加在standard_option_list
(一个类属性,可由OptionParser子类设置)中的任何选项之后,但添加在任何版本或帮助选项之前。Deprecated; use已弃用;在创建解析器后使用add_option()
after creating the parser instead.add_option()
。option_class
(default:optparse.Option
)Class to use when adding options to the parser in在add_option()
.add_option()
中向解析器添加选项时使用的类。version
(default:None
)A version string to print when the user supplies a version option.用户提供版本选项时要打印的版本字符串。If you supply a true value for如果您为version
,optparse
automatically adds a version option with the single option string--version
.version
提供了一个true
值,optparse
会自动添加一个带有单个选项字符串--version
的版本选项。The substring子字符串%prog
is expanded the same as forusage
.%prog
的展开方式与usage
相同。conflict_handler
(default:"error"
)Specifies what to do when options with conflicting option strings are added to the parser; see section Conflicts between options.指定将具有冲突选项字符串的选项添加到解析器时要执行的操作;请参阅选项之间的冲突一节。description
(default:None
)A paragraph of text giving a brief overview of your program.一段文字,简要概述您的计划。optparse
reformats this paragraph to fit the current terminal width and prints it when the user requests help (after重新格式化此段落以适合当前的终端宽度,并在用户请求帮助时打印(在usage
, but before the list of options).usage
后面,但在选项列表之前)。formatter
(default: a newIndentedHelpFormatter
)An instance of将用于打印帮助文本的optparse.HelpFormatter
that will be used for printing help text.optparse.HelpFormatter
实例。optparse
provides two concrete classes for this purpose: IndentedHelpFormatter and TitledHelpFormatter.为此提供了两个具体的类:IndendedHelpFormatter
和TitledHelpFormater
。add_help_option
(default:True
)If true,如果为optparse
will add a help option (with option strings-h
and--help
) to the parser.true
,optparse
将向解析器添加一个帮助选项(带有选项字符串-h
和--help
)。prog
The string to use when expanding在%prog
inusage
andversion
instead ofos.path.basename(sys.argv[0])
.usage
和version
中展开%prog
而不是os.path.basename(sys.argv[0])
时要使用的字符串。epilog
(default:None
)A paragraph of help text to print after the option help.选项帮助后要打印的一段帮助文本。
Populating the parser填充解析器¶
There are several ways to populate the parser with options. 有几种方法可以用选项填充解析器。The preferred way is by using 首选方法是使用OptionParser.add_option()
, as shown in section Tutorial. OptionParser.add_option()
,如教程部分所示。add_option()
can be called in one of two ways:可以通过以下两种方式之一调用:
pass it an Option instance (as returned by传递给它一个Option实例(由make_option()
)make_Option()
返回)pass it any combination of positional and keyword arguments that are acceptable to将make_option()
(i.e., to the Option constructor), and it will create the Option instance for youmake_option()
可接受的位置和关键字参数的任何组合传递给它(即,传递给Option构造函数),它将为您创建Option实例
The other alternative is to pass a list of pre-constructed Option instances to the OptionParser constructor, as in:另一种方法是将预先构造的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()
is a factory function for creating Option instances; currently it is an alias for the Option constructor. make_option()
是用于创建Option实例的工厂函数;当前它是Option构造函数的别名。A future version of optparse
may split Option into several classes, and make_option()
will pick the right class to instantiate. optparse
的未来版本可能会将Option拆分为几个类,make_Option()
将选择合适的类来实例化。Do not instantiate Option directly.)不要直接实例化Option。)
Defining options定义选项¶
Each Option instance represents a set of synonymous command-line option strings, e.g. 每个Option实例代表一组同义的命令行选项字符串,例如-f
and --file
. -f
和--file
。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 创建Option
instance is with the add_option()
method of OptionParser
.Option
实例的规范方法是使用OptionParser
的add_Option()
方法。
-
OptionParser.
add_option
(option)¶ -
OptionParser.
add_option
(*opt_str, attr=value, ...) To define an option with only a short option string:要定义仅包含短选项字符串的选项,请执行以下操作:parser.add_option("-f", attr=value, ...)
And to define an option with only a long option string:要定义仅包含长选项字符串的选项,请执行以下操作:parser.add_option("--foo", attr=value, ...)
The keyword arguments define attributes of the new Option object.关键字参数定义新Option对象的属性。The most important option attribute is最重要的选项属性是action
, and it largely determines which other attributes are relevant or required.action
,它在很大程度上决定了哪些其他属性是相关的或需要的。If you pass irrelevant option attributes, or fail to pass required ones,如果传递不相关的选项属性,或未能传递所需的属性,optparse
raises anOptionError
exception explaining your mistake.optparse
将引发OptionError
异常,解释错误。An option’s action determines what选项的操作决定了optparse
does when it encounters this option on the command-line.optparse
在命令行上遇到此选项时的操作。The standard option actions hard-coded into硬编码到optparse
are:optparse
中的标准选项操作包括:"store"
store this option’s argument (default)存储此选项的参数(默认值)"store_const"
store a constant value存储常量值"store_true"
store百货商店True
"store_false"
store百货商店False
"append"
append this option’s argument to a list将此选项的参数附加到列表"append_const"
append a constant value to a list将常量值附加到列表"count"
increment a counter by one计数器加1"callback"
call a specified function调用指定的函数"help"
print a usage message including all options and the documentation for them打印使用信息,包括所有选项及其文档
(If you don’t supply an action, the default is(如果不提供操作,默认值为"store"
."store"
。For this action, you may also supply对于此操作,您还可以提供type
anddest
option attributes; see Standard option actions.)type
和dest
选项属性;请参阅标准选项操作。)
As you can see, most actions involve storing or updating a value somewhere. 正如您所看到的,大多数操作都涉及在某处存储或更新值。optparse
always creates a special object for this, conventionally called 始终为此创建一个特殊的对象,通常称为options
(it happens to be an instance of optparse.Values
). options
(它恰好是optparse.Values
的一个实例)。Option arguments (and various other values) are stored as attributes of this object, according to the 根据dest
(destination) option attribute.dest
(destination
)选项属性,选项参数(以及各种其他值)存储为此对象的属性。
For example, when you call例如,当您拨打
parser.parse_args()
one of the first things optparse
does is create the options
object:optparse
首先要做的事情之一是创建options
对象:
options = Values()
If one of the options in this parser is defined with如果解析器中的选项之一是使用以下内容定义的:
parser.add_option("-f", "--file", action="store", type="string", dest="filename")
and the command-line being parsed includes any of the following:并且正在解析的命令行包括以下任一项:
-ffoo
-f foo
--file=foo
--file foo
then 那么optparse
, on seeing this option, will do the equivalent ofoptparse
在看到该选项时,将执行
options.filename = "foo"
The type
and dest
option attributes are almost as important as action
, but action
is the only one that makes sense for all options.type
和dest
选项属性几乎与action
一样重要,但action
是唯一对所有选项都有意义的属性。
Option attributes选项属性¶
The following option attributes may be passed as keyword arguments to 以下选项属性可以作为关键字参数传递给OptionParser.add_option()
. OptionParser.add_option()
。If you pass an option attribute that is not relevant to a particular option, or fail to pass a required option attribute, 如果您传递的选项属性与特定选项无关,或者未能传递所需的选项属性,optparse
raises OptionError
.optparse
将引发OptionError
。
-
Option.
action
¶ (default:
"store"
)Determines确定在命令行上看到此选项时optparse
’s behaviour when this option is seen on the command line; the available options are documented here.optparse
的行为;此处记录了可用选项。
-
Option.
type
¶ (default:
"string"
)The argument type expected by this option (e.g.,此选项所需的参数类型(例如,"string"
or"int"
); the available option types are documented here."string"
或"int"
);这里记录了可用的选项类型。
-
Option.
dest
¶ (default: derived from option strings)(默认值:源自选项字符串)If the option’s action implies writing or modifying a value somewhere, this tells如果选项的操作意味着在某处写入或修改值,这将告诉optparse
where to write it:dest
names an attribute of theoptions
object thatoptparse
builds as it parses the command line.optparse
将其写入何处:dest
命名optparse
在解析命令行时生成的options对象的属性。
-
Option.
default
¶ The value to use for this option’s destination if the option is not seen on the command line.如果命令行上未显示该选项,则用于该选项的目标的值。See also另请参阅OptionParser.set_defaults()
.OptionParser.set_defaults()
。
-
Option.
nargs
¶ (default: 1)
How many arguments of type看到此选项时应使用多少类型type
should be consumed when this option is seen.type
的参数。If > 1,如果>1,optparse
will store a tuple of values todest
.optparse
将存储一个值元组到dest
。
-
Option.
const
¶ For actions that store a constant value, the constant value to store.对于存储常量值的操作,要存储的常量值。
-
Option.
choices
¶ For options of type对于"choice"
, the list of strings the user may choose from."choice"
类型的选项,用户可以从中选择的字符串列表。
-
Option.
callback
¶ For options with action对于具有操作"callback"
, the callable to call when this option is seen."callback"
的选项,当看到此选项时,将调用该选项。See section Option Callbacks for detail on the arguments passed to the callable.有关传递给可调用对象的参数的详细信息,请参阅选项回调一节。
-
Option.
callback_args
¶ -
Option.
callback_kwargs
¶ Additional positional and keyword arguments to pass to在四个标准回调参数之后传递给callback
after the four standard callback arguments.callback
的其他位置和关键字参数。
-
Option.
help
¶ Help text to print for this option when listing all available options after the user supplies a在用户提供help
option (such as--help
).help
选项(例如--Help
)后列出所有可用选项时,要为此选项打印的帮助文本。If no help text is supplied, the option will be listed without help text.如果未提供帮助文本,则将列出选项而不提供帮助文本。To hide this option, use the special value要隐藏此选项,请使用特殊值optparse.SUPPRESS_HELP
.optparse.SUPPRESS_HELP
。
Standard option actions标准选项操作¶
The various option actions all have slightly different requirements and effects. 各种选项操作的要求和效果略有不同。Most actions have several relevant option attributes which you may specify to guide 大多数操作都有几个相关的选项属性,您可以指定这些属性来指导optparse
’s behaviour; a few have required attributes, which you must specify for any option using that action.optparse
的行为;其中一些具有必需的属性,您必须为使用该操作的任何选项指定这些属性。
"store"
[relevant:type
,dest
,nargs
,choices
]The option must be followed by an argument, which is converted to a value according to选项后面必须跟一个参数,该参数根据type
and stored indest
.type
转换为值并存储在dest
中。If如果nargs
> 1, multiple arguments will be consumed from the command line; all will be converted according totype
and stored todest
as a tuple.nargs
>1,将从命令行使用多个参数;所有这些都将根据type
进行转换,并作为元组存储到dest
。See the Standard option types section.请参见标准选项类型部分。If如果提供了choices
is supplied (a list or tuple of strings), the type defaults to"choice"
.choices
(字符串的列表或元组),则类型默认为"choice"
。If如果未提供type
is not supplied, it defaults to"string"
.type
,则默认为"string"
。If如果未提供dest
is not supplied,optparse
derives a destination from the first long option string (e.g.,--foo-bar
impliesfoo_bar
).dest
,optparse
将从第一个长选项字符串(例如,--foo-bar
表示foo_bar
)中导出目标。If there are no long option strings,如果没有长选项字符串,optparse
derives a destination from the first short option string (e.g.,-f
impliesf
).optparse
将从第一个短选项字符串中派生一个目标(例如,-f
表示f
)。Example:例子:parser.add_option("-f")
parser.add_option("-p", type="float", nargs=3, dest="point")As it parses the command line当它解析命令行时-f foo.txt -p 1 -3.5 4 -fbar.txt
optparse
will set将设置options.f = "foo.txt"
options.point = (1.0, -3.5, 4.0)
options.f = "bar.txt""store_const"
[required:const
; relevant:dest
]The valueconst
is stored indest
.const
值存储在dest
中。Example:例子: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")If如果看到--noisy
is seen,optparse
will set--noisy
,optparse
将设置options.verbose = 2
"store_true"
[relevant:dest
]A special case of存储"store_const"
that storesTrue
todest
.True
到dest
的"store_const"
的特殊情况。"store_false"
[relevant:dest
]Like类似"store_true"
, but storesFalse
."store_true"
,但存储False
。Example:例子:parser.add_option("--clobber", action="store_true", dest="clobber")
parser.add_option("--no-clobber", action="store_false", dest="clobber")"append"
[relevant:type
,dest
,nargs
,choices
]The option must be followed by an argument, which is appended to the list in选项后面必须跟一个参数,该参数附加到dest
.dest
中的列表。If no default value for如果未提供dest
is supplied, an empty list is automatically created whenoptparse
first encounters this option on the command-line.dest
的默认值,则当optparse
首次在命令行上遇到此选项时,将自动创建一个空列表。If如果nargs
> 1, multiple arguments are consumed, and a tuple of lengthnargs
is appended todest
.nargs
>1,将使用多个参数,并且长度为nargs
的元组将附加到dest
。The defaults fortype
anddest
are the same as for the"store"
action.type
和dest
的默认值与"store"
操作的默认值相同。Example:
parser.add_option("-t", "--tracks", action="append", type="int")
If如果在命令行上看到-t3
is seen on the command-line,optparse
does the equivalent of:-t3
,optparse
将执行以下操作:options.tracks = []
options.tracks.append(int("3"))If, a little later on,如果稍后看到--tracks=4
is seen, it does:--tracks=4
,则会:options.tracks.append(int("4"))
Theappend
action calls theappend
method on the current value of the option.append
操作对选项的当前值调用append
方法。This means that any default value specified must have an这意味着任何指定的默认值都必须有一个append
method.append
方法。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:这也意味着,如果默认值为非空,则默认元素将出现在选项的解析值中,命令行中的任何值都将附加在这些默认值之后:>>> 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"
[required:const
; relevant:dest
]Like类似于"store_const"
, but the valueconst
is appended todest
; as with"append"
,dest
defaults toNone
, and an empty list is automatically created the first time the option is encountered."store_const"
,但值const
附加到dest
;与"append"
一样,dest
默认为None
,并且在第一次遇到选项时会自动创建一个空列表。"count"
[relevant:dest
]Increment the integer stored at递增存储在dest
.dest
的整数。If no default value is supplied,如果未提供默认值,则dest
is set to zero before being incremented the first time.dest
在第一次递增之前设置为零。Example:
parser.add_option("-v", action="count", dest="verbosity")
The first time第一次在命令行上看到-v
is seen on the command line,optparse
does the equivalent of:-v
时,optparse
执行的操作相当于:options.verbosity = 0
options.verbosity += 1Every subsequent occurrence of随后每次出现-v
results in-v
都会导致options.verbosity += 1
"callback"
[required:callback
; relevant:type
,nargs
,callback_args
,callback_kwargs
]Call the function specified by调用callback
, which is called ascallback
指定的函数,该函数被调用为func(option, opt_str, value, parser, *args, **kwargs)
See section Option Callbacks for more detail.有关详细信息,请参阅选项回调一节。"help"
Prints a complete help message for all the options in the current option parser.打印当前选项分析器中所有选项的完整帮助消息。The help message is constructed from the帮助消息由传递给OptionParser构造函数的usage
string passed to OptionParser’s constructor and thehelp
string passed to every option.usage
字符串和传递给每个选项的help
字符串构成。If no如果没有为选项提供help
string is supplied for an option, it will still be listed in the help message.help
字符串,则它仍将列在帮助消息中。To omit an option entirely, use the special value要完全省略选项,请使用特殊值optparse.SUPPRESS_HELP
.optparse.SUPPRESS_HELP
。optparse
automatically adds ahelp
option to all OptionParsers, so you do not normally need to create one.optparse
会自动向所有OptionParser添加一个help
选项,因此通常不需要创建一个。Example:例子: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)If如果optparse
sees either-h
or--help
on the command line, it will print something like the following help message to stdout (assumingsys.argv[0]
is"foo.py"
):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 fromAfter printing the help message,打印帮助消息后,optparse
terminates your process withsys.exit(0)
.optparse
使用sys.exit(0)
终止进程。"version"
Prints the version number supplied to the OptionParser to stdout and exits.将提供给OptionParser的版本号打印到stdout并退出。The version number is actually formatted and printed by the版本号实际上是由OptionParser的print_version()
method of OptionParser.print_version()
方法格式化和打印的。Generally only relevant if the通常仅当version
argument is supplied to the OptionParser constructor.version
参数提供给OptionParser构造函数时才相关。As with与help
options, you will rarely createversion
options, sinceoptparse
automatically adds them when needed.help
选项一样,您很少创建version
选项,因为optparse
会在需要时自动添加它们。
Standard option types标准选项类型¶
optparse
has five built-in option types: "string"
, "int"
, "choice"
, "float"
and "complex"
. optparse
有五种内置选项类型:"string"
、"int"
、"choice"
、"float"
和"complex"
。If you need to add new option types, see section Extending optparse.如果需要添加新的选项类型,请参阅扩展optparse一节。
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 整数参数(类型"int"
) are parsed as follows:"int"
)的解析如下:
if the number starts with如果数字以0x
, it is parsed as a hexadecimal number0x
开头,则解析为十六进制数字if the number starts with如果数字以0
, it is parsed as an octal number0
开头,则解析为八进制数if the number starts with如果数字以0b
, it is parsed as a binary number0b
开头,则解析为二进制数字otherwise, the number is parsed as a decimal number否则,该数字将被解析为十进制数字
The conversion is done by calling 转换通过使用适当的基(2、8、10或16)调用int()
with the appropriate base (2, 8, 10, or 16). int()
来完成。If this fails, so will 如果失败,optparse
, although with a more useful error message.optparse
也会失败,尽管会显示一条更有用的错误消息。
"float"
and "complex"
option arguments are converted directly with float()
and complex()
, with similar error-handling."float"
和"complex"
选项参数直接使用float()
和complex()
转换,具有类似的错误处理。
"choice"
options are a subtype of "string"
options. "choice"
选项是"string"
选项的子类型。The choices
option attribute (a sequence of strings) defines the set of allowed option arguments. choices
选项属性(字符串序列)定义了一组允许的选项参数。optparse.check_choice()
compares user-supplied option arguments against this master list and raises 将用户提供的选项参数与此主列表进行比较,如果给定的字符串无效,则引发OptionValueError
if an invalid string is given.OptionValueError
。
Parsing arguments分析参数¶
The whole point of creating and populating an OptionParser is to call its 创建和填充OptionParser的关键是调用其parse_args()
method:parse_args()
方法:
(options, args) = parser.parse_args(args=None, values=None)
where the input parameters are其中输入参数为
args
the list of arguments to process (default:要处理的参数列表(默认值:sys.argv[1:]
)sys.argv[1:]
)values
an用于存储选项参数的optparse.Values
object to store option arguments in (default: a new instance ofValues
) – if you give an existing object, the option defaults will not be initialized on itoptparse.Values
对象(默认值:Values
的新实例)如果给定现有对象,则不会对其初始化选项默认值
and the return values are返回值为
options
the same object that was passed in as作为values
, or the optparse.Values instance created byoptparse
values
传入的同一对象,或optparse
创建的optparse.Values
实例args
the leftover positional arguments after all options have been processed处理完所有选项后剩余的位置参数
The most common usage is to supply neither keyword argument. 最常见的用法是既不提供关键字参数。If you supply 如果您提供值,它将通过重复的values
, it will be modified with repeated setattr()
calls (roughly one for every option argument stored to an option destination) and returned by parse_args()
.setattr()
调用进行修改(对于存储到选项目标的每个选项参数大约一个),并由parse_args()
返回。
If 如果parse_args()
encounters any errors in the argument list, it calls the OptionParser’s error()
method with an appropriate end-user error message. parse_args()
在参数列表中遇到任何错误,它将调用OptionParser的error()
方法并显示相应的最终用户错误消息。This ultimately terminates your process with an exit status of 2 (the traditional Unix exit status for command-line errors).这最终会终止进程,退出状态为2(传统的Unix退出状态用于命令行错误)。
Querying and manipulating your option parser查询和操作选项解析器¶
The default behavior of the option parser can be customized slightly, and you can also poke around your option parser and see what’s there. OptionParser provides several methods to help you out:选项解析器的默认行为可以稍微定制,您也可以在选项解析器周围查看有哪些内容。OptionParser提供了几种方法来帮助您:
-
OptionParser.
disable_interspersed_args
()¶ Set parsing to stop on the first non-option.将解析设置为在第一个非选项上停止。For example, if例如,如果-a
and-b
are both simple options that take no arguments,optparse
normally accepts this syntax:-a
和-b
都是不带参数的简单选项,optparse
通常接受以下语法:prog -a arg1 -b arg2
and treats it as equivalent to并将其视为等同于prog -a -b arg1 arg2
To disable this feature, call要禁用此功能,请调用disable_interspersed_args()
.disable_interspersed_args()
。This restores traditional Unix syntax, where option parsing stops with the first non-option argument.这恢复了传统的Unix语法,其中选项解析以第一个非选项参数停止。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.例如,每个命令可能有一组不同的选项。
-
OptionParser.
enable_interspersed_args
()¶ Set parsing to not stop on the first non-option, allowing interspersing switches with command arguments.将解析设置为不在第一个非选项上停止,允许使用命令参数来分散开关。This is the default behavior.这是默认行为。
-
OptionParser.
get_option
(opt_str)¶ Returns the Option instance with the option string opt_str, or返回选项字符串为opt_str的Option实例,如果没有选项具有该选项字符串,则返回None
if no options have that option string.None
。
-
OptionParser.
has_option
(opt_str)¶ Return如果OptionParser具有带有选项字符串opt_str(例如True
if the OptionParser has an option with option string opt_str (e.g.,-q
or--verbose
).-q
或--verbose
)的选项,则返回True
。
-
OptionParser.
remove_option
(opt_str)¶ If the如果OptionParser
has an option corresponding to opt_str, that option is removed.OptionParser
具有与opt_str对应的选项,则该选项将被删除。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如果opt_str未出现在属于此OptionParser
, raisesValueError
.OptionParser
的任何选项中,则引发ValueError
。
Conflicts between options选项之间的冲突¶
If you’re not careful, it’s easy to define options with conflicting option strings:如果不小心,很容易用冲突的选项字符串定义选项:
parser.add_option("-n", "--dry-run", ...)
...
parser.add_option("-n", "--noisy", ...)
(This is particularly true if you’ve defined your own OptionParser subclass with some standard options.)(如果您已经用一些标准选项定义了自己的OptionParser子类,则尤其如此。)
Every time you add an option, 每次添加选项时,optparse
checks for conflicts with existing options. optparse
都会检查与现有选项的冲突。If it finds any, it invokes the current conflict-handling mechanism. 如果发现任何冲突,它将调用当前的冲突处理机制。You can set the conflict-handling mechanism either in the constructor:您可以在构造函数中设置冲突处理机制:
parser = OptionParser(..., conflict_handler=handler)
or with a separate call:或单独呼叫:
parser.set_conflict_handler(handler)
The available conflict handlers are:可用的冲突处理程序包括:
"error"
(default)
assume option conflicts are a programming error and raise假设选项冲突是编程错误,并引发OptionConflictError
OptionConflictError
"resolve"
resolve option conflicts intelligently (see below)智能解决选项冲突(见下文)
As an example, let’s define an 例如,让我们定义一个OptionParser
that resolves conflicts intelligently and add conflicting options to it:OptionParser
,它智能地解决冲突并向其中添加冲突选项:
parser = OptionParser(conflict_handler="resolve")
parser.add_option("-n", "--dry-run", ..., help="do no harm")
parser.add_option("-n", "--noisy", ..., help="be noisy")
At this point, 此时,optparse
detects that a previously-added option is already using the -n
option string. optparse
检测到先前添加的选项已经在使用-n
选项字符串。Since 由于conflict_handler
is "resolve"
, it resolves the situation by removing -n
from the earlier option’s list of option strings. conflict_handler
是"resolve"
,它通过从前面选项的选项字符串列表中删除-n
来解决此问题。Now 现在,--dry-run
is the only way for the user to activate that option. --dry-run
是用户激活该选项的唯一方法。If the user asks for help, the help message will reflect that:如果用户请求帮助,帮助消息将反映:
Options:
--dry-run do no harm
...
-n, --noisy be noisy
It’s possible to whittle away the option strings for a previously-added option until there are none left, and the user has no way of invoking that option from the command-line. 可以删除之前添加的选项的选项字符串,直到没有剩余的选项,并且用户无法从命令行调用该选项。In that case, 在这种情况下,optparse
removes that option completely, so it doesn’t show up in help text or anywhere else. Carrying on with our existing OptionParser:optparse
会完全删除该选项,因此它不会显示在帮助文本或其他任何地方。继续使用我们现有的OptionParser:
parser.add_option("--dry-run", ..., help="new dry-run option")
At this point, the original 此时,原始的-n
/--dry-run
option is no longer accessible, so optparse
removes it, leaving this help text:-n
/--dry-run
选项不再可访问,因此optparse
将其删除,留下以下帮助文本:
Options:
...
-n, --noisy be noisy
--dry-run new dry-run option
Cleanup¶
OptionParser instances have several cyclic references. OptionParser实例有几个循环引用。This should not be a problem for Python’s garbage collector, but you may wish to break the cyclic references explicitly by calling 对于Python的垃圾收集器来说,这应该不是问题,但您可能希望在完成后通过在OptionParser上调用destroy()
on your OptionParser once you are done with it. destroy()
来显式中断循环引用。This is particularly useful in long-running applications where large object graphs are reachable from your OptionParser.这在长时间运行的应用程序中特别有用,在这些应用程序中,可以从OptionParser访问大型对象图。
Other methods其他方法¶
OptionParser supports several other public methods:OptionParser支持其他几种公共方法:
-
OptionParser.
set_usage
(usage)¶ Set the usage string according to the rules described above for the根据上面为usage
constructor keyword argument.usage
构造函数关键字参数描述的规则设置usage
字符串。Passing传递None
sets the default usage string; useoptparse.SUPPRESS_USAGE
to suppress a usage message.None
设置默认用法字符串;使用optparse.SUPPRESS_USAGE
抑制使用消息。
-
OptionParser.
print_usage
(file=None)¶ Print the usage message for the current program (将当前程序的使用信息(self.usage
) to file (default stdout).self.usage
)打印到文件(默认stdout)。Any occurrence of the string在%prog
inself.usage
is replaced with the name of the current program.self.usage
中出现的字符串%prog
将替换为当前程序的名称。Does nothing if如果self.usage
is empty or not defined.self.usage
为空或未定义,则不执行任何操作。
-
OptionParser.
get_usage
()¶ Same as与print_usage()
but returns the usage string instead of printing it.print_usage()
相同,但返回用法字符串而不是打印。
-
OptionParser.
set_defaults
(dest=value, ...)¶ Set default values for several option destinations at once.同时为多个选项目标设置默认值。Using使用set_defaults()
is the preferred way to set default values for options, since multiple options can share the same destination.set_defaults()
是设置选项默认值的首选方法,因为多个选项可以共享同一目标。For example, if several “mode” options all set the same destination, any one of them can set the default, and the last one wins:例如,如果多个“模式”选项都设置了相同的目的地,则其中任何一个选项都可以设置默认值,最后一个选项获胜: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 settingTo avoid this confusion, use要避免这种混淆,请使用set_defaults()
: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")
Option Callbacks选项回调¶
When 当optparse
’s built-in actions and types aren’t quite enough for your needs, you have two choices: extend optparse
or define a callback option. optparse
的内置操作和类型不足以满足您的需要时,您有两种选择:扩展optparse
或定义回调选项。Extending 扩展optparse
is more general, but overkill for a lot of simple cases. optparse
更为通用,但对于许多简单的情况来说,这是过度的。Quite often a simple callback is all you need.通常只需要一个简单的回调。
There are two steps to defining a callback option:定义回调选项有两个步骤:
define the option itself using the使用"callback"
action"callback"
操作定义选项本身write the callback; this is a function (or method) that takes at least four arguments, as described below写入回调;这是一个至少接受四个参数的函数(或方法),如下所述
Defining a callback option定义回调选项¶
As always, the easiest way to define a callback option is by using the 一如既往,定义回调选项的最简单方法是使用OptionParser.add_option()
method. OptionParser.add_option()
方法。Apart from 除action
, the only option attribute you must specify is callback
, the function to call:action
之外,您必须指定的唯一选项属性是callback
,即要调用的函数:
parser.add_option("-c", action="callback", callback=my_callback)
callback
is a function (or other callable object), so you must have already defined my_callback()
when you create this callback option. callback
是一个函数(或其他可调用对象),因此在创建此回调选项时,必须已经定义了my_callback()
。In this simple case, 在这个简单的例子中,optparse
doesn’t even know if -c
takes any arguments, which usually means that the option takes no arguments—the mere presence of -c
on the command-line is all it needs to know. optparse
甚至不知道-c
是否接受任何参数,这通常意味着该选项不接受任何参数——只需要知道命令行上存在-c
即可。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.这就是编写回调变得棘手的地方;这将在本节稍后介绍。
optparse
always passes four particular arguments to your callback, and it will only pass additional arguments if you specify them via 始终向回调传递四个特定的参数,并且只有当您通过callback_args
and callback_kwargs
. callback_args
和callback_kwargs
指定它们时,它才会传递额外的参数。Thus, the minimal callback function signature is:因此,最小回调函数签名为:
def my_callback(option, opt, value, parser):
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:定义回调选项时,可以提供其他几个选项属性:
type
has its usual meaning: as with the有其通常的含义:与"store"
or"append"
actions, it instructsoptparse
to consume one argument and convert it totype
."store"
或"append"
操作一样,它指示optparse
使用一个参数并将其转换为type
。Rather than storing the converted value(s) anywhere, though,但是,optparse
passes it to your callback function.optparse
不会将转换后的值存储在任何地方,而是将其传递给回调函数。nargs
also has its usual meaning: if it is supplied and > 1,也有其通常的含义:如果提供了它并且>1,optparse
will consumenargs
arguments, each of which must be convertible totype
.optparse
将使用nargs
参数,每个参数都必须可转换为type
。It then passes a tuple of converted values to your callback.然后,它将转换值的元组传递给回调。callback_args
a tuple of extra positional arguments to pass to the callback要传递给回调的额外位置参数的元组callback_kwargs
a dictionary of extra keyword arguments to pass to the callback要传递给回调的额外关键字参数的字典
How callbacks are called回调的调用方式¶
All callbacks are called as follows:所有回调调用如下:
func(option, opt_str, value, parser, *args, **kwargs)
where其中
option
is the Option instance that’s calling the callback是调用回调的Option实例opt_str
is the option string seen on the command-line that’s triggering the callback.是在命令行上看到的触发回调的选项字符串。(If an abbreviated long option was used,(如果使用了缩写的long选项,opt_str
will be the full, canonical option string—e.g. if the user puts--foo
on the command-line as an abbreviation for--foobar
, thenopt_str
will be"--foobar"
.)opt_str
将是完整的规范选项字符串。例如,如果用户将--foo
作为--foobar
的缩写放在命令行上,则opt_str
为"--foobar"
。)value
is the argument to this option seen on the command-line.是命令行上显示的此选项的参数。optparse
will only expect an argument iftype
is set; the type ofvalue
will be the type implied by the option’s type.optparse
仅在设置了type
时才需要参数;value
的类型将是选项类型所隐含的类型。If如果此选项的type
for this option isNone
(no argument expected), thenvalue
will beNone
.type
为None
(不需要参数),则值将为None
。If如果nargs
> 1,value
will be a tuple of values of the appropriate type.nargs
>1,则value
将是一个适当类型的值元组。parser
is the OptionParser instance driving the whole thing, mainly useful because you can access some other interesting data through its instance attributes:是驱动整个事情的OptionParser实例,主要是因为您可以通过它的实例属性访问一些其他有趣的数据:parser.largs
the current list of leftover arguments, ie. arguments that have been consumed but are neither options nor option arguments.剩余参数的当前列表,即已使用但既不是选项也不是选项参数的参数。Feel free to modify可以随意修改parser.largs
, e.g. by adding more arguments to it.parser.largs
,例如向其添加更多参数。(This list will become(此列表将变为args
, the second return value ofparse_args()
.)args
,parse_args()
的第二个返回值。)parser.rargs
the current list of remaining arguments, ie. with剩余参数的当前列表,即删除了opt_str
andvalue
(if applicable) removed, and only the arguments following them still there.opt_str
和value
(如果适用),只有后面的参数仍然存在。Feel free to modify可以随意修改parser.rargs
, e.g. by consuming more arguments.parser.rargs
,例如使用更多参数。parser.values
the object where option values are by default stored (an instance of optparse.OptionValues).默认存储选项值的对象(optparseOptionValues的实例)。This lets callbacks use the same mechanism as the rest of这使得回调可以使用与optparse
for storing option values; you don’t need to mess around with globals or closures.optparse
其余部分相同的机制来存储选项值;你不需要在全局变量或闭包上乱来。You can also access or modify the value(s) of any options already encountered on the command-line.您还可以访问或修改命令行上已遇到的任何选项的值。
args
is a tuple of arbitrary positional arguments supplied via the是通过callback_args
option attribute.callback_args
选项属性提供的任意位置参数的元组。kwargs
is a dictionary of arbitrary keyword arguments supplied via是通过callback_kwargs
.callback_kwargs
提供的任意关键字参数的字典。
Raising errors in a callback在回调中引发错误¶
The callback function should raise 如果选项或其参数有任何问题,回调函数应引发OptionValueError
if there are any problems with the option or its argument(s). OptionValueError
。optparse
catches this and terminates the program, printing the error message you supply to stderr. 捕获此错误并终止程序,打印您提供给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.否则,用户将很难弄清楚自己做错了什么。
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:下面是一个回调选项的示例,该选项不带参数,只记录看到该选项:
def record_foo_seen(option, opt_str, value, parser):
parser.values.saw_foo = True
parser.add_option("--foo", action="callback", callback=record_foo_seen)
Of course, you could do that with the 当然,您可以使用"store_true"
action."store_true"
操作来实现这一点。
Callback example 2: check option order回调示例2:检查选项顺序¶
Here’s a slightly more interesting example: record the fact that 这里有一个稍微有趣一点的例子:记录看到-a
is seen, but blow up if it comes after -b
in the command-line.-a
的事实,但如果命令行中的-b
后面出现-a
,则会爆炸。
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")
Callback example 3: check option order (generalized)回调示例3:检查选项顺序(通用)¶
If you want to re-use this callback for several similar options (set a flag, but blow up if 如果您想将此回调用于几个类似的选项(设置一个标志,但如果已经看到-b
has already been seen), it needs a bit of work: the error message and the flag that it sets must be generalized.-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')
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:例如,如果你有一些选项,在满月时不应该调用,那么你所要做的就是:
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")
(The definition of (is_moon_full()
is left as an exercise for the reader.)is_mon_full()
的定义留给读者作为练习。)
Callback example 5: fixed arguments回调示例5:固定参数¶
Things get slightly more interesting when you define callback options that take a fixed number of arguments. 当您定义接受固定数量参数的回调选项时,事情会稍微有趣一些。Specifying that a callback option takes arguments is similar to defining a 指定回调选项采用参数类似于定义"store"
or "append"
option: if you define type
, then the option takes one argument that must be convertible to that type; if you further define nargs
, then the option takes nargs
arguments."store"
或"append"
选项:如果定义type
,则该选项采用一个必须转换为该类型的参数;如果进一步定义nargs
,则该选项采用nargs
参数。
Here’s an example that just emulates the standard 下面是一个模拟标准"store"
action:"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")
Note that 注意,optparse
takes care of consuming 3 arguments and converting them to integers for you; all you have to do is store them. optparse
负责使用3个参数并将它们转换为整数;你所要做的就是储存它们。(Or whatever; obviously you don’t need a callback for this example.)(或者其他;显然,本例不需要回调。)
Callback example 6: variable arguments回调示例6:变量参数¶
Things get hairy when you want an option to take a variable number of arguments. 当你想要一个选项来接受可变数量的参数时,事情就会变得复杂起来。For this case, you must write a callback, as 在这种情况下,必须编写回调,因为optparse
doesn’t provide any built-in capabilities for it. optparse
不提供任何内置功能。And you have to deal with certain intricacies of conventional Unix command-line parsing that 您必须处理optparse
normally handles for you. optparse
通常为您处理的传统Unix命令行解析的某些复杂问题。In particular, callbacks should implement the conventional rules for bare 特别是,回调应该实现裸参数--
and -
arguments:--
和-
的常规规则:
either--
or-
can be option arguments--
或-
可以是选项参数bare
--
(if not the argument to some option): halt command-line processing and discard the(如果不是某个选项的参数):停止命令行处理并放弃--
--
bare
-
(if not the argument to some option): halt command-line processing but keep the(如果不是某个选项的参数):停止命令行处理,但保留-
(append it toparser.largs
)-
(将其附加到parser.largs
)
If you want an option that takes a variable number of arguments, there are 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 您选择的具体实现将基于您愿意为应用程序做出哪些权衡(这就是optparse
doesn’t support this sort of thing directly).optparse
不直接支持这类事情的原因)。
Nevertheless, here’s a stab at a callback for an option with variable arguments:然而,这里有一个带有变量参数的选项回调:
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)
Extending 扩展optparse
¶
Since the two major controlling factors in how 由于optparse
interprets 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.optparse
解释命令行选项的两个主要控制因素是每个选项的操作和类型,因此最可能的扩展方向是添加新操作和新类型。
Adding new types添加新类型¶
To add new types, you need to define your own subclass of 要添加新类型,需要定义optparse
’s Option
class. optparse
的Option
类的自己的子类。This class has a couple of attributes that define 这个类有两个定义optparse
’s types: TYPES
and TYPE_CHECKER
.optparse
类型的属性:TYPES
和TYPE_CHECKER
。
-
Option.
TYPES
¶ A tuple of type names; in your subclass, simply define a new tuple类型名称的元组;在子类中,只需定义一个基于标准元组的新元组TYPES
that builds on the standard one.TYPES
。
-
Option.
TYPE_CHECKER
¶ A dictionary mapping type names to type-checking functions.将类型名称映射到类型检查函数的字典。A type-checking function has the following signature:类型检查函数具有以下签名:def check_mytype(option, opt, value)
where其中option
is anOption
instance,opt
is an option string (e.g.,-f
), andvalue
is the string from the command line that must be checked and converted to your desired type.option
是Option
实例,opt
是选项字符串(例如-f
),value
是命令行中必须检查并转换为所需类型的字符串。check_mytype()
should return an object of the hypothetical type应该返回假设类型mytype
.mytype的
对象。The value returned by a type-checking function will wind up in the OptionValues instance returned by类型检查函数返回的值将在OptionParser.parse_args()
, or be passed to a callback as thevalue
parameter.OptionParser.parse_args()
返回的OptionValues实例中结束,或作为value
参数传递给回调。Your type-checking function should raise如果类型检查函数遇到任何问题,它应该引发OptionValueError
if it encounters any problems.OptionValueError
。OptionValueError
takes a single string argument, which is passed as-is to获取一个字符串参数,该参数按原样传递给OptionParser
’serror()
method, which in turn prepends the program name and the string"error:"
and prints everything to stderr before terminating the process.OptionParser
的error()
方法,该方法依次在程序名和字符串"error:"
前面加上前缀,并在终止进程之前将所有内容打印到stderr。
Here’s a silly example that demonstrates adding a 这里有一个愚蠢的例子,它演示了在命令行上添加一个"complex"
option type to parse Python-style complex numbers on the command line. "complex"
选项类型来解析Python风格的复数。(This is even sillier than it used to be, because (这比以前更加愚蠢,因为optparse
1.3 added built-in support for complex numbers, but never mind.)optparse
1.3增加了对复数的内置支持,但没关系。)
First, the necessary imports:首先,必要的导入:
from copy import copy
from optparse import Option, OptionValueError
You need to define your type-checker first, since it’s referred to later (in the 您需要首先定义类型检查器,因为稍后会引用它(在Option子类的TYPE_CHECKER
class attribute of your Option subclass):TYPE_CHECKER
类属性中):
def check_complex(option, opt, value):
try:
return complex(value)
except ValueError:
raise OptionValueError(
"option %s: invalid complex value: %r" % (opt, value))
Finally, the Option subclass:最后,Option子类:
class MyOption (Option):
TYPES = Option.TYPES + ("complex",)
TYPE_CHECKER = copy(Option.TYPE_CHECKER)
TYPE_CHECKER["complex"] = check_complex
(If we didn’t make a (如果我们没有copy()
of Option.TYPE_CHECKER
, we would end up modifying the TYPE_CHECKER
attribute of optparse
’s Option class. Option.TYPE_CHECKER
的copy()
,我们最终会修改optparse
的Option类的TYPE_CHECKER
属性。This being Python, nothing stops you from doing that except good manners and common sense.)这是Python,除了礼貌和常识,没有什么能阻止你这么做。)
That’s it! Now you can write a script that uses the new option type just like any other 就是这样!现在,您可以编写一个使用新选项类型的脚本,就像其他基于optparse
-based script, except you have to instruct your OptionParser to use MyOption instead of Option:optparse
的脚本一样,只需要指示OptionParser使用MyOption而不是option:
parser = OptionParser(option_class=MyOption)
parser.add_option("-c", type="complex")
Alternately, you can build your own option list and pass it to OptionParser; if you don’t use 或者,您可以构建自己的选项列表并将其传递给OptionParser;如果不以上述方式使用add_option()
in the above way, you don’t need to tell OptionParser which option class to use:add_option()
,则不需要告诉OptionParser要使用哪个选项类:
option_list = [MyOption("-c", action="store", type="complex", dest="c")]
parser = OptionParser(option_list=option_list)
Adding new actions添加新操作¶
Adding new actions is a bit trickier, because you have to understand that 添加新操作有点棘手,因为您必须了解optparse
has a couple of classifications for actions:optparse
对操作有两种分类:
- “store” actions
actions that result in导致optparse
storing a value to an attribute of the current OptionValues instance; these options require adest
attribute to be supplied to the Option constructor.optparse
将值存储到当前OptionValues实例的属性的操作;这些选项需要向Option构造函数提供dest
属性。- “typed” 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这些选项需要type
attribute to the Option constructor.type
构造函数的类型属性。
These are overlapping sets: some default “store” actions are 这些是重叠的集合:一些默认的"store"
, "store_const"
, "append"
, and "count"
, while the default “typed” actions are "store"
, "append"
, and "callback"
."store"
操作是"store"
、"store_const"
、"append"
和"count"
,而默认的“typed”操作是"store"
、"append"
和"callback"
。
When you add an action, you need to categorize it by listing it in at least one of the following class attributes of Option (all are lists of strings):添加操作时,需要通过在Option的以下至少一个类属性中列出它来对其进行分类(都是字符串列表):
-
Option.
ACTIONS
¶ All actions must be listed in ACTIONS.所有行动必须列在行动中。
-
Option.
STORE_ACTIONS
¶ “store” actions are additionally listed here.此处还列出了“存储”操作。
-
Option.
TYPED_ACTIONS
¶ “typed” actions are additionally listed here.此处还列出了“类型化”操作。
-
Option.
ALWAYS_TYPED_ACTIONS
¶ 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这样做的唯一效果是optparse
assigns the default type,"string"
, to options with no explicit type whose action is listed inALWAYS_TYPED_ACTIONS
.optparse
将默认类型"string"
分配给没有显式类型的选项,这些选项的操作在ALWAYS_TYPED_ACTIONS
中列出。
In order to actually implement your new action, you must override Option’s 为了实际实现新动作,必须重写Option的take_action()
method and add a case that recognizes your action.take_action()
方法,并添加一个识别动作的case。
For example, let’s add an 例如,让我们添加一个"extend"
action. "extend"
操作。This is similar to the standard 这类似于标准的"append"
action, but instead of taking a single value from the command-line and appending it to an existing list, "extend"
will take multiple values in a single comma-delimited string, and extend an existing list with them. "append"
操作,但"extend"
将在单个逗号分隔的字符串中获取多个值,并用它们扩展现有列表,而不是从命令行中获取单个值并将其附加到现有列表。That is, if 也就是说,如果--names
is an "extend"
option of type "string"
, the command line--names
是"string"
类型的"extend"
选项,则命令行
--names=foo,bar --names blah --names ding,dong
would result in a list会产生一个列表
["foo", "bar", "blah", "ding", "dong"]
Again we define a subclass of Option:我们再次定义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)
Features of note:注释的特点:
"extend"
both expects a value on the command-line and stores that value somewhere, so it goes in both两者都希望在命令行上有一个值,并将该值存储在某个位置,因此它同时存在STORE_ACTIONS
andTYPED_ACTIONS
.STORE_ACTIONS
和TYPED_ACTIONS
中。to ensure that为了确保optparse
assigns the default type of"string"
to"extend"
actions, we put the"extend"
action inALWAYS_TYPED_ACTIONS
as well.optparse
将默认类型"string"
分配给"extend"
操作,我们还将"extend"
动作放在ALWAYS_TYPED_ACTIONS
中。MyOption.take_action()
implements just this one new action, and passes control back to只实现这一个新操作,并将控制权传递回标准Option.take_action()
for the standardoptparse
actions.optparse
操作的Option.take_action()
。values
is an instance of the是optparse_parser.Values
class, which provides the very usefulensure_value()
method.optparse_parser.Values
类的一个实例,它提供了非常有用的ensure_value()
方法。ensure_value()
is essentially本质上是带有安全阀的getattr()
with a safety valve; it is called asgetattr()
;用以下方式调用它:values.ensure_value(attr, value)
If the如果attr
attribute ofvalues
doesn’t exist or isNone
, then ensure_value() first sets it tovalue
, and then returns ‘value’.value
的attr
属性不存在或为None
,则ensure_value()
首先将其设置为value
,然后返回‘value’。This is very handy for actions like这对于像"extend"
,"append"
, and"count"
, 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)."extend"
、"append"
和"count"
这样的操作非常方便,所有这些操作都在一个变量中累积数据,并期望该变量是特定类型的(前两个是列表,后一个是整数)。Using使用ensure_value()
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 asNone
andensure_value()
will take care of getting it right when it’s needed.ensure_value()
意味着使用您的操作的脚本不必担心为所讨论的选项目的地设置默认值;他们只需将默认值保留为None
,ensure_value()
将在需要时处理好它。