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