1 | n/a | """Parser for command line options. |
---|
2 | n/a | |
---|
3 | n/a | This module helps scripts to parse the command line arguments in |
---|
4 | n/a | sys.argv. It supports the same conventions as the Unix getopt() |
---|
5 | n/a | function (including the special meanings of arguments of the form `-' |
---|
6 | n/a | and `--'). Long options similar to those supported by GNU software |
---|
7 | n/a | may be used as well via an optional third argument. This module |
---|
8 | n/a | provides two functions and an exception: |
---|
9 | n/a | |
---|
10 | n/a | getopt() -- Parse command line options |
---|
11 | n/a | gnu_getopt() -- Like getopt(), but allow option and non-option arguments |
---|
12 | n/a | to be intermixed. |
---|
13 | n/a | GetoptError -- exception (class) raised with 'opt' attribute, which is the |
---|
14 | n/a | option involved with the exception. |
---|
15 | n/a | """ |
---|
16 | n/a | |
---|
17 | n/a | # Long option support added by Lars Wirzenius <liw@iki.fi>. |
---|
18 | n/a | # |
---|
19 | n/a | # Gerrit Holl <gerrit@nl.linux.org> moved the string-based exceptions |
---|
20 | n/a | # to class-based exceptions. |
---|
21 | n/a | # |
---|
22 | n/a | # Peter Ã
strand <astrand@lysator.liu.se> added gnu_getopt(). |
---|
23 | n/a | # |
---|
24 | n/a | # TODO for gnu_getopt(): |
---|
25 | n/a | # |
---|
26 | n/a | # - GNU getopt_long_only mechanism |
---|
27 | n/a | # - allow the caller to specify ordering |
---|
28 | n/a | # - RETURN_IN_ORDER option |
---|
29 | n/a | # - GNU extension with '-' as first character of option string |
---|
30 | n/a | # - optional arguments, specified by double colons |
---|
31 | n/a | # - an option string with a W followed by semicolon should |
---|
32 | n/a | # treat "-W foo" as "--foo" |
---|
33 | n/a | |
---|
34 | n/a | __all__ = ["GetoptError","error","getopt","gnu_getopt"] |
---|
35 | n/a | |
---|
36 | n/a | import os |
---|
37 | n/a | try: |
---|
38 | n/a | from gettext import gettext as _ |
---|
39 | n/a | except ImportError: |
---|
40 | n/a | # Bootstrapping Python: gettext's dependencies not built yet |
---|
41 | n/a | def _(s): return s |
---|
42 | n/a | |
---|
43 | n/a | class GetoptError(Exception): |
---|
44 | n/a | opt = '' |
---|
45 | n/a | msg = '' |
---|
46 | n/a | def __init__(self, msg, opt=''): |
---|
47 | n/a | self.msg = msg |
---|
48 | n/a | self.opt = opt |
---|
49 | n/a | Exception.__init__(self, msg, opt) |
---|
50 | n/a | |
---|
51 | n/a | def __str__(self): |
---|
52 | n/a | return self.msg |
---|
53 | n/a | |
---|
54 | n/a | error = GetoptError # backward compatibility |
---|
55 | n/a | |
---|
56 | n/a | def getopt(args, shortopts, longopts = []): |
---|
57 | n/a | """getopt(args, options[, long_options]) -> opts, args |
---|
58 | n/a | |
---|
59 | n/a | Parses command line options and parameter list. args is the |
---|
60 | n/a | argument list to be parsed, without the leading reference to the |
---|
61 | n/a | running program. Typically, this means "sys.argv[1:]". shortopts |
---|
62 | n/a | is the string of option letters that the script wants to |
---|
63 | n/a | recognize, with options that require an argument followed by a |
---|
64 | n/a | colon (i.e., the same format that Unix getopt() uses). If |
---|
65 | n/a | specified, longopts is a list of strings with the names of the |
---|
66 | n/a | long options which should be supported. The leading '--' |
---|
67 | n/a | characters should not be included in the option name. Options |
---|
68 | n/a | which require an argument should be followed by an equal sign |
---|
69 | n/a | ('='). |
---|
70 | n/a | |
---|
71 | n/a | The return value consists of two elements: the first is a list of |
---|
72 | n/a | (option, value) pairs; the second is the list of program arguments |
---|
73 | n/a | left after the option list was stripped (this is a trailing slice |
---|
74 | n/a | of the first argument). Each option-and-value pair returned has |
---|
75 | n/a | the option as its first element, prefixed with a hyphen (e.g., |
---|
76 | n/a | '-x'), and the option argument as its second element, or an empty |
---|
77 | n/a | string if the option has no argument. The options occur in the |
---|
78 | n/a | list in the same order in which they were found, thus allowing |
---|
79 | n/a | multiple occurrences. Long and short options may be mixed. |
---|
80 | n/a | |
---|
81 | n/a | """ |
---|
82 | n/a | |
---|
83 | n/a | opts = [] |
---|
84 | n/a | if type(longopts) == type(""): |
---|
85 | n/a | longopts = [longopts] |
---|
86 | n/a | else: |
---|
87 | n/a | longopts = list(longopts) |
---|
88 | n/a | while args and args[0].startswith('-') and args[0] != '-': |
---|
89 | n/a | if args[0] == '--': |
---|
90 | n/a | args = args[1:] |
---|
91 | n/a | break |
---|
92 | n/a | if args[0].startswith('--'): |
---|
93 | n/a | opts, args = do_longs(opts, args[0][2:], longopts, args[1:]) |
---|
94 | n/a | else: |
---|
95 | n/a | opts, args = do_shorts(opts, args[0][1:], shortopts, args[1:]) |
---|
96 | n/a | |
---|
97 | n/a | return opts, args |
---|
98 | n/a | |
---|
99 | n/a | def gnu_getopt(args, shortopts, longopts = []): |
---|
100 | n/a | """getopt(args, options[, long_options]) -> opts, args |
---|
101 | n/a | |
---|
102 | n/a | This function works like getopt(), except that GNU style scanning |
---|
103 | n/a | mode is used by default. This means that option and non-option |
---|
104 | n/a | arguments may be intermixed. The getopt() function stops |
---|
105 | n/a | processing options as soon as a non-option argument is |
---|
106 | n/a | encountered. |
---|
107 | n/a | |
---|
108 | n/a | If the first character of the option string is `+', or if the |
---|
109 | n/a | environment variable POSIXLY_CORRECT is set, then option |
---|
110 | n/a | processing stops as soon as a non-option argument is encountered. |
---|
111 | n/a | |
---|
112 | n/a | """ |
---|
113 | n/a | |
---|
114 | n/a | opts = [] |
---|
115 | n/a | prog_args = [] |
---|
116 | n/a | if isinstance(longopts, str): |
---|
117 | n/a | longopts = [longopts] |
---|
118 | n/a | else: |
---|
119 | n/a | longopts = list(longopts) |
---|
120 | n/a | |
---|
121 | n/a | # Allow options after non-option arguments? |
---|
122 | n/a | if shortopts.startswith('+'): |
---|
123 | n/a | shortopts = shortopts[1:] |
---|
124 | n/a | all_options_first = True |
---|
125 | n/a | elif os.environ.get("POSIXLY_CORRECT"): |
---|
126 | n/a | all_options_first = True |
---|
127 | n/a | else: |
---|
128 | n/a | all_options_first = False |
---|
129 | n/a | |
---|
130 | n/a | while args: |
---|
131 | n/a | if args[0] == '--': |
---|
132 | n/a | prog_args += args[1:] |
---|
133 | n/a | break |
---|
134 | n/a | |
---|
135 | n/a | if args[0][:2] == '--': |
---|
136 | n/a | opts, args = do_longs(opts, args[0][2:], longopts, args[1:]) |
---|
137 | n/a | elif args[0][:1] == '-' and args[0] != '-': |
---|
138 | n/a | opts, args = do_shorts(opts, args[0][1:], shortopts, args[1:]) |
---|
139 | n/a | else: |
---|
140 | n/a | if all_options_first: |
---|
141 | n/a | prog_args += args |
---|
142 | n/a | break |
---|
143 | n/a | else: |
---|
144 | n/a | prog_args.append(args[0]) |
---|
145 | n/a | args = args[1:] |
---|
146 | n/a | |
---|
147 | n/a | return opts, prog_args |
---|
148 | n/a | |
---|
149 | n/a | def do_longs(opts, opt, longopts, args): |
---|
150 | n/a | try: |
---|
151 | n/a | i = opt.index('=') |
---|
152 | n/a | except ValueError: |
---|
153 | n/a | optarg = None |
---|
154 | n/a | else: |
---|
155 | n/a | opt, optarg = opt[:i], opt[i+1:] |
---|
156 | n/a | |
---|
157 | n/a | has_arg, opt = long_has_args(opt, longopts) |
---|
158 | n/a | if has_arg: |
---|
159 | n/a | if optarg is None: |
---|
160 | n/a | if not args: |
---|
161 | n/a | raise GetoptError(_('option --%s requires argument') % opt, opt) |
---|
162 | n/a | optarg, args = args[0], args[1:] |
---|
163 | n/a | elif optarg is not None: |
---|
164 | n/a | raise GetoptError(_('option --%s must not have an argument') % opt, opt) |
---|
165 | n/a | opts.append(('--' + opt, optarg or '')) |
---|
166 | n/a | return opts, args |
---|
167 | n/a | |
---|
168 | n/a | # Return: |
---|
169 | n/a | # has_arg? |
---|
170 | n/a | # full option name |
---|
171 | n/a | def long_has_args(opt, longopts): |
---|
172 | n/a | possibilities = [o for o in longopts if o.startswith(opt)] |
---|
173 | n/a | if not possibilities: |
---|
174 | n/a | raise GetoptError(_('option --%s not recognized') % opt, opt) |
---|
175 | n/a | # Is there an exact match? |
---|
176 | n/a | if opt in possibilities: |
---|
177 | n/a | return False, opt |
---|
178 | n/a | elif opt + '=' in possibilities: |
---|
179 | n/a | return True, opt |
---|
180 | n/a | # No exact match, so better be unique. |
---|
181 | n/a | if len(possibilities) > 1: |
---|
182 | n/a | # XXX since possibilities contains all valid continuations, might be |
---|
183 | n/a | # nice to work them into the error msg |
---|
184 | n/a | raise GetoptError(_('option --%s not a unique prefix') % opt, opt) |
---|
185 | n/a | assert len(possibilities) == 1 |
---|
186 | n/a | unique_match = possibilities[0] |
---|
187 | n/a | has_arg = unique_match.endswith('=') |
---|
188 | n/a | if has_arg: |
---|
189 | n/a | unique_match = unique_match[:-1] |
---|
190 | n/a | return has_arg, unique_match |
---|
191 | n/a | |
---|
192 | n/a | def do_shorts(opts, optstring, shortopts, args): |
---|
193 | n/a | while optstring != '': |
---|
194 | n/a | opt, optstring = optstring[0], optstring[1:] |
---|
195 | n/a | if short_has_arg(opt, shortopts): |
---|
196 | n/a | if optstring == '': |
---|
197 | n/a | if not args: |
---|
198 | n/a | raise GetoptError(_('option -%s requires argument') % opt, |
---|
199 | n/a | opt) |
---|
200 | n/a | optstring, args = args[0], args[1:] |
---|
201 | n/a | optarg, optstring = optstring, '' |
---|
202 | n/a | else: |
---|
203 | n/a | optarg = '' |
---|
204 | n/a | opts.append(('-' + opt, optarg)) |
---|
205 | n/a | return opts, args |
---|
206 | n/a | |
---|
207 | n/a | def short_has_arg(opt, shortopts): |
---|
208 | n/a | for i in range(len(shortopts)): |
---|
209 | n/a | if opt == shortopts[i] != ':': |
---|
210 | n/a | return shortopts.startswith(':', i+1) |
---|
211 | n/a | raise GetoptError(_('option -%s not recognized') % opt, opt) |
---|
212 | n/a | |
---|
213 | n/a | if __name__ == '__main__': |
---|
214 | n/a | import sys |
---|
215 | n/a | print(getopt(sys.argv[1:], "a:b", ["alpha=", "beta"])) |
---|