getopt — Analisador sintático no estilo C para opções de linha de comando

Código-fonte: Lib/getopt.py

Obsoleto desde a versão 3.13: The getopt module is soft deprecated and will not be developed further; development will continue with the argparse module.

Nota

The getopt module is a parser for command line options whose API is designed to be familiar to users of the C getopt() function. 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.


This module helps scripts to parse the command line arguments in sys.argv. It supports the same conventions as the Unix getopt() function (including the special meanings of arguments of the form ‘-’ and ‘--‘). Long options similar to those supported by GNU software may be used as well via an optional third argument.

Este módulo fornece duas funções e uma exceção:

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 (':'; i.e., the same format that Unix getopt() uses).

Nota

Unlike GNU getopt(), after a non-option argument, all further arguments are considered also non-options. This is similar to the way non-GNU Unix systems work.

longopts, se especificado, deve ser uma lista de strings com os nomes das opções longas que devem ser suportadas. Os caracteres '--' no início não devem ser incluídos no nome da opção. Opções longas que requerem um argumento devem ser seguidas por um sinal de igual ('='). Argumentos opcionais não são suportados. Para aceitar apenas opções longas, shortopts deve ser uma string vazia. Opções longas na linha de comando podem ser reconhecidas, desde que forneçam um prefixo do nome da opção que corresponda exatamente a uma das opções aceitas. Por exemplo, se longopts for ['foo', 'frob'], a opção --fo irá corresponder a --foo, mas --f não corresponderá exclusivamente, então GetoptError será levantada.

O valor de retorno consiste em dois elementos: o primeiro é uma lista de pares (option, value); a segunda é a lista de argumentos de programa restantes depois que a lista de opções foi removida (esta é uma fatia ao final de args). Cada par de opção e valor retornado tem a opção como seu primeiro elemento, prefixado com um hífen para opções curtas (por exemplo, '-x') ou dois hifenes para opções longas (por exemplo, '--long-option'), e o argumento da opção como seu segundo elemento, ou uma string vazia se a opção não tiver argumento. As opções ocorrem na lista na mesma ordem em que foram encontradas, permitindo assim múltiplas ocorrências. Opções longas e curtas podem ser misturadas.

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

Esta função funciona como getopt(), exceto que o modo de digitalização do estilo GNU é usado por padrão. Isso significa que os argumentos de opção e não opção podem ser misturados. A função getopt() interrompe o processamento das opções assim que um argumento não opcional é encontrado.

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.

exception getopt.GetoptError

This is raised when an unrecognized option is found in the argument list or when an option requiring an argument is given 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.

exception getopt.error

Alias para GetoptError; para compatibilidade reversa.

Um exemplo usando apenas opções de estilo 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']

Usar nomes de opções longos é igualmente fácil:

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

Em um script, o uso típico é algo assim:

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

Observe que uma interface de linha de comando equivalente pode ser produzida com menos código e mais mensagens de erro de ajuda e erro informativas usando o módulo 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 ..

Ver também

Módulo argparse

Alternativa de opção de linha de comando e biblioteca de análise de argumento.