getopt --- C 风格的命令行选项解析器

源代码: Lib/getopt.py

备注

This module is considered feature complete. A more declarative and extensible alternative to this API is provided in the optparse module. Further functional enhancements for command line parameter processing are provided either as third party modules on PyPI, or else as features in the argparse module.


此模块可协助脚本解析 sys.argv 中的命令行参数。 它支持与 Unix getopt() 函数相同的惯例 (包括形式为 '-' 和 '--' 的参数的特殊含义)。 也可以通过可选的第三个参数来使用类似于 GNU 软件所支持形式的长选项。

Users who are unfamiliar with the Unix getopt() function should consider using the argparse module instead. Users who are familiar with the Unix getopt() function, but would like to get equivalent behavior while writing less code and getting better help and error messages should consider using the optparse module. See Choosing an argument parsing library for additional details.

此模块提供了两个函数和一个异常:

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:]. shortopts is the string of option letters that the script wants to recognize, with options that require an argument followed by a colon (':') and options that accept an optional argument followed by two colons ('::'); i.e., the same format that Unix getopt() uses.

备注

与 GNU getopt() 不同,在非选项参数之后,所有后续参数都会被视为非选项。 这类似于非 GNU Unix 系统的运作方式。

longopts, if specified, must be a list of strings with the names of the long options which should be supported. The leading '--' characters should not be included in the option name. Long options which require an argument should be followed by an equal sign ('='). Long options which accept an optional argument should be followed by an equal sign and question mark ('=?'). To accept only long options, shortopts should be an empty string. 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.

返回值由两个元素组成:第一个是 (option, value) 对的列表;第二个是在去除该选项列表后余下的程序参数列表(这也就是 args 的尾部切片)。每个被返回的选项与值对的第一个元素是选项,短选项前缀一个连字符 (例如 '-x'),长选项则前缀两个连字符 (例如 '--long-option'),第二个元素是选项参数,如果选项不带参数则为空字符串。 列表中选项的排列顺序与它们被解析的顺序相同,因此允许多次出现。 长选项与短选项可以混用。

在 3.14 版本发生变更: Optional arguments are supported.

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

此函数与 getopt() 类似,区别在于它默认使用 GNU 风格的扫描模式。 这意味着选项和非选项参数可能会混在一起。 getopt() 函数将在遇到非选项参数时立即停止处理选项。

如果选项字符串的第一个字符为 '+',或者如果设置了环境变量 POSIXLY_CORRECT,则选项处理会在遇到非选项参数时立即停止。

If the first character of the option string is '-', non-option arguments that are followed by options are added to the list of option-and-value pairs as a pair that has None as its first element and the list of non-option arguments as its second element. The second element of the gnu_getopt() result is a list of program arguments after the last option.

在 3.14 版本发生变更: Support for returning intermixed options and non-option arguments in order.

exception getopt.GetoptError

当参数列表中出现不可识别的选项或当一个需要参数的选项未带参数时将引发此异常。 此异常的参数是一个指明错误原因的字符串。 对于长选项,将一个参数传给不需要参数的选项也将导致此异常被引发。 msgopt 属性将给出错误消息和关联的选项;如果没有关联到此异常的特定选项,则 opt 将为空字符串。

exception getopt.error

GetoptError 的别名;用于向后兼容。

一个仅使用 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']

使用长选项名也同样容易:

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

Optional arguments should be specified explicitly:

>>> s = '-Con -C --color=off --color a1 a2'
>>> args = s.split()
>>> args
['-Con', '-C', '--color=off', '--color', 'a1', 'a2']
>>> optlist, args = getopt.getopt(args, 'C::', ['color=?'])
>>> optlist
[('-C', 'on'), ('-C', ''), ('--color', 'off'), ('--color', '')]
>>> args
['a1', 'a2']

The order of options and non-option arguments can be preserved:

>>> s = 'a1 -x a2 a3 a4 --long a5 a6'
>>> args = s.split()
>>> args
['a1', '-x', 'a2', 'a3', 'a4', '--long', 'a5', 'a6']
>>> optlist, args = getopt.gnu_getopt(args, '-x:', ['long='])
>>> optlist
[(None, ['a1']), ('-x', 'a2'), (None, ['a3', 'a4']), ('--long', 'a5')]
>>> args
['a6']

在脚本中,典型的用法是这样的:

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"
    process(args, output=output, verbose=verbose)

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 optparse module:

import optparse

if __name__ == '__main__':
    parser = optparse.OptionParser()
    parser.add_option('-o', '--output')
    parser.add_option('-v', dest='verbose', action='store_true')
    opts, args = parser.parse_args()
    process(args, output=opts.output, verbose=opts.verbose)

A roughly equivalent command line interface for this case can also be produced by using the argparse module:

import argparse

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('-o', '--output')
    parser.add_argument('-v', dest='verbose', action='store_true')
    parser.add_argument('rest', nargs='*')
    args = parser.parse_args()
    process(args.rest, output=args.output, verbose=args.verbose)

See Choosing an argument parsing library for details on how the argparse version of this code differs in behaviour from the optparse (and getopt) version.

参见

Module optparse

Declarative command line option parsing.

模块 argparse

More opinionated command line option and argument parsing library.