Commit 6d06094c authored by Guido van Rossum's avatar Guido van Rossum

Accept a non-list sequence for the long options (request by Jack Jansen).

Because it might be a common mistake to pass a single string, this
situation is treated separately.

Since we were making a copy of the longopts list anyway, we now use
the list() function -- this made it necessary to change all uses of
the local variable (and argument) 'list' to something more meaningful,
i.e., 'opts'.

Also added docstrings (copied from the library manual) and removed the
(now redundant) module comments.
parent e9bc62d9
# module getopt -- Standard command line processing. """Module getopt -- Parser for command line options.
# Function getopt.getopt() has a different interface but provides the This module helps scripts to parse the command line arguments in
# similar functionality to the Unix getopt() function, with the sys.argv. It supports the same conventions as the Unix getopt()
# addition of long-option support. (Long option support added by Lars function (including the special meanings of arguments of the form `-'
# Wirzenius <liw@iki.fi>.) and `--'). Long options similar to those supported by GNU software
may be used as well via an optional third argument. This module
# It has two required arguments: the first should be argv[1:] (it provides a single function and an exception:
# doesn't want the script name), the second the string of option
# letters as passed to Unix getopt() (i.e., a string of allowable getopt() -- Parse command line options
# option letters, with options requiring an argument followed by a error -- Exception (string) raised when bad options are found
# colon). """
# The optional third argument, if present, getopt.getopt works similar # Long option support added by Lars Wirzenius <liw@iki.fi>.
# to the GNU getopt_long function (but optional arguments are not
# supported). The third argument should be a list of strings that
# name the long options. If the name ends '=', the argument requires
# an argument.
# It raises the exception getopt.error with a string argument if it
# detects an error.
# It returns two values:
# (1) a list of pairs (option, option_argument) giving the options in
# the order in which they were specified. (I'd use a dictionary
# but applications may depend on option order or multiple
# occurrences.) Boolean options have '' as option_argument.
# (2) the list of remaining arguments (may be empty).
import string import string
error = 'getopt.error' error = 'getopt.error'
def getopt(args, shortopts, longopts = []): def getopt(args, shortopts, longopts = []):
list = [] """getopt(args, options[, long_options]) -> opts, args
longopts = 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). If
specified, longopts is 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. Options
which require an argument should be followed by an equal sign
('=').
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 the first argument). Each option-and-value pair returned has
the option as its first element, prefixed with a hyphen (e.g.,
'-x'), and the option argument as its second element, or an empty
string if the option has no argument. 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.
"""
opts = []
if type(longopts) == type(""):
longopts = [longopts]
else:
longopts = list(longopts)
longopts.sort() longopts.sort()
while args and args[0][:1] == '-' and args[0] != '-': while args and args[0][:1] == '-' and args[0] != '-':
if args[0] == '--': if args[0] == '--':
args = args[1:] args = args[1:]
break break
if args[0][:2] == '--': if args[0][:2] == '--':
list, args = do_longs(list, args[0][2:], longopts, args[1:]) opts, args = do_longs(opts, args[0][2:], longopts, args[1:])
else: else:
list, args = do_shorts(list, args[0][1:], shortopts, args[1:]) opts, args = do_shorts(opts, args[0][1:], shortopts, args[1:])
return list, args return opts, args
def do_longs(list, opt, longopts, args): def do_longs(opts, opt, longopts, args):
try: try:
i = string.index(opt, '=') i = string.index(opt, '=')
opt, optarg = opt[:i], opt[i+1:] opt, optarg = opt[:i], opt[i+1:]
...@@ -61,8 +76,8 @@ def do_longs(list, opt, longopts, args): ...@@ -61,8 +76,8 @@ def do_longs(list, opt, longopts, args):
optarg, args = args[0], args[1:] optarg, args = args[0], args[1:]
elif optarg: elif optarg:
raise error, 'option --%s must not have an argument' % opt raise error, 'option --%s must not have an argument' % opt
list.append(('--' + opt, optarg or '')) opts.append(('--' + opt, optarg or ''))
return list, args return opts, args
# Return: # Return:
# has_arg? # has_arg?
...@@ -81,7 +96,7 @@ def long_has_args(opt, longopts): ...@@ -81,7 +96,7 @@ def long_has_args(opt, longopts):
return 0, longopts[i] return 0, longopts[i]
raise error, 'option --' + opt + ' not recognized' raise error, 'option --' + opt + ' not recognized'
def do_shorts(list, optstring, shortopts, args): def do_shorts(opts, optstring, shortopts, args):
while optstring != '': while optstring != '':
opt, optstring = optstring[0], optstring[1:] opt, optstring = optstring[0], optstring[1:]
if short_has_arg(opt, shortopts): if short_has_arg(opt, shortopts):
...@@ -92,8 +107,8 @@ def do_shorts(list, optstring, shortopts, args): ...@@ -92,8 +107,8 @@ def do_shorts(list, optstring, shortopts, args):
optarg, optstring = optstring, '' optarg, optstring = optstring, ''
else: else:
optarg = '' optarg = ''
list.append(('-' + opt, optarg)) opts.append(('-' + opt, optarg))
return list, args return opts, args
def short_has_arg(opt, shortopts): def short_has_arg(opt, shortopts):
for i in range(len(shortopts)): for i in range(len(shortopts)):
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment