getoptC-style parser for command line options用于命令行选项的C风格解析器

Source code: Lib/getopt.py

Note

The getopt module is a parser for command line options whose API is designed to be familiar to users of the C getopt() function. getopt模块是一个用于命令行选项的解析器,其API设计为C getopt()函数的用户所熟悉。Users who are unfamiliar with the C getopt() function or who would like to write less code and get better help and error messages should consider using the argparse module instead.不熟悉C getopt()函数或希望编写更少代码并获得更好帮助和错误消息的用户应考虑使用argparse模块。


This module helps scripts to parse the command line arguments in sys.argv. 此模块帮助脚本解析sys.argv中的命令行参数。It supports the same conventions as the Unix getopt() function (including the special meanings of arguments of the form ‘-’ and ‘--‘). 它支持与Unix getopt()函数相同的约定(包括形式为“-”和“--”的参数的特殊含义)。Long options similar to those supported by GNU software may be used as well via an optional third argument.也可以通过可选的第三个参数使用与GNU软件支持的选项类似的长选项。

This module provides two functions and an exception:此模块提供两个功能和一个异常:

getopt.getopt(args, shortopts, longopts=[])

Parses command line options and parameter list. 分析命令行选项和参数列表。args is the argument list to be parsed, without the leading reference to the running program. 要分析的参数列表,不带对运行程序的前导引用。Typically, this means sys.argv[1:]. 通常,这意味着sys.argv[1:]shortopts is the string of option letters that the script wants to recognize, with options that require an argument followed by a colon (':'; i.e., the same format that Unix getopt() uses).是脚本要识别的选项字母字符串,其中的选项需要一个参数后跟冒号(':';即,与Unix getopt()使用的格式相同)。

Note

Unlike GNU getopt(), after a non-option argument, all further arguments are considered also non-options. 与GNU getopt()不同,在非选项参数之后,所有其他参数也被视为非选项。This is similar to the way non-GNU Unix systems work.这类似于非GNU Unix系统的工作方式。

longopts, if specified, must be a list of strings with the names of the long options which should be supported. 如果指定了longopts,则必须是包含应支持的长选项名称的字符串列表。The leading '--' characters should not be included in the option name. 选项名称中不应包含前导'--'字符。Long options which require an argument should be followed by an equal sign ('='). 需要参数的长选项后面应该跟一个等号('=')。Optional arguments are not supported. 不支持可选参数。To accept only long options, shortopts should be an empty string. 要仅接受长选项,shortopts应为空字符串。Long options on the command line can be recognized so long as they provide a prefix of the option name that matches exactly one of the accepted options. 命令行上的长选项可以被识别,只要它们提供了与接受的选项之一完全匹配的选项名称前缀。For example, if longopts is ['foo', 'frob'], the option --fo will match as --foo, but --f will not match uniquely, so GetoptError will be raised.例如,如果longopts['foo', 'frob'],选项--fo将匹配为--foo,但--f将不唯一匹配,因此将引发GetoptError

The return value consists of two elements: the first is a list of (option, value) pairs; the second is the list of program arguments left after the option list was stripped (this is a trailing slice of args). 返回值由两个元素组成:第一个是(option, value))对的列表;第二个是去掉选项列表后剩下的程序参数列表(这是args的尾随部分)。Each option-and-value pair returned has the option as its first element, prefixed with a hyphen for short options (e.g., '-x') or two hyphens for long options (e.g., '--long-option'), and the option argument as its second element, or an empty string if the option has no argument. 返回的每个选项和值对都将选项作为其第一个元素,前缀为短选项的连字符(例如,'-x')或长选项的两个连字符(如,'--long-option'),选项参数作为其第二个元素,如果选项没有参数,则为空字符串。The options occur in the list in the same order in which they were found, thus allowing multiple occurrences. 这些选项在列表中的出现顺序与找到它们的顺序相同,因此允许多次出现。Long and short options may be mixed.长期权和短期权可以混合使用。

getopt.gnu_getopt(args, shortopts, longopts=[])

This function works like getopt(), except that GNU style scanning mode is used by default. 该函数与getopt()类似,只是默认使用GNU风格的扫描模式。This means that option and non-option arguments may be intermixed. 这意味着选项和非选项参数可以混合使用。The getopt() function stops processing options as soon as a non-option argument is encountered.一旦遇到非选项参数,getopt()函数就会停止处理选项。

If the first character of the option string is '+', or if the environment variable POSIXLY_CORRECT is set, then option processing stops as soon as a non-option argument is encountered.如果选项字符串的第一个字符是'+',或者如果设置了环境变量POSIXLY_CORRECT,则一旦遇到非选项参数,选项处理就会停止。

exceptiongetopt.GetoptError

This is raised when an unrecognized option is found in the argument list or when an option requiring an argument is given none. 当在参数列表中找到无法识别的选项时,或者当需要参数的选项被赋予none时,会引发此问题。The argument to the exception is a string indicating the cause of the error. 异常的参数是指示错误原因的字符串。For long options, an argument given to an option which does not require one will also cause this exception to be raised. 对于长选项,给予不需要参数的选项的参数也会导致引发此异常。The attributes msg and opt give the error message and related option; if there is no specific option to which the exception relates, opt is an empty string.属性msgopt给出错误消息和相关选项;如果没有与异常相关的特定选项,则opt为空字符串。

exceptiongetopt.error

Alias for GetoptError; for backward compatibility.GetoptError的别名;用于向后兼容性。

An example using only Unix style options:仅使用Unix样式选项的示例:

>>> import getopt
>>> args = '-a -b -cfoo -d bar a1 a2'.split()
>>> args
['-a', '-b', '-cfoo', '-d', 'bar', 'a1', 'a2']
>>> optlist, args = getopt.getopt(args, 'abc:d:')
>>> optlist
[('-a', ''), ('-b', ''), ('-c', 'foo'), ('-d', 'bar')]
>>> args
['a1', 'a2']

Using long option names is equally easy:使用长选项名同样简单:

>>> s = '--condition=foo --testing --output-file abc.def -x a1 a2'
>>> args = s.split()
>>> args
['--condition=foo', '--testing', '--output-file', 'abc.def', '-x', 'a1', 'a2']
>>> optlist, args = getopt.getopt(args, 'x', [
... 'condition=', 'output-file=', 'testing'])
>>> optlist
[('--condition', 'foo'), ('--testing', ''), ('--output-file', 'abc.def'), ('-x', '')]
>>> args
['a1', 'a2']

In a script, typical usage is something like this:在脚本中,典型用法如下:

import getopt, sys
def main():
try:
opts, args = getopt.getopt(sys.argv[1:], "ho:v", ["help", "output="])
except getopt.GetoptError as err:
# print help information and exit:
print(err) # will print something like "option -a not recognized"
usage()
sys.exit(2)
output = None
verbose = False
for o, a in opts:
if o == "-v":
verbose = True
elif o in ("-h", "--help"):
usage()
sys.exit()
elif o in ("-o", "--output"):
output = a
else:
assert False, "unhandled option"
# ...

if __name__ == "__main__":
main()

Note that an equivalent command line interface could be produced with less code and more informative help and error messages by using the argparse module:请注意,通过使用argparse模块,可以用更少的代码和更多信息性的帮助和错误消息生成等效的命令行界面:

import argparse
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('-o', '--output')
parser.add_argument('-v', dest='verbose', action='store_true')
args = parser.parse_args()
# ... do something with args.output ...
# ... do something with args.verbose ..

See also

Module argparse

Alternative command line option and argument parsing library.备选命令行选项和参数解析库。