1 """Parser for command line options.
3 This module helps scripts to parse the command line arguments in
4 sys.argv. It supports the same conventions as the Unix getopt()
5 function (including the special meanings of arguments of the form `-'
6 and `--'). Long options similar to those supported by GNU software
7 may be used as well via an optional third argument. This module
8 provides a single function and an exception:
10 getopt() -- Parse command line options
11 GetoptError -- exception (class) raised with 'opt' attribute, which is the
12 option involved with the exception.
15 # Long option support added by Lars Wirzenius <liw@iki.fi>.
17 # Gerrit Holl <gerrit@nl.linux.org> moved the string-based exceptions
18 # to class-based exceptions.
20 __all__
= ["GetoptError","error","getopt"]
22 class GetoptError(Exception):
25 def __init__(self
, msg
, opt
):
28 Exception.__init
__(self
, msg
, opt
)
33 error
= GetoptError
# backward compatibility
35 def getopt(args
, shortopts
, longopts
= []):
36 """getopt(args, options[, long_options]) -> opts, args
38 Parses command line options and parameter list. args is the
39 argument list to be parsed, without the leading reference to the
40 running program. Typically, this means "sys.argv[1:]". shortopts
41 is the string of option letters that the script wants to
42 recognize, with options that require an argument followed by a
43 colon (i.e., the same format that Unix getopt() uses). If
44 specified, longopts is a list of strings with the names of the
45 long options which should be supported. The leading '--'
46 characters should not be included in the option name. Options
47 which require an argument should be followed by an equal sign
50 The return value consists of two elements: the first is a list of
51 (option, value) pairs; the second is the list of program arguments
52 left after the option list was stripped (this is a trailing slice
53 of the first argument). Each option-and-value pair returned has
54 the option as its first element, prefixed with a hyphen (e.g.,
55 '-x'), and the option argument as its second element, or an empty
56 string if the option has no argument. The options occur in the
57 list in the same order in which they were found, thus allowing
58 multiple occurrences. Long and short options may be mixed.
63 if type(longopts
) == type(""):
66 longopts
= list(longopts
)
67 while args
and args
[0].startswith('-') and args
[0] != '-':
71 if args
[0][:2] == '--':
72 opts
, args
= do_longs(opts
, args
[0][2:], longopts
, args
[1:])
74 opts
, args
= do_shorts(opts
, args
[0][1:], shortopts
, args
[1:])
78 def do_longs(opts
, opt
, longopts
, args
):
84 opt
, optarg
= opt
[:i
], opt
[i
+1:]
86 has_arg
, opt
= long_has_args(opt
, longopts
)
90 raise GetoptError('option --%s requires argument' % opt
, opt
)
91 optarg
, args
= args
[0], args
[1:]
93 raise GetoptError('option --%s must not have an argument' % opt
, opt
)
94 opts
.append(('--' + opt
, optarg
or ''))
100 def long_has_args(opt
, longopts
):
101 possibilities
= [o
for o
in longopts
if o
.startswith(opt
)]
102 if not possibilities
:
103 raise GetoptError('option --%s not recognized' % opt
, opt
)
104 # Is there an exact match?
105 if opt
in possibilities
:
107 elif opt
+ '=' in possibilities
:
109 # No exact match, so better be unique.
110 if len(possibilities
) > 1:
111 # XXX since possibilities contains all valid continuations, might be
112 # nice to work them into the error msg
113 raise GetoptError('option --%s not a unique prefix' % opt
, opt
)
114 assert len(possibilities
) == 1
115 unique_match
= possibilities
[0]
116 has_arg
= unique_match
.endswith('=')
118 unique_match
= unique_match
[:-1]
119 return has_arg
, unique_match
121 def do_shorts(opts
, optstring
, shortopts
, args
):
122 while optstring
!= '':
123 opt
, optstring
= optstring
[0], optstring
[1:]
124 if short_has_arg(opt
, shortopts
):
127 raise GetoptError('option -%s requires argument' % opt
, opt
)
128 optstring
, args
= args
[0], args
[1:]
129 optarg
, optstring
= optstring
, ''
132 opts
.append(('-' + opt
, optarg
))
135 def short_has_arg(opt
, shortopts
):
136 for i
in range(len(shortopts
)):
137 if opt
== shortopts
[i
] != ':':
138 return shortopts
[i
+1:i
+2] == ':'
139 raise GetoptError('option -%s not recognized' % opt
, opt
)
141 if __name__
== '__main__':
143 print getopt(sys
.argv
[1:], "a:b", ["alpha=", "beta"])