optparseParser 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将为Falseoptparse 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 sys.argv[0]).其中yourscript的值是在运行时确定的(通常来自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 execl() or execv(). 在命令行上输入的字符串,并由shell传递给execl()execv()In Python, arguments are elements of sys.argv[1:] (sys.argv[0] is the name of the program being executed). 在Python中,参数是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 of sys.argv[1:], or of some other list provided as a substitute for sys.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. -x or -F. 选项有许多不同的语法;传统的Unix语法是连字符(“-”)后跟一个字母,例如-x-FAlso, traditional Unix syntax allows multiple options to be merged into a single argument, e.g. -x -F is equivalent to -xF. 此外,传统的Unix语法允许将多个选项合并为一个参数,例如-x -F等同于-xFThe GNU project introduced -- followed by a series of hyphen-separated words, e.g. --file or --dry-run. GNU项目引入了一系列连字符--分隔的单词,例如--file--dry-runThese 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 by optparse, 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 foo

or included in the same argument:或包含在同一参数中:

-ffoo
--file=foo

Typically, 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完全是另一个选项,我们如何解释-abBecause 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.foobar是位置参数。

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.)主要的例外是findtardd,所有这些都是变异的怪球,因为它们不标准的语法和令人困惑的接口而受到了正确的批评。)

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, then options.file will be the filename supplied by the user, or None 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. 本教程部分仅介绍四个最重要的选项属性:actiontypedest(目标)和helpOf 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支持的其他一些选项类型是intfloatHere’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 -n42 (one argument) is equivalent to -n 42 (two arguments), the code这一次,我们将把option参数与option对齐:由于-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将采用stringCombined 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_barIf 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. 当看到特定选项时,标志选项将变量设置为truefalse是非常常见的。optparse supports them with two separate actions, store_true and store_false. 通过两个单独的操作store_truestore_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. 因为我们没有提供任何默认值,所以它们都设置为NoneThis 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:如果我们希望optparseverbose设置为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 set_defaults() method of OptionParser, which you can call at any time before calling parse_args():指定默认值的更清晰的方法是OptionParser的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 -m/--mode. 这里,“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 sets metavar="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 with str() of the option’s default value. 具有默认值的选项可以在帮助字符串中包含%defaultoptparse将用选项默认值的str()替换它。If an option has no default value (or the default value is None), %default expands to none.如果选项没有默认值(或默认值为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类获得选项组:

classoptparse.OptionGroup(parser, title, description=None)

where

  • parser is the OptionParser instance the group will be inserted in toparser是组将插入其中的OptionParser实例

  • 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 OptionGroup to which the short or long option string opt_str (e.g. '-o' or '--option') belongs. 返回短或长选项字符串opt_str(例如'-o''--option')所属的OptionGroupIf there’s no such OptionGroup, return None.如果没有这样的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 in self.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如何处理错误

There 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.OptionErrorTypeError)并让程序崩溃。

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实例。

classoptparse.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 to os.path.basename(sys.argv[0]) (or to prog 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 in option_list are added after any options in standard_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 for usage.子字符串%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 new IndentedHelpFormatter)

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.为此提供了两个具体的类:IndendedHelpFormatterTitledHelpFormater

add_help_option (default: True)

If true, optparse will add a help option (with option strings -h and --help) to the parser.如果为trueoptparse将向解析器添加一个帮助选项(带有选项字符串-h--help)。

prog

The string to use when expanding %prog in usage and version instead of os.path.basename(sys.argv[0]).usageversion中展开%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 make_option())传递给它一个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. -f and --file. 每个Option实例代表一组同义的命令行选项字符串,例如-f--fileYou 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实例的规范方法是使用OptionParseradd_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 an OptionError 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 and dest option attributes; see Standard option actions.)对于此操作,您还可以提供typedest选项属性;请参阅标准选项操作。)

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.根据destdestination)选项属性,选项参数(以及各种其他值)存储为此对象的属性。

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 of那么optparse在看到该选项时,将执行

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.typedest选项属性几乎与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 the options object that optparse 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, optparse will store a tuple of values to dest.如果>1,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

Option.metavar

(default: derived from option strings)(默认值:源自选项字符串)

Stand-in for the option argument(s) to use when printing help text. 打印帮助文本时要使用的选项参数。See section Tutorial for an example.有关示例,请参阅教程部分。

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 in dest. 选项后面必须跟一个参数,该参数根据type转换为值并存储在dest中。If nargs > 1, multiple arguments will be consumed from the command line; all will be converted according to type and stored to dest as a tuple. 如果nargs>1,将从命令行使用多个参数;所有这些都将根据type进行转换,并作为元组存储到destSee 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 implies foo_bar). 如果未提供destoptparse将从第一个长选项字符串(例如,--foo-bar表示foo_bar)中导出目标。If there are no long option strings, optparse derives a destination from the first short option string (e.g., -f implies f).如果没有长选项字符串,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 value const is stored in dest.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如果看到--noisyoptparse将设置

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

    A special case of "store_const" that stores True to dest.存储Truedest"store_const"的特殊情况。

  • "store_false" [relevant: dest]

    Like "store_true", but stores False.类似"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 when optparse first encounters this option on the command-line. 如果未提供dest的默认值,则当optparse首次在命令行上遇到此选项时,将自动创建一个空列表。If nargs > 1, multiple arguments are consumed, and a tuple of length nargs is appended to dest.如果nargs>1,将使用多个参数,并且长度为nargs的元组将附加到dest

    The defaults for type and dest are the same as for the "store" action.typedest的默认值与"store"操作的默认值相同。

    Example:

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

    If -t3 is seen on the command-line, optparse does the equivalent of:如果在命令行上看到-t3optparse将执行以下操作:

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

    The append action calls the append 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 value const is appended to dest; as with "append", dest defaults to None, 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 += 1

    Every 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 as调用callback指定的函数,该函数被调用为

    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 usage string passed to OptionParser’s constructor and the help string passed to every option.帮助消息由传递给OptionParser构造函数的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 a help 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 (assuming sys.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 from

    After printing the help message, optparse terminates your process with sys.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 print_version() method of OptionParser. 版本号实际上是由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 create version options, since optparse 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 number如果数字以0x开头,则解析为十六进制数字

  • if the number starts with 0, it is parsed as an octal number如果数字以0开头,则解析为八进制数

  • if the number starts with 0b, it is parsed as a binary number如果数字以0b开头,则解析为二进制数字

  • otherwise, the number is parsed as a decimal number否则,该数字将被解析为十进制数字

The conversion is done by calling int() with the appropriate base (2, 8, 10, or 16). 转换通过使用适当的基(2、8、10或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 parse_args() method:创建和填充OptionParser的关键是调用其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 of Values) – if you give an existing object, the option defaults will not be initialized on it用于存储选项参数的optparse.Values对象(默认值:Values的新实例)如果给定现有对象,则不会对其初始化选项默认值

and the return values are返回值为

options

the same object that was passed in as values, or the optparse.Values instance created by optparse作为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 None if no options have that option string.返回选项字符串为opt_str的Option实例,如果没有选项具有该选项字符串,则返回None

OptionParser.has_option(opt_str)

Return True if the OptionParser has an option with option string opt_str (e.g., -q or --verbose).如果OptionParser具有带有选项字符串opt_str(例如-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 OptionParser, raises ValueError.如果opt_str未出现在属于此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 destroy() on your OptionParser once you are done with it. 对于Python的垃圾收集器来说,这应该不是问题,但您可能希望在完成后通过在OptionParser上调用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; use optparse.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 in self.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 setting

To 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_argscallback_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 instructs optparse to consume one argument and convert it to type. 有其通常的含义:与"store""append"操作一样,它指示optparse使用一个参数并将其转换为typeRather 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, optparse will consume nargs arguments, each of which must be convertible to type. 也有其通常的含义:如果提供了它并且>1,optparse将使用nargs参数,每个参数都必须可转换为typeIt 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, 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, then opt_str will be "--foobar".)(如果使用了缩写的long选项,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 if type is set; the type of value will be the type implied by the option’s type. optparse仅在设置了type时才需要参数;value的类型将是选项类型所隐含的类型。If type for this option is None (no argument expected), then value will be None. 如果此选项的typeNone(不需要参数),则值将为NoneIf 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 of parse_args().)(此列表将变为argsparse_args()的第二个返回值。)

parser.rargs

the current list of remaining arguments, ie. with opt_str and value (if applicable) removed, and only the arguments following them still there. 剩余参数的当前列表,即删除了opt_strvalue(如果适用),只有后面的参数仍然存在。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). 如果选项或其参数有任何问题,回调函数应引发OptionValueErroroptparse 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 to parser.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. 要添加新类型,需要定义optparseOption类的自己的子类。This class has a couple of attributes that define optparse’s types: TYPES and TYPE_CHECKER.这个类有两个定义optparse类型的属性:TYPESTYPE_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 an Option instance, opt is an option string (e.g., -f), and value is the string from the command line that must be checked and converted to your desired type. 其中optionOption实例,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 the value parameter.类型检查函数返回的值将在OptionParser.parse_args()返回的OptionValues实例中结束,或作为value参数传递给回调。

Your type-checking function should raise OptionValueError if it encounters any problems. 如果类型检查函数遇到任何问题,它应该引发OptionValueErrorOptionValueError takes a single string argument, which is passed as-is to OptionParser’s error() method, which in turn prepends the program name and the string "error:" and prints everything to stderr before terminating the process.获取一个字符串参数,该参数按原样传递给OptionParsererror()方法,该方法依次在程序名和字符串"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 TYPE_CHECKER class attribute of your Option subclass):您需要首先定义类型检查器,因为稍后会引用它(在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))

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_CHECKERcopy(),我们最终会修改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 add_option() in the above way, you don’t need to tell OptionParser which option class to use:或者,您可以构建自己的选项列表并将其传递给OptionParser;如果不以上述方式使用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 a dest 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 in ALWAYS_TYPED_ACTIONS.这样做的唯一效果是optparse将默认类型"string"分配给没有显式类型的选项,这些选项的操作在ALWAYS_TYPED_ACTIONS中列出。

In order to actually implement your new action, you must override Option’s take_action() method and add a case that recognizes your action.为了实际实现新动作,必须重写Option的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 and TYPED_ACTIONS.两者都希望在命令行上有一个值,并将该值存储在某个位置,因此它同时存在STORE_ACTIONSTYPED_ACTIONS中。

  • to ensure that optparse assigns the default type of "string" to "extend" actions, we put the "extend" action in ALWAYS_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 standard optparse actions.只实现这一个新操作,并将控制权传递回标准optparse操作的Option.take_action()

  • values is an instance of the optparse_parser.Values class, which provides the very useful ensure_value() method. optparse_parser.Values类的一个实例,它提供了非常有用的ensure_value()方法。ensure_value() is essentially getattr() with a safety valve; it is called as本质上是带有安全阀的getattr();用以下方式调用它:

    values.ensure_value(attr, value)

    If the attr attribute of values doesn’t exist or is None, then ensure_value() first sets it to value, and then returns ‘value’. 如果valueattr属性不存在或为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 as None and ensure_value() will take care of getting it right when it’s needed.使用ensure_value()意味着使用您的操作的脚本不必担心为所讨论的选项目的地设置默认值;他们只需将默认值保留为Noneensure_value()将在需要时处理好它。