getopt —- C-style parser for command line options

Source code:Lib/getopt.py

注解

The getopt module is a parser for command line options whose API isdesigned to be familiar to users of the C getopt() function. Users whoare unfamiliar with the C getopt() function or who would like to writeless code and get better help and error messages should consider using theargparse 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 (includingthe special meanings of arguments of the form '-' and ''). Longoptions similar to those supported by GNU software may be used as well via anoptional third argument.

This module provides two functions and anexception:

  • getopt.getopt(args, shortopts, longopts=[])
  • Parses command line options and parameter list. args is the argument list tobe parsed, without the leading reference to the running program. Typically, thismeans sys.argv[1:]. shortopts is the string of option letters that thescript wants to recognize, with options that require an argument followed by acolon (':'; i.e., the same format that Unix getopt() uses).

注解

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

longopts, if specified, must be a list of strings with the names of thelong options which should be supported. The leading '—' charactersshould not be included in the option name. Long options which require anargument should be followed by an equal sign ('='). Optional argumentsare not supported. To accept only long options, shortopts should be anempty string. Long options on the command line can be recognized so long asthey provide a prefix of the option name that matches exactly one of theaccepted options. For example, if longopts is ['foo', 'frob'], theoption —fo will match as —foo, but —f willnot match uniquely, so GetoptError will be raised.

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 theoption list was stripped (this is a trailing slice of args). Eachoption-and-value pair returned has the option as its first element, prefixedwith a hyphen for short options (e.g., '-x') or two hyphens for longoptions (e.g., '—long-option'), and the option argument as itssecond element, or an empty string if the option has no argument. Theoptions occur in the list in the same order in which they were found, thusallowing multiple occurrences. Long and short options may be mixed.

  • getopt.gnugetopt(_args, shortopts, longopts=[])
  • This function works like getopt(), except that GNU style scanning mode isused by default. This means that option and non-option arguments may beintermixed. The getopt() function stops processing options as soon as anon-option argument is encountered.

If the first character of the option string is '+', or if the environmentvariable POSIXLY_CORRECT is set, then option processing stops assoon as a non-option argument is encountered.

  • exception getopt.GetoptError
  • This is raised when an unrecognized option is found in the argument list or whenan option requiring an argument is given none. The argument to the exception isa string indicating the cause of the error. For long options, an argument givento an option which does not require one will also cause this exception to beraised. The attributes msg and opt give the error message andrelated option; if there is no specific option to which the exception relates,opt is an empty string.
  • exception getopt.error
  • Alias for GetoptError; for backward compatibility.

An example using only Unix style options:

  1. >>> import getopt
  2. >>> args = '-a -b -cfoo -d bar a1 a2'.split()
  3. >>> args
  4. ['-a', '-b', '-cfoo', '-d', 'bar', 'a1', 'a2']
  5. >>> optlist, args = getopt.getopt(args, 'abc:d:')
  6. >>> optlist
  7. [('-a', ''), ('-b', ''), ('-c', 'foo'), ('-d', 'bar')]
  8. >>> args
  9. ['a1', 'a2']

Using long option names is equally easy:

  1. >>> s = '--condition=foo --testing --output-file abc.def -x a1 a2'
  2. >>> args = s.split()
  3. >>> args
  4. ['--condition=foo', '--testing', '--output-file', 'abc.def', '-x', 'a1', 'a2']
  5. >>> optlist, args = getopt.getopt(args, 'x', [
  6. ... 'condition=', 'output-file=', 'testing'])
  7. >>> optlist
  8. [('--condition', 'foo'), ('--testing', ''), ('--output-file', 'abc.def'), ('-x', '')]
  9. >>> args
  10. ['a1', 'a2']

In a script, typical usage is something like this:

  1. import getopt, sys
  2.  
  3. def main():
  4. try:
  5. opts, args = getopt.getopt(sys.argv[1:], "ho:v", ["help", "output="])
  6. except getopt.GetoptError as err:
  7. # print help information and exit:
  8. print(err) # will print something like "option -a not recognized"
  9. usage()
  10. sys.exit(2)
  11. output = None
  12. verbose = False
  13. for o, a in opts:
  14. if o == "-v":
  15. verbose = True
  16. elif o in ("-h", "--help"):
  17. usage()
  18. sys.exit()
  19. elif o in ("-o", "--output"):
  20. output = a
  21. else:
  22. assert False, "unhandled option"
  23. # ...
  24.  
  25. if __name__ == "__main__":
  26. main()

Note that an equivalent command line interface could be produced with less codeand more informative help and error messages by using the argparse module:

  1. import argparse
  2.  
  3. if __name__ == '__main__':
  4. parser = argparse.ArgumentParser()
  5. parser.add_argument('-o', '--output')
  6. parser.add_argument('-v', dest='verbose', action='store_true')
  7. args = parser.parse_args()
  8. # ... do something with args.output ...
  9. # ... do something with args.verbose ..

参见

  • Module argparse
  • Alternative command line option and argument parsing library.