1 | n/a | # Author: Steven J. Bethard <steven.bethard@gmail.com>. |
---|
2 | n/a | |
---|
3 | n/a | """Command-line parsing library |
---|
4 | n/a | |
---|
5 | n/a | This module is an optparse-inspired command-line parsing library that: |
---|
6 | n/a | |
---|
7 | n/a | - handles both optional and positional arguments |
---|
8 | n/a | - produces highly informative usage messages |
---|
9 | n/a | - supports parsers that dispatch to sub-parsers |
---|
10 | n/a | |
---|
11 | n/a | The following is a simple usage example that sums integers from the |
---|
12 | n/a | command-line and writes the result to a file:: |
---|
13 | n/a | |
---|
14 | n/a | parser = argparse.ArgumentParser( |
---|
15 | n/a | description='sum the integers at the command line') |
---|
16 | n/a | parser.add_argument( |
---|
17 | n/a | 'integers', metavar='int', nargs='+', type=int, |
---|
18 | n/a | help='an integer to be summed') |
---|
19 | n/a | parser.add_argument( |
---|
20 | n/a | '--log', default=sys.stdout, type=argparse.FileType('w'), |
---|
21 | n/a | help='the file where the sum should be written') |
---|
22 | n/a | args = parser.parse_args() |
---|
23 | n/a | args.log.write('%s' % sum(args.integers)) |
---|
24 | n/a | args.log.close() |
---|
25 | n/a | |
---|
26 | n/a | The module contains the following public classes: |
---|
27 | n/a | |
---|
28 | n/a | - ArgumentParser -- The main entry point for command-line parsing. As the |
---|
29 | n/a | example above shows, the add_argument() method is used to populate |
---|
30 | n/a | the parser with actions for optional and positional arguments. Then |
---|
31 | n/a | the parse_args() method is invoked to convert the args at the |
---|
32 | n/a | command-line into an object with attributes. |
---|
33 | n/a | |
---|
34 | n/a | - ArgumentError -- The exception raised by ArgumentParser objects when |
---|
35 | n/a | there are errors with the parser's actions. Errors raised while |
---|
36 | n/a | parsing the command-line are caught by ArgumentParser and emitted |
---|
37 | n/a | as command-line messages. |
---|
38 | n/a | |
---|
39 | n/a | - FileType -- A factory for defining types of files to be created. As the |
---|
40 | n/a | example above shows, instances of FileType are typically passed as |
---|
41 | n/a | the type= argument of add_argument() calls. |
---|
42 | n/a | |
---|
43 | n/a | - Action -- The base class for parser actions. Typically actions are |
---|
44 | n/a | selected by passing strings like 'store_true' or 'append_const' to |
---|
45 | n/a | the action= argument of add_argument(). However, for greater |
---|
46 | n/a | customization of ArgumentParser actions, subclasses of Action may |
---|
47 | n/a | be defined and passed as the action= argument. |
---|
48 | n/a | |
---|
49 | n/a | - HelpFormatter, RawDescriptionHelpFormatter, RawTextHelpFormatter, |
---|
50 | n/a | ArgumentDefaultsHelpFormatter -- Formatter classes which |
---|
51 | n/a | may be passed as the formatter_class= argument to the |
---|
52 | n/a | ArgumentParser constructor. HelpFormatter is the default, |
---|
53 | n/a | RawDescriptionHelpFormatter and RawTextHelpFormatter tell the parser |
---|
54 | n/a | not to change the formatting for help text, and |
---|
55 | n/a | ArgumentDefaultsHelpFormatter adds information about argument defaults |
---|
56 | n/a | to the help. |
---|
57 | n/a | |
---|
58 | n/a | All other classes in this module are considered implementation details. |
---|
59 | n/a | (Also note that HelpFormatter and RawDescriptionHelpFormatter are only |
---|
60 | n/a | considered public as object names -- the API of the formatter objects is |
---|
61 | n/a | still considered an implementation detail.) |
---|
62 | n/a | """ |
---|
63 | n/a | |
---|
64 | n/a | __version__ = '1.1' |
---|
65 | n/a | __all__ = [ |
---|
66 | n/a | 'ArgumentParser', |
---|
67 | n/a | 'ArgumentError', |
---|
68 | n/a | 'ArgumentTypeError', |
---|
69 | n/a | 'FileType', |
---|
70 | n/a | 'HelpFormatter', |
---|
71 | n/a | 'ArgumentDefaultsHelpFormatter', |
---|
72 | n/a | 'RawDescriptionHelpFormatter', |
---|
73 | n/a | 'RawTextHelpFormatter', |
---|
74 | n/a | 'MetavarTypeHelpFormatter', |
---|
75 | n/a | 'Namespace', |
---|
76 | n/a | 'Action', |
---|
77 | n/a | 'ONE_OR_MORE', |
---|
78 | n/a | 'OPTIONAL', |
---|
79 | n/a | 'PARSER', |
---|
80 | n/a | 'REMAINDER', |
---|
81 | n/a | 'SUPPRESS', |
---|
82 | n/a | 'ZERO_OR_MORE', |
---|
83 | n/a | ] |
---|
84 | n/a | |
---|
85 | n/a | |
---|
86 | n/a | import collections as _collections |
---|
87 | n/a | import copy as _copy |
---|
88 | n/a | import os as _os |
---|
89 | n/a | import re as _re |
---|
90 | n/a | import sys as _sys |
---|
91 | n/a | import textwrap as _textwrap |
---|
92 | n/a | |
---|
93 | n/a | from gettext import gettext as _, ngettext |
---|
94 | n/a | |
---|
95 | n/a | |
---|
96 | n/a | SUPPRESS = '==SUPPRESS==' |
---|
97 | n/a | |
---|
98 | n/a | OPTIONAL = '?' |
---|
99 | n/a | ZERO_OR_MORE = '*' |
---|
100 | n/a | ONE_OR_MORE = '+' |
---|
101 | n/a | PARSER = 'A...' |
---|
102 | n/a | REMAINDER = '...' |
---|
103 | n/a | _UNRECOGNIZED_ARGS_ATTR = '_unrecognized_args' |
---|
104 | n/a | |
---|
105 | n/a | # ============================= |
---|
106 | n/a | # Utility functions and classes |
---|
107 | n/a | # ============================= |
---|
108 | n/a | |
---|
109 | n/a | class _AttributeHolder(object): |
---|
110 | n/a | """Abstract base class that provides __repr__. |
---|
111 | n/a | |
---|
112 | n/a | The __repr__ method returns a string in the format:: |
---|
113 | n/a | ClassName(attr=name, attr=name, ...) |
---|
114 | n/a | The attributes are determined either by a class-level attribute, |
---|
115 | n/a | '_kwarg_names', or by inspecting the instance __dict__. |
---|
116 | n/a | """ |
---|
117 | n/a | |
---|
118 | n/a | def __repr__(self): |
---|
119 | n/a | type_name = type(self).__name__ |
---|
120 | n/a | arg_strings = [] |
---|
121 | n/a | star_args = {} |
---|
122 | n/a | for arg in self._get_args(): |
---|
123 | n/a | arg_strings.append(repr(arg)) |
---|
124 | n/a | for name, value in self._get_kwargs(): |
---|
125 | n/a | if name.isidentifier(): |
---|
126 | n/a | arg_strings.append('%s=%r' % (name, value)) |
---|
127 | n/a | else: |
---|
128 | n/a | star_args[name] = value |
---|
129 | n/a | if star_args: |
---|
130 | n/a | arg_strings.append('**%s' % repr(star_args)) |
---|
131 | n/a | return '%s(%s)' % (type_name, ', '.join(arg_strings)) |
---|
132 | n/a | |
---|
133 | n/a | def _get_kwargs(self): |
---|
134 | n/a | return sorted(self.__dict__.items()) |
---|
135 | n/a | |
---|
136 | n/a | def _get_args(self): |
---|
137 | n/a | return [] |
---|
138 | n/a | |
---|
139 | n/a | |
---|
140 | n/a | def _ensure_value(namespace, name, value): |
---|
141 | n/a | if getattr(namespace, name, None) is None: |
---|
142 | n/a | setattr(namespace, name, value) |
---|
143 | n/a | return getattr(namespace, name) |
---|
144 | n/a | |
---|
145 | n/a | |
---|
146 | n/a | # =============== |
---|
147 | n/a | # Formatting Help |
---|
148 | n/a | # =============== |
---|
149 | n/a | |
---|
150 | n/a | class HelpFormatter(object): |
---|
151 | n/a | """Formatter for generating usage messages and argument help strings. |
---|
152 | n/a | |
---|
153 | n/a | Only the name of this class is considered a public API. All the methods |
---|
154 | n/a | provided by the class are considered an implementation detail. |
---|
155 | n/a | """ |
---|
156 | n/a | |
---|
157 | n/a | def __init__(self, |
---|
158 | n/a | prog, |
---|
159 | n/a | indent_increment=2, |
---|
160 | n/a | max_help_position=24, |
---|
161 | n/a | width=None): |
---|
162 | n/a | |
---|
163 | n/a | # default setting for width |
---|
164 | n/a | if width is None: |
---|
165 | n/a | try: |
---|
166 | n/a | width = int(_os.environ['COLUMNS']) |
---|
167 | n/a | except (KeyError, ValueError): |
---|
168 | n/a | width = 80 |
---|
169 | n/a | width -= 2 |
---|
170 | n/a | |
---|
171 | n/a | self._prog = prog |
---|
172 | n/a | self._indent_increment = indent_increment |
---|
173 | n/a | self._max_help_position = max_help_position |
---|
174 | n/a | self._max_help_position = min(max_help_position, |
---|
175 | n/a | max(width - 20, indent_increment * 2)) |
---|
176 | n/a | self._width = width |
---|
177 | n/a | |
---|
178 | n/a | self._current_indent = 0 |
---|
179 | n/a | self._level = 0 |
---|
180 | n/a | self._action_max_length = 0 |
---|
181 | n/a | |
---|
182 | n/a | self._root_section = self._Section(self, None) |
---|
183 | n/a | self._current_section = self._root_section |
---|
184 | n/a | |
---|
185 | n/a | self._whitespace_matcher = _re.compile(r'\s+', _re.ASCII) |
---|
186 | n/a | self._long_break_matcher = _re.compile(r'\n\n\n+') |
---|
187 | n/a | |
---|
188 | n/a | # =============================== |
---|
189 | n/a | # Section and indentation methods |
---|
190 | n/a | # =============================== |
---|
191 | n/a | def _indent(self): |
---|
192 | n/a | self._current_indent += self._indent_increment |
---|
193 | n/a | self._level += 1 |
---|
194 | n/a | |
---|
195 | n/a | def _dedent(self): |
---|
196 | n/a | self._current_indent -= self._indent_increment |
---|
197 | n/a | assert self._current_indent >= 0, 'Indent decreased below 0.' |
---|
198 | n/a | self._level -= 1 |
---|
199 | n/a | |
---|
200 | n/a | class _Section(object): |
---|
201 | n/a | |
---|
202 | n/a | def __init__(self, formatter, parent, heading=None): |
---|
203 | n/a | self.formatter = formatter |
---|
204 | n/a | self.parent = parent |
---|
205 | n/a | self.heading = heading |
---|
206 | n/a | self.items = [] |
---|
207 | n/a | |
---|
208 | n/a | def format_help(self): |
---|
209 | n/a | # format the indented section |
---|
210 | n/a | if self.parent is not None: |
---|
211 | n/a | self.formatter._indent() |
---|
212 | n/a | join = self.formatter._join_parts |
---|
213 | n/a | item_help = join([func(*args) for func, args in self.items]) |
---|
214 | n/a | if self.parent is not None: |
---|
215 | n/a | self.formatter._dedent() |
---|
216 | n/a | |
---|
217 | n/a | # return nothing if the section was empty |
---|
218 | n/a | if not item_help: |
---|
219 | n/a | return '' |
---|
220 | n/a | |
---|
221 | n/a | # add the heading if the section was non-empty |
---|
222 | n/a | if self.heading is not SUPPRESS and self.heading is not None: |
---|
223 | n/a | current_indent = self.formatter._current_indent |
---|
224 | n/a | heading = '%*s%s:\n' % (current_indent, '', self.heading) |
---|
225 | n/a | else: |
---|
226 | n/a | heading = '' |
---|
227 | n/a | |
---|
228 | n/a | # join the section-initial newline, the heading and the help |
---|
229 | n/a | return join(['\n', heading, item_help, '\n']) |
---|
230 | n/a | |
---|
231 | n/a | def _add_item(self, func, args): |
---|
232 | n/a | self._current_section.items.append((func, args)) |
---|
233 | n/a | |
---|
234 | n/a | # ======================== |
---|
235 | n/a | # Message building methods |
---|
236 | n/a | # ======================== |
---|
237 | n/a | def start_section(self, heading): |
---|
238 | n/a | self._indent() |
---|
239 | n/a | section = self._Section(self, self._current_section, heading) |
---|
240 | n/a | self._add_item(section.format_help, []) |
---|
241 | n/a | self._current_section = section |
---|
242 | n/a | |
---|
243 | n/a | def end_section(self): |
---|
244 | n/a | self._current_section = self._current_section.parent |
---|
245 | n/a | self._dedent() |
---|
246 | n/a | |
---|
247 | n/a | def add_text(self, text): |
---|
248 | n/a | if text is not SUPPRESS and text is not None: |
---|
249 | n/a | self._add_item(self._format_text, [text]) |
---|
250 | n/a | |
---|
251 | n/a | def add_usage(self, usage, actions, groups, prefix=None): |
---|
252 | n/a | if usage is not SUPPRESS: |
---|
253 | n/a | args = usage, actions, groups, prefix |
---|
254 | n/a | self._add_item(self._format_usage, args) |
---|
255 | n/a | |
---|
256 | n/a | def add_argument(self, action): |
---|
257 | n/a | if action.help is not SUPPRESS: |
---|
258 | n/a | |
---|
259 | n/a | # find all invocations |
---|
260 | n/a | get_invocation = self._format_action_invocation |
---|
261 | n/a | invocations = [get_invocation(action)] |
---|
262 | n/a | for subaction in self._iter_indented_subactions(action): |
---|
263 | n/a | invocations.append(get_invocation(subaction)) |
---|
264 | n/a | |
---|
265 | n/a | # update the maximum item length |
---|
266 | n/a | invocation_length = max([len(s) for s in invocations]) |
---|
267 | n/a | action_length = invocation_length + self._current_indent |
---|
268 | n/a | self._action_max_length = max(self._action_max_length, |
---|
269 | n/a | action_length) |
---|
270 | n/a | |
---|
271 | n/a | # add the item to the list |
---|
272 | n/a | self._add_item(self._format_action, [action]) |
---|
273 | n/a | |
---|
274 | n/a | def add_arguments(self, actions): |
---|
275 | n/a | for action in actions: |
---|
276 | n/a | self.add_argument(action) |
---|
277 | n/a | |
---|
278 | n/a | # ======================= |
---|
279 | n/a | # Help-formatting methods |
---|
280 | n/a | # ======================= |
---|
281 | n/a | def format_help(self): |
---|
282 | n/a | help = self._root_section.format_help() |
---|
283 | n/a | if help: |
---|
284 | n/a | help = self._long_break_matcher.sub('\n\n', help) |
---|
285 | n/a | help = help.strip('\n') + '\n' |
---|
286 | n/a | return help |
---|
287 | n/a | |
---|
288 | n/a | def _join_parts(self, part_strings): |
---|
289 | n/a | return ''.join([part |
---|
290 | n/a | for part in part_strings |
---|
291 | n/a | if part and part is not SUPPRESS]) |
---|
292 | n/a | |
---|
293 | n/a | def _format_usage(self, usage, actions, groups, prefix): |
---|
294 | n/a | if prefix is None: |
---|
295 | n/a | prefix = _('usage: ') |
---|
296 | n/a | |
---|
297 | n/a | # if usage is specified, use that |
---|
298 | n/a | if usage is not None: |
---|
299 | n/a | usage = usage % dict(prog=self._prog) |
---|
300 | n/a | |
---|
301 | n/a | # if no optionals or positionals are available, usage is just prog |
---|
302 | n/a | elif usage is None and not actions: |
---|
303 | n/a | usage = '%(prog)s' % dict(prog=self._prog) |
---|
304 | n/a | |
---|
305 | n/a | # if optionals and positionals are available, calculate usage |
---|
306 | n/a | elif usage is None: |
---|
307 | n/a | prog = '%(prog)s' % dict(prog=self._prog) |
---|
308 | n/a | |
---|
309 | n/a | # split optionals from positionals |
---|
310 | n/a | optionals = [] |
---|
311 | n/a | positionals = [] |
---|
312 | n/a | for action in actions: |
---|
313 | n/a | if action.option_strings: |
---|
314 | n/a | optionals.append(action) |
---|
315 | n/a | else: |
---|
316 | n/a | positionals.append(action) |
---|
317 | n/a | |
---|
318 | n/a | # build full usage string |
---|
319 | n/a | format = self._format_actions_usage |
---|
320 | n/a | action_usage = format(optionals + positionals, groups) |
---|
321 | n/a | usage = ' '.join([s for s in [prog, action_usage] if s]) |
---|
322 | n/a | |
---|
323 | n/a | # wrap the usage parts if it's too long |
---|
324 | n/a | text_width = self._width - self._current_indent |
---|
325 | n/a | if len(prefix) + len(usage) > text_width: |
---|
326 | n/a | |
---|
327 | n/a | # break usage into wrappable parts |
---|
328 | n/a | part_regexp = r'\(.*?\)+|\[.*?\]+|\S+' |
---|
329 | n/a | opt_usage = format(optionals, groups) |
---|
330 | n/a | pos_usage = format(positionals, groups) |
---|
331 | n/a | opt_parts = _re.findall(part_regexp, opt_usage) |
---|
332 | n/a | pos_parts = _re.findall(part_regexp, pos_usage) |
---|
333 | n/a | assert ' '.join(opt_parts) == opt_usage |
---|
334 | n/a | assert ' '.join(pos_parts) == pos_usage |
---|
335 | n/a | |
---|
336 | n/a | # helper for wrapping lines |
---|
337 | n/a | def get_lines(parts, indent, prefix=None): |
---|
338 | n/a | lines = [] |
---|
339 | n/a | line = [] |
---|
340 | n/a | if prefix is not None: |
---|
341 | n/a | line_len = len(prefix) - 1 |
---|
342 | n/a | else: |
---|
343 | n/a | line_len = len(indent) - 1 |
---|
344 | n/a | for part in parts: |
---|
345 | n/a | if line_len + 1 + len(part) > text_width and line: |
---|
346 | n/a | lines.append(indent + ' '.join(line)) |
---|
347 | n/a | line = [] |
---|
348 | n/a | line_len = len(indent) - 1 |
---|
349 | n/a | line.append(part) |
---|
350 | n/a | line_len += len(part) + 1 |
---|
351 | n/a | if line: |
---|
352 | n/a | lines.append(indent + ' '.join(line)) |
---|
353 | n/a | if prefix is not None: |
---|
354 | n/a | lines[0] = lines[0][len(indent):] |
---|
355 | n/a | return lines |
---|
356 | n/a | |
---|
357 | n/a | # if prog is short, follow it with optionals or positionals |
---|
358 | n/a | if len(prefix) + len(prog) <= 0.75 * text_width: |
---|
359 | n/a | indent = ' ' * (len(prefix) + len(prog) + 1) |
---|
360 | n/a | if opt_parts: |
---|
361 | n/a | lines = get_lines([prog] + opt_parts, indent, prefix) |
---|
362 | n/a | lines.extend(get_lines(pos_parts, indent)) |
---|
363 | n/a | elif pos_parts: |
---|
364 | n/a | lines = get_lines([prog] + pos_parts, indent, prefix) |
---|
365 | n/a | else: |
---|
366 | n/a | lines = [prog] |
---|
367 | n/a | |
---|
368 | n/a | # if prog is long, put it on its own line |
---|
369 | n/a | else: |
---|
370 | n/a | indent = ' ' * len(prefix) |
---|
371 | n/a | parts = opt_parts + pos_parts |
---|
372 | n/a | lines = get_lines(parts, indent) |
---|
373 | n/a | if len(lines) > 1: |
---|
374 | n/a | lines = [] |
---|
375 | n/a | lines.extend(get_lines(opt_parts, indent)) |
---|
376 | n/a | lines.extend(get_lines(pos_parts, indent)) |
---|
377 | n/a | lines = [prog] + lines |
---|
378 | n/a | |
---|
379 | n/a | # join lines into usage |
---|
380 | n/a | usage = '\n'.join(lines) |
---|
381 | n/a | |
---|
382 | n/a | # prefix with 'usage:' |
---|
383 | n/a | return '%s%s\n\n' % (prefix, usage) |
---|
384 | n/a | |
---|
385 | n/a | def _format_actions_usage(self, actions, groups): |
---|
386 | n/a | # find group indices and identify actions in groups |
---|
387 | n/a | group_actions = set() |
---|
388 | n/a | inserts = {} |
---|
389 | n/a | for group in groups: |
---|
390 | n/a | try: |
---|
391 | n/a | start = actions.index(group._group_actions[0]) |
---|
392 | n/a | except ValueError: |
---|
393 | n/a | continue |
---|
394 | n/a | else: |
---|
395 | n/a | end = start + len(group._group_actions) |
---|
396 | n/a | if actions[start:end] == group._group_actions: |
---|
397 | n/a | for action in group._group_actions: |
---|
398 | n/a | group_actions.add(action) |
---|
399 | n/a | if not group.required: |
---|
400 | n/a | if start in inserts: |
---|
401 | n/a | inserts[start] += ' [' |
---|
402 | n/a | else: |
---|
403 | n/a | inserts[start] = '[' |
---|
404 | n/a | inserts[end] = ']' |
---|
405 | n/a | else: |
---|
406 | n/a | if start in inserts: |
---|
407 | n/a | inserts[start] += ' (' |
---|
408 | n/a | else: |
---|
409 | n/a | inserts[start] = '(' |
---|
410 | n/a | inserts[end] = ')' |
---|
411 | n/a | for i in range(start + 1, end): |
---|
412 | n/a | inserts[i] = '|' |
---|
413 | n/a | |
---|
414 | n/a | # collect all actions format strings |
---|
415 | n/a | parts = [] |
---|
416 | n/a | for i, action in enumerate(actions): |
---|
417 | n/a | |
---|
418 | n/a | # suppressed arguments are marked with None |
---|
419 | n/a | # remove | separators for suppressed arguments |
---|
420 | n/a | if action.help is SUPPRESS: |
---|
421 | n/a | parts.append(None) |
---|
422 | n/a | if inserts.get(i) == '|': |
---|
423 | n/a | inserts.pop(i) |
---|
424 | n/a | elif inserts.get(i + 1) == '|': |
---|
425 | n/a | inserts.pop(i + 1) |
---|
426 | n/a | |
---|
427 | n/a | # produce all arg strings |
---|
428 | n/a | elif not action.option_strings: |
---|
429 | n/a | default = self._get_default_metavar_for_positional(action) |
---|
430 | n/a | part = self._format_args(action, default) |
---|
431 | n/a | |
---|
432 | n/a | # if it's in a group, strip the outer [] |
---|
433 | n/a | if action in group_actions: |
---|
434 | n/a | if part[0] == '[' and part[-1] == ']': |
---|
435 | n/a | part = part[1:-1] |
---|
436 | n/a | |
---|
437 | n/a | # add the action string to the list |
---|
438 | n/a | parts.append(part) |
---|
439 | n/a | |
---|
440 | n/a | # produce the first way to invoke the option in brackets |
---|
441 | n/a | else: |
---|
442 | n/a | option_string = action.option_strings[0] |
---|
443 | n/a | |
---|
444 | n/a | # if the Optional doesn't take a value, format is: |
---|
445 | n/a | # -s or --long |
---|
446 | n/a | if action.nargs == 0: |
---|
447 | n/a | part = '%s' % option_string |
---|
448 | n/a | |
---|
449 | n/a | # if the Optional takes a value, format is: |
---|
450 | n/a | # -s ARGS or --long ARGS |
---|
451 | n/a | else: |
---|
452 | n/a | default = self._get_default_metavar_for_optional(action) |
---|
453 | n/a | args_string = self._format_args(action, default) |
---|
454 | n/a | part = '%s %s' % (option_string, args_string) |
---|
455 | n/a | |
---|
456 | n/a | # make it look optional if it's not required or in a group |
---|
457 | n/a | if not action.required and action not in group_actions: |
---|
458 | n/a | part = '[%s]' % part |
---|
459 | n/a | |
---|
460 | n/a | # add the action string to the list |
---|
461 | n/a | parts.append(part) |
---|
462 | n/a | |
---|
463 | n/a | # insert things at the necessary indices |
---|
464 | n/a | for i in sorted(inserts, reverse=True): |
---|
465 | n/a | parts[i:i] = [inserts[i]] |
---|
466 | n/a | |
---|
467 | n/a | # join all the action items with spaces |
---|
468 | n/a | text = ' '.join([item for item in parts if item is not None]) |
---|
469 | n/a | |
---|
470 | n/a | # clean up separators for mutually exclusive groups |
---|
471 | n/a | open = r'[\[(]' |
---|
472 | n/a | close = r'[\])]' |
---|
473 | n/a | text = _re.sub(r'(%s) ' % open, r'\1', text) |
---|
474 | n/a | text = _re.sub(r' (%s)' % close, r'\1', text) |
---|
475 | n/a | text = _re.sub(r'%s *%s' % (open, close), r'', text) |
---|
476 | n/a | text = _re.sub(r'\(([^|]*)\)', r'\1', text) |
---|
477 | n/a | text = text.strip() |
---|
478 | n/a | |
---|
479 | n/a | # return the text |
---|
480 | n/a | return text |
---|
481 | n/a | |
---|
482 | n/a | def _format_text(self, text): |
---|
483 | n/a | if '%(prog)' in text: |
---|
484 | n/a | text = text % dict(prog=self._prog) |
---|
485 | n/a | text_width = max(self._width - self._current_indent, 11) |
---|
486 | n/a | indent = ' ' * self._current_indent |
---|
487 | n/a | return self._fill_text(text, text_width, indent) + '\n\n' |
---|
488 | n/a | |
---|
489 | n/a | def _format_action(self, action): |
---|
490 | n/a | # determine the required width and the entry label |
---|
491 | n/a | help_position = min(self._action_max_length + 2, |
---|
492 | n/a | self._max_help_position) |
---|
493 | n/a | help_width = max(self._width - help_position, 11) |
---|
494 | n/a | action_width = help_position - self._current_indent - 2 |
---|
495 | n/a | action_header = self._format_action_invocation(action) |
---|
496 | n/a | |
---|
497 | n/a | # no help; start on same line and add a final newline |
---|
498 | n/a | if not action.help: |
---|
499 | n/a | tup = self._current_indent, '', action_header |
---|
500 | n/a | action_header = '%*s%s\n' % tup |
---|
501 | n/a | |
---|
502 | n/a | # short action name; start on the same line and pad two spaces |
---|
503 | n/a | elif len(action_header) <= action_width: |
---|
504 | n/a | tup = self._current_indent, '', action_width, action_header |
---|
505 | n/a | action_header = '%*s%-*s ' % tup |
---|
506 | n/a | indent_first = 0 |
---|
507 | n/a | |
---|
508 | n/a | # long action name; start on the next line |
---|
509 | n/a | else: |
---|
510 | n/a | tup = self._current_indent, '', action_header |
---|
511 | n/a | action_header = '%*s%s\n' % tup |
---|
512 | n/a | indent_first = help_position |
---|
513 | n/a | |
---|
514 | n/a | # collect the pieces of the action help |
---|
515 | n/a | parts = [action_header] |
---|
516 | n/a | |
---|
517 | n/a | # if there was help for the action, add lines of help text |
---|
518 | n/a | if action.help: |
---|
519 | n/a | help_text = self._expand_help(action) |
---|
520 | n/a | help_lines = self._split_lines(help_text, help_width) |
---|
521 | n/a | parts.append('%*s%s\n' % (indent_first, '', help_lines[0])) |
---|
522 | n/a | for line in help_lines[1:]: |
---|
523 | n/a | parts.append('%*s%s\n' % (help_position, '', line)) |
---|
524 | n/a | |
---|
525 | n/a | # or add a newline if the description doesn't end with one |
---|
526 | n/a | elif not action_header.endswith('\n'): |
---|
527 | n/a | parts.append('\n') |
---|
528 | n/a | |
---|
529 | n/a | # if there are any sub-actions, add their help as well |
---|
530 | n/a | for subaction in self._iter_indented_subactions(action): |
---|
531 | n/a | parts.append(self._format_action(subaction)) |
---|
532 | n/a | |
---|
533 | n/a | # return a single string |
---|
534 | n/a | return self._join_parts(parts) |
---|
535 | n/a | |
---|
536 | n/a | def _format_action_invocation(self, action): |
---|
537 | n/a | if not action.option_strings: |
---|
538 | n/a | default = self._get_default_metavar_for_positional(action) |
---|
539 | n/a | metavar, = self._metavar_formatter(action, default)(1) |
---|
540 | n/a | return metavar |
---|
541 | n/a | |
---|
542 | n/a | else: |
---|
543 | n/a | parts = [] |
---|
544 | n/a | |
---|
545 | n/a | # if the Optional doesn't take a value, format is: |
---|
546 | n/a | # -s, --long |
---|
547 | n/a | if action.nargs == 0: |
---|
548 | n/a | parts.extend(action.option_strings) |
---|
549 | n/a | |
---|
550 | n/a | # if the Optional takes a value, format is: |
---|
551 | n/a | # -s ARGS, --long ARGS |
---|
552 | n/a | else: |
---|
553 | n/a | default = self._get_default_metavar_for_optional(action) |
---|
554 | n/a | args_string = self._format_args(action, default) |
---|
555 | n/a | for option_string in action.option_strings: |
---|
556 | n/a | parts.append('%s %s' % (option_string, args_string)) |
---|
557 | n/a | |
---|
558 | n/a | return ', '.join(parts) |
---|
559 | n/a | |
---|
560 | n/a | def _metavar_formatter(self, action, default_metavar): |
---|
561 | n/a | if action.metavar is not None: |
---|
562 | n/a | result = action.metavar |
---|
563 | n/a | elif action.choices is not None: |
---|
564 | n/a | choice_strs = [str(choice) for choice in action.choices] |
---|
565 | n/a | result = '{%s}' % ','.join(choice_strs) |
---|
566 | n/a | else: |
---|
567 | n/a | result = default_metavar |
---|
568 | n/a | |
---|
569 | n/a | def format(tuple_size): |
---|
570 | n/a | if isinstance(result, tuple): |
---|
571 | n/a | return result |
---|
572 | n/a | else: |
---|
573 | n/a | return (result, ) * tuple_size |
---|
574 | n/a | return format |
---|
575 | n/a | |
---|
576 | n/a | def _format_args(self, action, default_metavar): |
---|
577 | n/a | get_metavar = self._metavar_formatter(action, default_metavar) |
---|
578 | n/a | if action.nargs is None: |
---|
579 | n/a | result = '%s' % get_metavar(1) |
---|
580 | n/a | elif action.nargs == OPTIONAL: |
---|
581 | n/a | result = '[%s]' % get_metavar(1) |
---|
582 | n/a | elif action.nargs == ZERO_OR_MORE: |
---|
583 | n/a | result = '[%s [%s ...]]' % get_metavar(2) |
---|
584 | n/a | elif action.nargs == ONE_OR_MORE: |
---|
585 | n/a | result = '%s [%s ...]' % get_metavar(2) |
---|
586 | n/a | elif action.nargs == REMAINDER: |
---|
587 | n/a | result = '...' |
---|
588 | n/a | elif action.nargs == PARSER: |
---|
589 | n/a | result = '%s ...' % get_metavar(1) |
---|
590 | n/a | else: |
---|
591 | n/a | formats = ['%s' for _ in range(action.nargs)] |
---|
592 | n/a | result = ' '.join(formats) % get_metavar(action.nargs) |
---|
593 | n/a | return result |
---|
594 | n/a | |
---|
595 | n/a | def _expand_help(self, action): |
---|
596 | n/a | params = dict(vars(action), prog=self._prog) |
---|
597 | n/a | for name in list(params): |
---|
598 | n/a | if params[name] is SUPPRESS: |
---|
599 | n/a | del params[name] |
---|
600 | n/a | for name in list(params): |
---|
601 | n/a | if hasattr(params[name], '__name__'): |
---|
602 | n/a | params[name] = params[name].__name__ |
---|
603 | n/a | if params.get('choices') is not None: |
---|
604 | n/a | choices_str = ', '.join([str(c) for c in params['choices']]) |
---|
605 | n/a | params['choices'] = choices_str |
---|
606 | n/a | return self._get_help_string(action) % params |
---|
607 | n/a | |
---|
608 | n/a | def _iter_indented_subactions(self, action): |
---|
609 | n/a | try: |
---|
610 | n/a | get_subactions = action._get_subactions |
---|
611 | n/a | except AttributeError: |
---|
612 | n/a | pass |
---|
613 | n/a | else: |
---|
614 | n/a | self._indent() |
---|
615 | n/a | yield from get_subactions() |
---|
616 | n/a | self._dedent() |
---|
617 | n/a | |
---|
618 | n/a | def _split_lines(self, text, width): |
---|
619 | n/a | text = self._whitespace_matcher.sub(' ', text).strip() |
---|
620 | n/a | return _textwrap.wrap(text, width) |
---|
621 | n/a | |
---|
622 | n/a | def _fill_text(self, text, width, indent): |
---|
623 | n/a | text = self._whitespace_matcher.sub(' ', text).strip() |
---|
624 | n/a | return _textwrap.fill(text, width, initial_indent=indent, |
---|
625 | n/a | subsequent_indent=indent) |
---|
626 | n/a | |
---|
627 | n/a | def _get_help_string(self, action): |
---|
628 | n/a | return action.help |
---|
629 | n/a | |
---|
630 | n/a | def _get_default_metavar_for_optional(self, action): |
---|
631 | n/a | return action.dest.upper() |
---|
632 | n/a | |
---|
633 | n/a | def _get_default_metavar_for_positional(self, action): |
---|
634 | n/a | return action.dest |
---|
635 | n/a | |
---|
636 | n/a | |
---|
637 | n/a | class RawDescriptionHelpFormatter(HelpFormatter): |
---|
638 | n/a | """Help message formatter which retains any formatting in descriptions. |
---|
639 | n/a | |
---|
640 | n/a | Only the name of this class is considered a public API. All the methods |
---|
641 | n/a | provided by the class are considered an implementation detail. |
---|
642 | n/a | """ |
---|
643 | n/a | |
---|
644 | n/a | def _fill_text(self, text, width, indent): |
---|
645 | n/a | return ''.join(indent + line for line in text.splitlines(keepends=True)) |
---|
646 | n/a | |
---|
647 | n/a | |
---|
648 | n/a | class RawTextHelpFormatter(RawDescriptionHelpFormatter): |
---|
649 | n/a | """Help message formatter which retains formatting of all help text. |
---|
650 | n/a | |
---|
651 | n/a | Only the name of this class is considered a public API. All the methods |
---|
652 | n/a | provided by the class are considered an implementation detail. |
---|
653 | n/a | """ |
---|
654 | n/a | |
---|
655 | n/a | def _split_lines(self, text, width): |
---|
656 | n/a | return text.splitlines() |
---|
657 | n/a | |
---|
658 | n/a | |
---|
659 | n/a | class ArgumentDefaultsHelpFormatter(HelpFormatter): |
---|
660 | n/a | """Help message formatter which adds default values to argument help. |
---|
661 | n/a | |
---|
662 | n/a | Only the name of this class is considered a public API. All the methods |
---|
663 | n/a | provided by the class are considered an implementation detail. |
---|
664 | n/a | """ |
---|
665 | n/a | |
---|
666 | n/a | def _get_help_string(self, action): |
---|
667 | n/a | help = action.help |
---|
668 | n/a | if '%(default)' not in action.help: |
---|
669 | n/a | if action.default is not SUPPRESS: |
---|
670 | n/a | defaulting_nargs = [OPTIONAL, ZERO_OR_MORE] |
---|
671 | n/a | if action.option_strings or action.nargs in defaulting_nargs: |
---|
672 | n/a | help += ' (default: %(default)s)' |
---|
673 | n/a | return help |
---|
674 | n/a | |
---|
675 | n/a | |
---|
676 | n/a | class MetavarTypeHelpFormatter(HelpFormatter): |
---|
677 | n/a | """Help message formatter which uses the argument 'type' as the default |
---|
678 | n/a | metavar value (instead of the argument 'dest') |
---|
679 | n/a | |
---|
680 | n/a | Only the name of this class is considered a public API. All the methods |
---|
681 | n/a | provided by the class are considered an implementation detail. |
---|
682 | n/a | """ |
---|
683 | n/a | |
---|
684 | n/a | def _get_default_metavar_for_optional(self, action): |
---|
685 | n/a | return action.type.__name__ |
---|
686 | n/a | |
---|
687 | n/a | def _get_default_metavar_for_positional(self, action): |
---|
688 | n/a | return action.type.__name__ |
---|
689 | n/a | |
---|
690 | n/a | |
---|
691 | n/a | |
---|
692 | n/a | # ===================== |
---|
693 | n/a | # Options and Arguments |
---|
694 | n/a | # ===================== |
---|
695 | n/a | |
---|
696 | n/a | def _get_action_name(argument): |
---|
697 | n/a | if argument is None: |
---|
698 | n/a | return None |
---|
699 | n/a | elif argument.option_strings: |
---|
700 | n/a | return '/'.join(argument.option_strings) |
---|
701 | n/a | elif argument.metavar not in (None, SUPPRESS): |
---|
702 | n/a | return argument.metavar |
---|
703 | n/a | elif argument.dest not in (None, SUPPRESS): |
---|
704 | n/a | return argument.dest |
---|
705 | n/a | else: |
---|
706 | n/a | return None |
---|
707 | n/a | |
---|
708 | n/a | |
---|
709 | n/a | class ArgumentError(Exception): |
---|
710 | n/a | """An error from creating or using an argument (optional or positional). |
---|
711 | n/a | |
---|
712 | n/a | The string value of this exception is the message, augmented with |
---|
713 | n/a | information about the argument that caused it. |
---|
714 | n/a | """ |
---|
715 | n/a | |
---|
716 | n/a | def __init__(self, argument, message): |
---|
717 | n/a | self.argument_name = _get_action_name(argument) |
---|
718 | n/a | self.message = message |
---|
719 | n/a | |
---|
720 | n/a | def __str__(self): |
---|
721 | n/a | if self.argument_name is None: |
---|
722 | n/a | format = '%(message)s' |
---|
723 | n/a | else: |
---|
724 | n/a | format = 'argument %(argument_name)s: %(message)s' |
---|
725 | n/a | return format % dict(message=self.message, |
---|
726 | n/a | argument_name=self.argument_name) |
---|
727 | n/a | |
---|
728 | n/a | |
---|
729 | n/a | class ArgumentTypeError(Exception): |
---|
730 | n/a | """An error from trying to convert a command line string to a type.""" |
---|
731 | n/a | pass |
---|
732 | n/a | |
---|
733 | n/a | |
---|
734 | n/a | # ============== |
---|
735 | n/a | # Action classes |
---|
736 | n/a | # ============== |
---|
737 | n/a | |
---|
738 | n/a | class Action(_AttributeHolder): |
---|
739 | n/a | """Information about how to convert command line strings to Python objects. |
---|
740 | n/a | |
---|
741 | n/a | Action objects are used by an ArgumentParser to represent the information |
---|
742 | n/a | needed to parse a single argument from one or more strings from the |
---|
743 | n/a | command line. The keyword arguments to the Action constructor are also |
---|
744 | n/a | all attributes of Action instances. |
---|
745 | n/a | |
---|
746 | n/a | Keyword Arguments: |
---|
747 | n/a | |
---|
748 | n/a | - option_strings -- A list of command-line option strings which |
---|
749 | n/a | should be associated with this action. |
---|
750 | n/a | |
---|
751 | n/a | - dest -- The name of the attribute to hold the created object(s) |
---|
752 | n/a | |
---|
753 | n/a | - nargs -- The number of command-line arguments that should be |
---|
754 | n/a | consumed. By default, one argument will be consumed and a single |
---|
755 | n/a | value will be produced. Other values include: |
---|
756 | n/a | - N (an integer) consumes N arguments (and produces a list) |
---|
757 | n/a | - '?' consumes zero or one arguments |
---|
758 | n/a | - '*' consumes zero or more arguments (and produces a list) |
---|
759 | n/a | - '+' consumes one or more arguments (and produces a list) |
---|
760 | n/a | Note that the difference between the default and nargs=1 is that |
---|
761 | n/a | with the default, a single value will be produced, while with |
---|
762 | n/a | nargs=1, a list containing a single value will be produced. |
---|
763 | n/a | |
---|
764 | n/a | - const -- The value to be produced if the option is specified and the |
---|
765 | n/a | option uses an action that takes no values. |
---|
766 | n/a | |
---|
767 | n/a | - default -- The value to be produced if the option is not specified. |
---|
768 | n/a | |
---|
769 | n/a | - type -- A callable that accepts a single string argument, and |
---|
770 | n/a | returns the converted value. The standard Python types str, int, |
---|
771 | n/a | float, and complex are useful examples of such callables. If None, |
---|
772 | n/a | str is used. |
---|
773 | n/a | |
---|
774 | n/a | - choices -- A container of values that should be allowed. If not None, |
---|
775 | n/a | after a command-line argument has been converted to the appropriate |
---|
776 | n/a | type, an exception will be raised if it is not a member of this |
---|
777 | n/a | collection. |
---|
778 | n/a | |
---|
779 | n/a | - required -- True if the action must always be specified at the |
---|
780 | n/a | command line. This is only meaningful for optional command-line |
---|
781 | n/a | arguments. |
---|
782 | n/a | |
---|
783 | n/a | - help -- The help string describing the argument. |
---|
784 | n/a | |
---|
785 | n/a | - metavar -- The name to be used for the option's argument with the |
---|
786 | n/a | help string. If None, the 'dest' value will be used as the name. |
---|
787 | n/a | """ |
---|
788 | n/a | |
---|
789 | n/a | def __init__(self, |
---|
790 | n/a | option_strings, |
---|
791 | n/a | dest, |
---|
792 | n/a | nargs=None, |
---|
793 | n/a | const=None, |
---|
794 | n/a | default=None, |
---|
795 | n/a | type=None, |
---|
796 | n/a | choices=None, |
---|
797 | n/a | required=False, |
---|
798 | n/a | help=None, |
---|
799 | n/a | metavar=None): |
---|
800 | n/a | self.option_strings = option_strings |
---|
801 | n/a | self.dest = dest |
---|
802 | n/a | self.nargs = nargs |
---|
803 | n/a | self.const = const |
---|
804 | n/a | self.default = default |
---|
805 | n/a | self.type = type |
---|
806 | n/a | self.choices = choices |
---|
807 | n/a | self.required = required |
---|
808 | n/a | self.help = help |
---|
809 | n/a | self.metavar = metavar |
---|
810 | n/a | |
---|
811 | n/a | def _get_kwargs(self): |
---|
812 | n/a | names = [ |
---|
813 | n/a | 'option_strings', |
---|
814 | n/a | 'dest', |
---|
815 | n/a | 'nargs', |
---|
816 | n/a | 'const', |
---|
817 | n/a | 'default', |
---|
818 | n/a | 'type', |
---|
819 | n/a | 'choices', |
---|
820 | n/a | 'help', |
---|
821 | n/a | 'metavar', |
---|
822 | n/a | ] |
---|
823 | n/a | return [(name, getattr(self, name)) for name in names] |
---|
824 | n/a | |
---|
825 | n/a | def __call__(self, parser, namespace, values, option_string=None): |
---|
826 | n/a | raise NotImplementedError(_('.__call__() not defined')) |
---|
827 | n/a | |
---|
828 | n/a | |
---|
829 | n/a | class _StoreAction(Action): |
---|
830 | n/a | |
---|
831 | n/a | def __init__(self, |
---|
832 | n/a | option_strings, |
---|
833 | n/a | dest, |
---|
834 | n/a | nargs=None, |
---|
835 | n/a | const=None, |
---|
836 | n/a | default=None, |
---|
837 | n/a | type=None, |
---|
838 | n/a | choices=None, |
---|
839 | n/a | required=False, |
---|
840 | n/a | help=None, |
---|
841 | n/a | metavar=None): |
---|
842 | n/a | if nargs == 0: |
---|
843 | n/a | raise ValueError('nargs for store actions must be > 0; if you ' |
---|
844 | n/a | 'have nothing to store, actions such as store ' |
---|
845 | n/a | 'true or store const may be more appropriate') |
---|
846 | n/a | if const is not None and nargs != OPTIONAL: |
---|
847 | n/a | raise ValueError('nargs must be %r to supply const' % OPTIONAL) |
---|
848 | n/a | super(_StoreAction, self).__init__( |
---|
849 | n/a | option_strings=option_strings, |
---|
850 | n/a | dest=dest, |
---|
851 | n/a | nargs=nargs, |
---|
852 | n/a | const=const, |
---|
853 | n/a | default=default, |
---|
854 | n/a | type=type, |
---|
855 | n/a | choices=choices, |
---|
856 | n/a | required=required, |
---|
857 | n/a | help=help, |
---|
858 | n/a | metavar=metavar) |
---|
859 | n/a | |
---|
860 | n/a | def __call__(self, parser, namespace, values, option_string=None): |
---|
861 | n/a | setattr(namespace, self.dest, values) |
---|
862 | n/a | |
---|
863 | n/a | |
---|
864 | n/a | class _StoreConstAction(Action): |
---|
865 | n/a | |
---|
866 | n/a | def __init__(self, |
---|
867 | n/a | option_strings, |
---|
868 | n/a | dest, |
---|
869 | n/a | const, |
---|
870 | n/a | default=None, |
---|
871 | n/a | required=False, |
---|
872 | n/a | help=None, |
---|
873 | n/a | metavar=None): |
---|
874 | n/a | super(_StoreConstAction, self).__init__( |
---|
875 | n/a | option_strings=option_strings, |
---|
876 | n/a | dest=dest, |
---|
877 | n/a | nargs=0, |
---|
878 | n/a | const=const, |
---|
879 | n/a | default=default, |
---|
880 | n/a | required=required, |
---|
881 | n/a | help=help) |
---|
882 | n/a | |
---|
883 | n/a | def __call__(self, parser, namespace, values, option_string=None): |
---|
884 | n/a | setattr(namespace, self.dest, self.const) |
---|
885 | n/a | |
---|
886 | n/a | |
---|
887 | n/a | class _StoreTrueAction(_StoreConstAction): |
---|
888 | n/a | |
---|
889 | n/a | def __init__(self, |
---|
890 | n/a | option_strings, |
---|
891 | n/a | dest, |
---|
892 | n/a | default=False, |
---|
893 | n/a | required=False, |
---|
894 | n/a | help=None): |
---|
895 | n/a | super(_StoreTrueAction, self).__init__( |
---|
896 | n/a | option_strings=option_strings, |
---|
897 | n/a | dest=dest, |
---|
898 | n/a | const=True, |
---|
899 | n/a | default=default, |
---|
900 | n/a | required=required, |
---|
901 | n/a | help=help) |
---|
902 | n/a | |
---|
903 | n/a | |
---|
904 | n/a | class _StoreFalseAction(_StoreConstAction): |
---|
905 | n/a | |
---|
906 | n/a | def __init__(self, |
---|
907 | n/a | option_strings, |
---|
908 | n/a | dest, |
---|
909 | n/a | default=True, |
---|
910 | n/a | required=False, |
---|
911 | n/a | help=None): |
---|
912 | n/a | super(_StoreFalseAction, self).__init__( |
---|
913 | n/a | option_strings=option_strings, |
---|
914 | n/a | dest=dest, |
---|
915 | n/a | const=False, |
---|
916 | n/a | default=default, |
---|
917 | n/a | required=required, |
---|
918 | n/a | help=help) |
---|
919 | n/a | |
---|
920 | n/a | |
---|
921 | n/a | class _AppendAction(Action): |
---|
922 | n/a | |
---|
923 | n/a | def __init__(self, |
---|
924 | n/a | option_strings, |
---|
925 | n/a | dest, |
---|
926 | n/a | nargs=None, |
---|
927 | n/a | const=None, |
---|
928 | n/a | default=None, |
---|
929 | n/a | type=None, |
---|
930 | n/a | choices=None, |
---|
931 | n/a | required=False, |
---|
932 | n/a | help=None, |
---|
933 | n/a | metavar=None): |
---|
934 | n/a | if nargs == 0: |
---|
935 | n/a | raise ValueError('nargs for append actions must be > 0; if arg ' |
---|
936 | n/a | 'strings are not supplying the value to append, ' |
---|
937 | n/a | 'the append const action may be more appropriate') |
---|
938 | n/a | if const is not None and nargs != OPTIONAL: |
---|
939 | n/a | raise ValueError('nargs must be %r to supply const' % OPTIONAL) |
---|
940 | n/a | super(_AppendAction, self).__init__( |
---|
941 | n/a | option_strings=option_strings, |
---|
942 | n/a | dest=dest, |
---|
943 | n/a | nargs=nargs, |
---|
944 | n/a | const=const, |
---|
945 | n/a | default=default, |
---|
946 | n/a | type=type, |
---|
947 | n/a | choices=choices, |
---|
948 | n/a | required=required, |
---|
949 | n/a | help=help, |
---|
950 | n/a | metavar=metavar) |
---|
951 | n/a | |
---|
952 | n/a | def __call__(self, parser, namespace, values, option_string=None): |
---|
953 | n/a | items = _copy.copy(_ensure_value(namespace, self.dest, [])) |
---|
954 | n/a | items.append(values) |
---|
955 | n/a | setattr(namespace, self.dest, items) |
---|
956 | n/a | |
---|
957 | n/a | |
---|
958 | n/a | class _AppendConstAction(Action): |
---|
959 | n/a | |
---|
960 | n/a | def __init__(self, |
---|
961 | n/a | option_strings, |
---|
962 | n/a | dest, |
---|
963 | n/a | const, |
---|
964 | n/a | default=None, |
---|
965 | n/a | required=False, |
---|
966 | n/a | help=None, |
---|
967 | n/a | metavar=None): |
---|
968 | n/a | super(_AppendConstAction, self).__init__( |
---|
969 | n/a | option_strings=option_strings, |
---|
970 | n/a | dest=dest, |
---|
971 | n/a | nargs=0, |
---|
972 | n/a | const=const, |
---|
973 | n/a | default=default, |
---|
974 | n/a | required=required, |
---|
975 | n/a | help=help, |
---|
976 | n/a | metavar=metavar) |
---|
977 | n/a | |
---|
978 | n/a | def __call__(self, parser, namespace, values, option_string=None): |
---|
979 | n/a | items = _copy.copy(_ensure_value(namespace, self.dest, [])) |
---|
980 | n/a | items.append(self.const) |
---|
981 | n/a | setattr(namespace, self.dest, items) |
---|
982 | n/a | |
---|
983 | n/a | |
---|
984 | n/a | class _CountAction(Action): |
---|
985 | n/a | |
---|
986 | n/a | def __init__(self, |
---|
987 | n/a | option_strings, |
---|
988 | n/a | dest, |
---|
989 | n/a | default=None, |
---|
990 | n/a | required=False, |
---|
991 | n/a | help=None): |
---|
992 | n/a | super(_CountAction, self).__init__( |
---|
993 | n/a | option_strings=option_strings, |
---|
994 | n/a | dest=dest, |
---|
995 | n/a | nargs=0, |
---|
996 | n/a | default=default, |
---|
997 | n/a | required=required, |
---|
998 | n/a | help=help) |
---|
999 | n/a | |
---|
1000 | n/a | def __call__(self, parser, namespace, values, option_string=None): |
---|
1001 | n/a | new_count = _ensure_value(namespace, self.dest, 0) + 1 |
---|
1002 | n/a | setattr(namespace, self.dest, new_count) |
---|
1003 | n/a | |
---|
1004 | n/a | |
---|
1005 | n/a | class _HelpAction(Action): |
---|
1006 | n/a | |
---|
1007 | n/a | def __init__(self, |
---|
1008 | n/a | option_strings, |
---|
1009 | n/a | dest=SUPPRESS, |
---|
1010 | n/a | default=SUPPRESS, |
---|
1011 | n/a | help=None): |
---|
1012 | n/a | super(_HelpAction, self).__init__( |
---|
1013 | n/a | option_strings=option_strings, |
---|
1014 | n/a | dest=dest, |
---|
1015 | n/a | default=default, |
---|
1016 | n/a | nargs=0, |
---|
1017 | n/a | help=help) |
---|
1018 | n/a | |
---|
1019 | n/a | def __call__(self, parser, namespace, values, option_string=None): |
---|
1020 | n/a | parser.print_help() |
---|
1021 | n/a | parser.exit() |
---|
1022 | n/a | |
---|
1023 | n/a | |
---|
1024 | n/a | class _VersionAction(Action): |
---|
1025 | n/a | |
---|
1026 | n/a | def __init__(self, |
---|
1027 | n/a | option_strings, |
---|
1028 | n/a | version=None, |
---|
1029 | n/a | dest=SUPPRESS, |
---|
1030 | n/a | default=SUPPRESS, |
---|
1031 | n/a | help="show program's version number and exit"): |
---|
1032 | n/a | super(_VersionAction, self).__init__( |
---|
1033 | n/a | option_strings=option_strings, |
---|
1034 | n/a | dest=dest, |
---|
1035 | n/a | default=default, |
---|
1036 | n/a | nargs=0, |
---|
1037 | n/a | help=help) |
---|
1038 | n/a | self.version = version |
---|
1039 | n/a | |
---|
1040 | n/a | def __call__(self, parser, namespace, values, option_string=None): |
---|
1041 | n/a | version = self.version |
---|
1042 | n/a | if version is None: |
---|
1043 | n/a | version = parser.version |
---|
1044 | n/a | formatter = parser._get_formatter() |
---|
1045 | n/a | formatter.add_text(version) |
---|
1046 | n/a | parser._print_message(formatter.format_help(), _sys.stdout) |
---|
1047 | n/a | parser.exit() |
---|
1048 | n/a | |
---|
1049 | n/a | |
---|
1050 | n/a | class _SubParsersAction(Action): |
---|
1051 | n/a | |
---|
1052 | n/a | class _ChoicesPseudoAction(Action): |
---|
1053 | n/a | |
---|
1054 | n/a | def __init__(self, name, aliases, help): |
---|
1055 | n/a | metavar = dest = name |
---|
1056 | n/a | if aliases: |
---|
1057 | n/a | metavar += ' (%s)' % ', '.join(aliases) |
---|
1058 | n/a | sup = super(_SubParsersAction._ChoicesPseudoAction, self) |
---|
1059 | n/a | sup.__init__(option_strings=[], dest=dest, help=help, |
---|
1060 | n/a | metavar=metavar) |
---|
1061 | n/a | |
---|
1062 | n/a | def __init__(self, |
---|
1063 | n/a | option_strings, |
---|
1064 | n/a | prog, |
---|
1065 | n/a | parser_class, |
---|
1066 | n/a | dest=SUPPRESS, |
---|
1067 | n/a | help=None, |
---|
1068 | n/a | metavar=None): |
---|
1069 | n/a | |
---|
1070 | n/a | self._prog_prefix = prog |
---|
1071 | n/a | self._parser_class = parser_class |
---|
1072 | n/a | self._name_parser_map = _collections.OrderedDict() |
---|
1073 | n/a | self._choices_actions = [] |
---|
1074 | n/a | |
---|
1075 | n/a | super(_SubParsersAction, self).__init__( |
---|
1076 | n/a | option_strings=option_strings, |
---|
1077 | n/a | dest=dest, |
---|
1078 | n/a | nargs=PARSER, |
---|
1079 | n/a | choices=self._name_parser_map, |
---|
1080 | n/a | help=help, |
---|
1081 | n/a | metavar=metavar) |
---|
1082 | n/a | |
---|
1083 | n/a | def add_parser(self, name, **kwargs): |
---|
1084 | n/a | # set prog from the existing prefix |
---|
1085 | n/a | if kwargs.get('prog') is None: |
---|
1086 | n/a | kwargs['prog'] = '%s %s' % (self._prog_prefix, name) |
---|
1087 | n/a | |
---|
1088 | n/a | aliases = kwargs.pop('aliases', ()) |
---|
1089 | n/a | |
---|
1090 | n/a | # create a pseudo-action to hold the choice help |
---|
1091 | n/a | if 'help' in kwargs: |
---|
1092 | n/a | help = kwargs.pop('help') |
---|
1093 | n/a | choice_action = self._ChoicesPseudoAction(name, aliases, help) |
---|
1094 | n/a | self._choices_actions.append(choice_action) |
---|
1095 | n/a | |
---|
1096 | n/a | # create the parser and add it to the map |
---|
1097 | n/a | parser = self._parser_class(**kwargs) |
---|
1098 | n/a | self._name_parser_map[name] = parser |
---|
1099 | n/a | |
---|
1100 | n/a | # make parser available under aliases also |
---|
1101 | n/a | for alias in aliases: |
---|
1102 | n/a | self._name_parser_map[alias] = parser |
---|
1103 | n/a | |
---|
1104 | n/a | return parser |
---|
1105 | n/a | |
---|
1106 | n/a | def _get_subactions(self): |
---|
1107 | n/a | return self._choices_actions |
---|
1108 | n/a | |
---|
1109 | n/a | def __call__(self, parser, namespace, values, option_string=None): |
---|
1110 | n/a | parser_name = values[0] |
---|
1111 | n/a | arg_strings = values[1:] |
---|
1112 | n/a | |
---|
1113 | n/a | # set the parser name if requested |
---|
1114 | n/a | if self.dest is not SUPPRESS: |
---|
1115 | n/a | setattr(namespace, self.dest, parser_name) |
---|
1116 | n/a | |
---|
1117 | n/a | # select the parser |
---|
1118 | n/a | try: |
---|
1119 | n/a | parser = self._name_parser_map[parser_name] |
---|
1120 | n/a | except KeyError: |
---|
1121 | n/a | args = {'parser_name': parser_name, |
---|
1122 | n/a | 'choices': ', '.join(self._name_parser_map)} |
---|
1123 | n/a | msg = _('unknown parser %(parser_name)r (choices: %(choices)s)') % args |
---|
1124 | n/a | raise ArgumentError(self, msg) |
---|
1125 | n/a | |
---|
1126 | n/a | # parse all the remaining options into the namespace |
---|
1127 | n/a | # store any unrecognized options on the object, so that the top |
---|
1128 | n/a | # level parser can decide what to do with them |
---|
1129 | n/a | |
---|
1130 | n/a | # In case this subparser defines new defaults, we parse them |
---|
1131 | n/a | # in a new namespace object and then update the original |
---|
1132 | n/a | # namespace for the relevant parts. |
---|
1133 | n/a | subnamespace, arg_strings = parser.parse_known_args(arg_strings, None) |
---|
1134 | n/a | for key, value in vars(subnamespace).items(): |
---|
1135 | n/a | setattr(namespace, key, value) |
---|
1136 | n/a | |
---|
1137 | n/a | if arg_strings: |
---|
1138 | n/a | vars(namespace).setdefault(_UNRECOGNIZED_ARGS_ATTR, []) |
---|
1139 | n/a | getattr(namespace, _UNRECOGNIZED_ARGS_ATTR).extend(arg_strings) |
---|
1140 | n/a | |
---|
1141 | n/a | |
---|
1142 | n/a | # ============== |
---|
1143 | n/a | # Type classes |
---|
1144 | n/a | # ============== |
---|
1145 | n/a | |
---|
1146 | n/a | class FileType(object): |
---|
1147 | n/a | """Factory for creating file object types |
---|
1148 | n/a | |
---|
1149 | n/a | Instances of FileType are typically passed as type= arguments to the |
---|
1150 | n/a | ArgumentParser add_argument() method. |
---|
1151 | n/a | |
---|
1152 | n/a | Keyword Arguments: |
---|
1153 | n/a | - mode -- A string indicating how the file is to be opened. Accepts the |
---|
1154 | n/a | same values as the builtin open() function. |
---|
1155 | n/a | - bufsize -- The file's desired buffer size. Accepts the same values as |
---|
1156 | n/a | the builtin open() function. |
---|
1157 | n/a | - encoding -- The file's encoding. Accepts the same values as the |
---|
1158 | n/a | builtin open() function. |
---|
1159 | n/a | - errors -- A string indicating how encoding and decoding errors are to |
---|
1160 | n/a | be handled. Accepts the same value as the builtin open() function. |
---|
1161 | n/a | """ |
---|
1162 | n/a | |
---|
1163 | n/a | def __init__(self, mode='r', bufsize=-1, encoding=None, errors=None): |
---|
1164 | n/a | self._mode = mode |
---|
1165 | n/a | self._bufsize = bufsize |
---|
1166 | n/a | self._encoding = encoding |
---|
1167 | n/a | self._errors = errors |
---|
1168 | n/a | |
---|
1169 | n/a | def __call__(self, string): |
---|
1170 | n/a | # the special argument "-" means sys.std{in,out} |
---|
1171 | n/a | if string == '-': |
---|
1172 | n/a | if 'r' in self._mode: |
---|
1173 | n/a | return _sys.stdin |
---|
1174 | n/a | elif 'w' in self._mode: |
---|
1175 | n/a | return _sys.stdout |
---|
1176 | n/a | else: |
---|
1177 | n/a | msg = _('argument "-" with mode %r') % self._mode |
---|
1178 | n/a | raise ValueError(msg) |
---|
1179 | n/a | |
---|
1180 | n/a | # all other arguments are used as file names |
---|
1181 | n/a | try: |
---|
1182 | n/a | return open(string, self._mode, self._bufsize, self._encoding, |
---|
1183 | n/a | self._errors) |
---|
1184 | n/a | except OSError as e: |
---|
1185 | n/a | message = _("can't open '%s': %s") |
---|
1186 | n/a | raise ArgumentTypeError(message % (string, e)) |
---|
1187 | n/a | |
---|
1188 | n/a | def __repr__(self): |
---|
1189 | n/a | args = self._mode, self._bufsize |
---|
1190 | n/a | kwargs = [('encoding', self._encoding), ('errors', self._errors)] |
---|
1191 | n/a | args_str = ', '.join([repr(arg) for arg in args if arg != -1] + |
---|
1192 | n/a | ['%s=%r' % (kw, arg) for kw, arg in kwargs |
---|
1193 | n/a | if arg is not None]) |
---|
1194 | n/a | return '%s(%s)' % (type(self).__name__, args_str) |
---|
1195 | n/a | |
---|
1196 | n/a | # =========================== |
---|
1197 | n/a | # Optional and Positional Parsing |
---|
1198 | n/a | # =========================== |
---|
1199 | n/a | |
---|
1200 | n/a | class Namespace(_AttributeHolder): |
---|
1201 | n/a | """Simple object for storing attributes. |
---|
1202 | n/a | |
---|
1203 | n/a | Implements equality by attribute names and values, and provides a simple |
---|
1204 | n/a | string representation. |
---|
1205 | n/a | """ |
---|
1206 | n/a | |
---|
1207 | n/a | def __init__(self, **kwargs): |
---|
1208 | n/a | for name in kwargs: |
---|
1209 | n/a | setattr(self, name, kwargs[name]) |
---|
1210 | n/a | |
---|
1211 | n/a | def __eq__(self, other): |
---|
1212 | n/a | if not isinstance(other, Namespace): |
---|
1213 | n/a | return NotImplemented |
---|
1214 | n/a | return vars(self) == vars(other) |
---|
1215 | n/a | |
---|
1216 | n/a | def __contains__(self, key): |
---|
1217 | n/a | return key in self.__dict__ |
---|
1218 | n/a | |
---|
1219 | n/a | |
---|
1220 | n/a | class _ActionsContainer(object): |
---|
1221 | n/a | |
---|
1222 | n/a | def __init__(self, |
---|
1223 | n/a | description, |
---|
1224 | n/a | prefix_chars, |
---|
1225 | n/a | argument_default, |
---|
1226 | n/a | conflict_handler): |
---|
1227 | n/a | super(_ActionsContainer, self).__init__() |
---|
1228 | n/a | |
---|
1229 | n/a | self.description = description |
---|
1230 | n/a | self.argument_default = argument_default |
---|
1231 | n/a | self.prefix_chars = prefix_chars |
---|
1232 | n/a | self.conflict_handler = conflict_handler |
---|
1233 | n/a | |
---|
1234 | n/a | # set up registries |
---|
1235 | n/a | self._registries = {} |
---|
1236 | n/a | |
---|
1237 | n/a | # register actions |
---|
1238 | n/a | self.register('action', None, _StoreAction) |
---|
1239 | n/a | self.register('action', 'store', _StoreAction) |
---|
1240 | n/a | self.register('action', 'store_const', _StoreConstAction) |
---|
1241 | n/a | self.register('action', 'store_true', _StoreTrueAction) |
---|
1242 | n/a | self.register('action', 'store_false', _StoreFalseAction) |
---|
1243 | n/a | self.register('action', 'append', _AppendAction) |
---|
1244 | n/a | self.register('action', 'append_const', _AppendConstAction) |
---|
1245 | n/a | self.register('action', 'count', _CountAction) |
---|
1246 | n/a | self.register('action', 'help', _HelpAction) |
---|
1247 | n/a | self.register('action', 'version', _VersionAction) |
---|
1248 | n/a | self.register('action', 'parsers', _SubParsersAction) |
---|
1249 | n/a | |
---|
1250 | n/a | # raise an exception if the conflict handler is invalid |
---|
1251 | n/a | self._get_handler() |
---|
1252 | n/a | |
---|
1253 | n/a | # action storage |
---|
1254 | n/a | self._actions = [] |
---|
1255 | n/a | self._option_string_actions = {} |
---|
1256 | n/a | |
---|
1257 | n/a | # groups |
---|
1258 | n/a | self._action_groups = [] |
---|
1259 | n/a | self._mutually_exclusive_groups = [] |
---|
1260 | n/a | |
---|
1261 | n/a | # defaults storage |
---|
1262 | n/a | self._defaults = {} |
---|
1263 | n/a | |
---|
1264 | n/a | # determines whether an "option" looks like a negative number |
---|
1265 | n/a | self._negative_number_matcher = _re.compile(r'^-\d+$|^-\d*\.\d+$') |
---|
1266 | n/a | |
---|
1267 | n/a | # whether or not there are any optionals that look like negative |
---|
1268 | n/a | # numbers -- uses a list so it can be shared and edited |
---|
1269 | n/a | self._has_negative_number_optionals = [] |
---|
1270 | n/a | |
---|
1271 | n/a | # ==================== |
---|
1272 | n/a | # Registration methods |
---|
1273 | n/a | # ==================== |
---|
1274 | n/a | def register(self, registry_name, value, object): |
---|
1275 | n/a | registry = self._registries.setdefault(registry_name, {}) |
---|
1276 | n/a | registry[value] = object |
---|
1277 | n/a | |
---|
1278 | n/a | def _registry_get(self, registry_name, value, default=None): |
---|
1279 | n/a | return self._registries[registry_name].get(value, default) |
---|
1280 | n/a | |
---|
1281 | n/a | # ================================== |
---|
1282 | n/a | # Namespace default accessor methods |
---|
1283 | n/a | # ================================== |
---|
1284 | n/a | def set_defaults(self, **kwargs): |
---|
1285 | n/a | self._defaults.update(kwargs) |
---|
1286 | n/a | |
---|
1287 | n/a | # if these defaults match any existing arguments, replace |
---|
1288 | n/a | # the previous default on the object with the new one |
---|
1289 | n/a | for action in self._actions: |
---|
1290 | n/a | if action.dest in kwargs: |
---|
1291 | n/a | action.default = kwargs[action.dest] |
---|
1292 | n/a | |
---|
1293 | n/a | def get_default(self, dest): |
---|
1294 | n/a | for action in self._actions: |
---|
1295 | n/a | if action.dest == dest and action.default is not None: |
---|
1296 | n/a | return action.default |
---|
1297 | n/a | return self._defaults.get(dest, None) |
---|
1298 | n/a | |
---|
1299 | n/a | |
---|
1300 | n/a | # ======================= |
---|
1301 | n/a | # Adding argument actions |
---|
1302 | n/a | # ======================= |
---|
1303 | n/a | def add_argument(self, *args, **kwargs): |
---|
1304 | n/a | """ |
---|
1305 | n/a | add_argument(dest, ..., name=value, ...) |
---|
1306 | n/a | add_argument(option_string, option_string, ..., name=value, ...) |
---|
1307 | n/a | """ |
---|
1308 | n/a | |
---|
1309 | n/a | # if no positional args are supplied or only one is supplied and |
---|
1310 | n/a | # it doesn't look like an option string, parse a positional |
---|
1311 | n/a | # argument |
---|
1312 | n/a | chars = self.prefix_chars |
---|
1313 | n/a | if not args or len(args) == 1 and args[0][0] not in chars: |
---|
1314 | n/a | if args and 'dest' in kwargs: |
---|
1315 | n/a | raise ValueError('dest supplied twice for positional argument') |
---|
1316 | n/a | kwargs = self._get_positional_kwargs(*args, **kwargs) |
---|
1317 | n/a | |
---|
1318 | n/a | # otherwise, we're adding an optional argument |
---|
1319 | n/a | else: |
---|
1320 | n/a | kwargs = self._get_optional_kwargs(*args, **kwargs) |
---|
1321 | n/a | |
---|
1322 | n/a | # if no default was supplied, use the parser-level default |
---|
1323 | n/a | if 'default' not in kwargs: |
---|
1324 | n/a | dest = kwargs['dest'] |
---|
1325 | n/a | if dest in self._defaults: |
---|
1326 | n/a | kwargs['default'] = self._defaults[dest] |
---|
1327 | n/a | elif self.argument_default is not None: |
---|
1328 | n/a | kwargs['default'] = self.argument_default |
---|
1329 | n/a | |
---|
1330 | n/a | # create the action object, and add it to the parser |
---|
1331 | n/a | action_class = self._pop_action_class(kwargs) |
---|
1332 | n/a | if not callable(action_class): |
---|
1333 | n/a | raise ValueError('unknown action "%s"' % (action_class,)) |
---|
1334 | n/a | action = action_class(**kwargs) |
---|
1335 | n/a | |
---|
1336 | n/a | # raise an error if the action type is not callable |
---|
1337 | n/a | type_func = self._registry_get('type', action.type, action.type) |
---|
1338 | n/a | if not callable(type_func): |
---|
1339 | n/a | raise ValueError('%r is not callable' % (type_func,)) |
---|
1340 | n/a | |
---|
1341 | n/a | # raise an error if the metavar does not match the type |
---|
1342 | n/a | if hasattr(self, "_get_formatter"): |
---|
1343 | n/a | try: |
---|
1344 | n/a | self._get_formatter()._format_args(action, None) |
---|
1345 | n/a | except TypeError: |
---|
1346 | n/a | raise ValueError("length of metavar tuple does not match nargs") |
---|
1347 | n/a | |
---|
1348 | n/a | return self._add_action(action) |
---|
1349 | n/a | |
---|
1350 | n/a | def add_argument_group(self, *args, **kwargs): |
---|
1351 | n/a | group = _ArgumentGroup(self, *args, **kwargs) |
---|
1352 | n/a | self._action_groups.append(group) |
---|
1353 | n/a | return group |
---|
1354 | n/a | |
---|
1355 | n/a | def add_mutually_exclusive_group(self, **kwargs): |
---|
1356 | n/a | group = _MutuallyExclusiveGroup(self, **kwargs) |
---|
1357 | n/a | self._mutually_exclusive_groups.append(group) |
---|
1358 | n/a | return group |
---|
1359 | n/a | |
---|
1360 | n/a | def _add_action(self, action): |
---|
1361 | n/a | # resolve any conflicts |
---|
1362 | n/a | self._check_conflict(action) |
---|
1363 | n/a | |
---|
1364 | n/a | # add to actions list |
---|
1365 | n/a | self._actions.append(action) |
---|
1366 | n/a | action.container = self |
---|
1367 | n/a | |
---|
1368 | n/a | # index the action by any option strings it has |
---|
1369 | n/a | for option_string in action.option_strings: |
---|
1370 | n/a | self._option_string_actions[option_string] = action |
---|
1371 | n/a | |
---|
1372 | n/a | # set the flag if any option strings look like negative numbers |
---|
1373 | n/a | for option_string in action.option_strings: |
---|
1374 | n/a | if self._negative_number_matcher.match(option_string): |
---|
1375 | n/a | if not self._has_negative_number_optionals: |
---|
1376 | n/a | self._has_negative_number_optionals.append(True) |
---|
1377 | n/a | |
---|
1378 | n/a | # return the created action |
---|
1379 | n/a | return action |
---|
1380 | n/a | |
---|
1381 | n/a | def _remove_action(self, action): |
---|
1382 | n/a | self._actions.remove(action) |
---|
1383 | n/a | |
---|
1384 | n/a | def _add_container_actions(self, container): |
---|
1385 | n/a | # collect groups by titles |
---|
1386 | n/a | title_group_map = {} |
---|
1387 | n/a | for group in self._action_groups: |
---|
1388 | n/a | if group.title in title_group_map: |
---|
1389 | n/a | msg = _('cannot merge actions - two groups are named %r') |
---|
1390 | n/a | raise ValueError(msg % (group.title)) |
---|
1391 | n/a | title_group_map[group.title] = group |
---|
1392 | n/a | |
---|
1393 | n/a | # map each action to its group |
---|
1394 | n/a | group_map = {} |
---|
1395 | n/a | for group in container._action_groups: |
---|
1396 | n/a | |
---|
1397 | n/a | # if a group with the title exists, use that, otherwise |
---|
1398 | n/a | # create a new group matching the container's group |
---|
1399 | n/a | if group.title not in title_group_map: |
---|
1400 | n/a | title_group_map[group.title] = self.add_argument_group( |
---|
1401 | n/a | title=group.title, |
---|
1402 | n/a | description=group.description, |
---|
1403 | n/a | conflict_handler=group.conflict_handler) |
---|
1404 | n/a | |
---|
1405 | n/a | # map the actions to their new group |
---|
1406 | n/a | for action in group._group_actions: |
---|
1407 | n/a | group_map[action] = title_group_map[group.title] |
---|
1408 | n/a | |
---|
1409 | n/a | # add container's mutually exclusive groups |
---|
1410 | n/a | # NOTE: if add_mutually_exclusive_group ever gains title= and |
---|
1411 | n/a | # description= then this code will need to be expanded as above |
---|
1412 | n/a | for group in container._mutually_exclusive_groups: |
---|
1413 | n/a | mutex_group = self.add_mutually_exclusive_group( |
---|
1414 | n/a | required=group.required) |
---|
1415 | n/a | |
---|
1416 | n/a | # map the actions to their new mutex group |
---|
1417 | n/a | for action in group._group_actions: |
---|
1418 | n/a | group_map[action] = mutex_group |
---|
1419 | n/a | |
---|
1420 | n/a | # add all actions to this container or their group |
---|
1421 | n/a | for action in container._actions: |
---|
1422 | n/a | group_map.get(action, self)._add_action(action) |
---|
1423 | n/a | |
---|
1424 | n/a | def _get_positional_kwargs(self, dest, **kwargs): |
---|
1425 | n/a | # make sure required is not specified |
---|
1426 | n/a | if 'required' in kwargs: |
---|
1427 | n/a | msg = _("'required' is an invalid argument for positionals") |
---|
1428 | n/a | raise TypeError(msg) |
---|
1429 | n/a | |
---|
1430 | n/a | # mark positional arguments as required if at least one is |
---|
1431 | n/a | # always required |
---|
1432 | n/a | if kwargs.get('nargs') not in [OPTIONAL, ZERO_OR_MORE]: |
---|
1433 | n/a | kwargs['required'] = True |
---|
1434 | n/a | if kwargs.get('nargs') == ZERO_OR_MORE and 'default' not in kwargs: |
---|
1435 | n/a | kwargs['required'] = True |
---|
1436 | n/a | |
---|
1437 | n/a | # return the keyword arguments with no option strings |
---|
1438 | n/a | return dict(kwargs, dest=dest, option_strings=[]) |
---|
1439 | n/a | |
---|
1440 | n/a | def _get_optional_kwargs(self, *args, **kwargs): |
---|
1441 | n/a | # determine short and long option strings |
---|
1442 | n/a | option_strings = [] |
---|
1443 | n/a | long_option_strings = [] |
---|
1444 | n/a | for option_string in args: |
---|
1445 | n/a | # error on strings that don't start with an appropriate prefix |
---|
1446 | n/a | if not option_string[0] in self.prefix_chars: |
---|
1447 | n/a | args = {'option': option_string, |
---|
1448 | n/a | 'prefix_chars': self.prefix_chars} |
---|
1449 | n/a | msg = _('invalid option string %(option)r: ' |
---|
1450 | n/a | 'must start with a character %(prefix_chars)r') |
---|
1451 | n/a | raise ValueError(msg % args) |
---|
1452 | n/a | |
---|
1453 | n/a | # strings starting with two prefix characters are long options |
---|
1454 | n/a | option_strings.append(option_string) |
---|
1455 | n/a | if option_string[0] in self.prefix_chars: |
---|
1456 | n/a | if len(option_string) > 1: |
---|
1457 | n/a | if option_string[1] in self.prefix_chars: |
---|
1458 | n/a | long_option_strings.append(option_string) |
---|
1459 | n/a | |
---|
1460 | n/a | # infer destination, '--foo-bar' -> 'foo_bar' and '-x' -> 'x' |
---|
1461 | n/a | dest = kwargs.pop('dest', None) |
---|
1462 | n/a | if dest is None: |
---|
1463 | n/a | if long_option_strings: |
---|
1464 | n/a | dest_option_string = long_option_strings[0] |
---|
1465 | n/a | else: |
---|
1466 | n/a | dest_option_string = option_strings[0] |
---|
1467 | n/a | dest = dest_option_string.lstrip(self.prefix_chars) |
---|
1468 | n/a | if not dest: |
---|
1469 | n/a | msg = _('dest= is required for options like %r') |
---|
1470 | n/a | raise ValueError(msg % option_string) |
---|
1471 | n/a | dest = dest.replace('-', '_') |
---|
1472 | n/a | |
---|
1473 | n/a | # return the updated keyword arguments |
---|
1474 | n/a | return dict(kwargs, dest=dest, option_strings=option_strings) |
---|
1475 | n/a | |
---|
1476 | n/a | def _pop_action_class(self, kwargs, default=None): |
---|
1477 | n/a | action = kwargs.pop('action', default) |
---|
1478 | n/a | return self._registry_get('action', action, action) |
---|
1479 | n/a | |
---|
1480 | n/a | def _get_handler(self): |
---|
1481 | n/a | # determine function from conflict handler string |
---|
1482 | n/a | handler_func_name = '_handle_conflict_%s' % self.conflict_handler |
---|
1483 | n/a | try: |
---|
1484 | n/a | return getattr(self, handler_func_name) |
---|
1485 | n/a | except AttributeError: |
---|
1486 | n/a | msg = _('invalid conflict_resolution value: %r') |
---|
1487 | n/a | raise ValueError(msg % self.conflict_handler) |
---|
1488 | n/a | |
---|
1489 | n/a | def _check_conflict(self, action): |
---|
1490 | n/a | |
---|
1491 | n/a | # find all options that conflict with this option |
---|
1492 | n/a | confl_optionals = [] |
---|
1493 | n/a | for option_string in action.option_strings: |
---|
1494 | n/a | if option_string in self._option_string_actions: |
---|
1495 | n/a | confl_optional = self._option_string_actions[option_string] |
---|
1496 | n/a | confl_optionals.append((option_string, confl_optional)) |
---|
1497 | n/a | |
---|
1498 | n/a | # resolve any conflicts |
---|
1499 | n/a | if confl_optionals: |
---|
1500 | n/a | conflict_handler = self._get_handler() |
---|
1501 | n/a | conflict_handler(action, confl_optionals) |
---|
1502 | n/a | |
---|
1503 | n/a | def _handle_conflict_error(self, action, conflicting_actions): |
---|
1504 | n/a | message = ngettext('conflicting option string: %s', |
---|
1505 | n/a | 'conflicting option strings: %s', |
---|
1506 | n/a | len(conflicting_actions)) |
---|
1507 | n/a | conflict_string = ', '.join([option_string |
---|
1508 | n/a | for option_string, action |
---|
1509 | n/a | in conflicting_actions]) |
---|
1510 | n/a | raise ArgumentError(action, message % conflict_string) |
---|
1511 | n/a | |
---|
1512 | n/a | def _handle_conflict_resolve(self, action, conflicting_actions): |
---|
1513 | n/a | |
---|
1514 | n/a | # remove all conflicting options |
---|
1515 | n/a | for option_string, action in conflicting_actions: |
---|
1516 | n/a | |
---|
1517 | n/a | # remove the conflicting option |
---|
1518 | n/a | action.option_strings.remove(option_string) |
---|
1519 | n/a | self._option_string_actions.pop(option_string, None) |
---|
1520 | n/a | |
---|
1521 | n/a | # if the option now has no option string, remove it from the |
---|
1522 | n/a | # container holding it |
---|
1523 | n/a | if not action.option_strings: |
---|
1524 | n/a | action.container._remove_action(action) |
---|
1525 | n/a | |
---|
1526 | n/a | |
---|
1527 | n/a | class _ArgumentGroup(_ActionsContainer): |
---|
1528 | n/a | |
---|
1529 | n/a | def __init__(self, container, title=None, description=None, **kwargs): |
---|
1530 | n/a | # add any missing keyword arguments by checking the container |
---|
1531 | n/a | update = kwargs.setdefault |
---|
1532 | n/a | update('conflict_handler', container.conflict_handler) |
---|
1533 | n/a | update('prefix_chars', container.prefix_chars) |
---|
1534 | n/a | update('argument_default', container.argument_default) |
---|
1535 | n/a | super_init = super(_ArgumentGroup, self).__init__ |
---|
1536 | n/a | super_init(description=description, **kwargs) |
---|
1537 | n/a | |
---|
1538 | n/a | # group attributes |
---|
1539 | n/a | self.title = title |
---|
1540 | n/a | self._group_actions = [] |
---|
1541 | n/a | |
---|
1542 | n/a | # share most attributes with the container |
---|
1543 | n/a | self._registries = container._registries |
---|
1544 | n/a | self._actions = container._actions |
---|
1545 | n/a | self._option_string_actions = container._option_string_actions |
---|
1546 | n/a | self._defaults = container._defaults |
---|
1547 | n/a | self._has_negative_number_optionals = \ |
---|
1548 | n/a | container._has_negative_number_optionals |
---|
1549 | n/a | self._mutually_exclusive_groups = container._mutually_exclusive_groups |
---|
1550 | n/a | |
---|
1551 | n/a | def _add_action(self, action): |
---|
1552 | n/a | action = super(_ArgumentGroup, self)._add_action(action) |
---|
1553 | n/a | self._group_actions.append(action) |
---|
1554 | n/a | return action |
---|
1555 | n/a | |
---|
1556 | n/a | def _remove_action(self, action): |
---|
1557 | n/a | super(_ArgumentGroup, self)._remove_action(action) |
---|
1558 | n/a | self._group_actions.remove(action) |
---|
1559 | n/a | |
---|
1560 | n/a | |
---|
1561 | n/a | class _MutuallyExclusiveGroup(_ArgumentGroup): |
---|
1562 | n/a | |
---|
1563 | n/a | def __init__(self, container, required=False): |
---|
1564 | n/a | super(_MutuallyExclusiveGroup, self).__init__(container) |
---|
1565 | n/a | self.required = required |
---|
1566 | n/a | self._container = container |
---|
1567 | n/a | |
---|
1568 | n/a | def _add_action(self, action): |
---|
1569 | n/a | if action.required: |
---|
1570 | n/a | msg = _('mutually exclusive arguments must be optional') |
---|
1571 | n/a | raise ValueError(msg) |
---|
1572 | n/a | action = self._container._add_action(action) |
---|
1573 | n/a | self._group_actions.append(action) |
---|
1574 | n/a | return action |
---|
1575 | n/a | |
---|
1576 | n/a | def _remove_action(self, action): |
---|
1577 | n/a | self._container._remove_action(action) |
---|
1578 | n/a | self._group_actions.remove(action) |
---|
1579 | n/a | |
---|
1580 | n/a | |
---|
1581 | n/a | class ArgumentParser(_AttributeHolder, _ActionsContainer): |
---|
1582 | n/a | """Object for parsing command line strings into Python objects. |
---|
1583 | n/a | |
---|
1584 | n/a | Keyword Arguments: |
---|
1585 | n/a | - prog -- The name of the program (default: sys.argv[0]) |
---|
1586 | n/a | - usage -- A usage message (default: auto-generated from arguments) |
---|
1587 | n/a | - description -- A description of what the program does |
---|
1588 | n/a | - epilog -- Text following the argument descriptions |
---|
1589 | n/a | - parents -- Parsers whose arguments should be copied into this one |
---|
1590 | n/a | - formatter_class -- HelpFormatter class for printing help messages |
---|
1591 | n/a | - prefix_chars -- Characters that prefix optional arguments |
---|
1592 | n/a | - fromfile_prefix_chars -- Characters that prefix files containing |
---|
1593 | n/a | additional arguments |
---|
1594 | n/a | - argument_default -- The default value for all arguments |
---|
1595 | n/a | - conflict_handler -- String indicating how to handle conflicts |
---|
1596 | n/a | - add_help -- Add a -h/-help option |
---|
1597 | n/a | - allow_abbrev -- Allow long options to be abbreviated unambiguously |
---|
1598 | n/a | """ |
---|
1599 | n/a | |
---|
1600 | n/a | def __init__(self, |
---|
1601 | n/a | prog=None, |
---|
1602 | n/a | usage=None, |
---|
1603 | n/a | description=None, |
---|
1604 | n/a | epilog=None, |
---|
1605 | n/a | parents=[], |
---|
1606 | n/a | formatter_class=HelpFormatter, |
---|
1607 | n/a | prefix_chars='-', |
---|
1608 | n/a | fromfile_prefix_chars=None, |
---|
1609 | n/a | argument_default=None, |
---|
1610 | n/a | conflict_handler='error', |
---|
1611 | n/a | add_help=True, |
---|
1612 | n/a | allow_abbrev=True): |
---|
1613 | n/a | |
---|
1614 | n/a | superinit = super(ArgumentParser, self).__init__ |
---|
1615 | n/a | superinit(description=description, |
---|
1616 | n/a | prefix_chars=prefix_chars, |
---|
1617 | n/a | argument_default=argument_default, |
---|
1618 | n/a | conflict_handler=conflict_handler) |
---|
1619 | n/a | |
---|
1620 | n/a | # default setting for prog |
---|
1621 | n/a | if prog is None: |
---|
1622 | n/a | prog = _os.path.basename(_sys.argv[0]) |
---|
1623 | n/a | |
---|
1624 | n/a | self.prog = prog |
---|
1625 | n/a | self.usage = usage |
---|
1626 | n/a | self.epilog = epilog |
---|
1627 | n/a | self.formatter_class = formatter_class |
---|
1628 | n/a | self.fromfile_prefix_chars = fromfile_prefix_chars |
---|
1629 | n/a | self.add_help = add_help |
---|
1630 | n/a | self.allow_abbrev = allow_abbrev |
---|
1631 | n/a | |
---|
1632 | n/a | add_group = self.add_argument_group |
---|
1633 | n/a | self._positionals = add_group(_('positional arguments')) |
---|
1634 | n/a | self._optionals = add_group(_('optional arguments')) |
---|
1635 | n/a | self._subparsers = None |
---|
1636 | n/a | |
---|
1637 | n/a | # register types |
---|
1638 | n/a | def identity(string): |
---|
1639 | n/a | return string |
---|
1640 | n/a | self.register('type', None, identity) |
---|
1641 | n/a | |
---|
1642 | n/a | # add help argument if necessary |
---|
1643 | n/a | # (using explicit default to override global argument_default) |
---|
1644 | n/a | default_prefix = '-' if '-' in prefix_chars else prefix_chars[0] |
---|
1645 | n/a | if self.add_help: |
---|
1646 | n/a | self.add_argument( |
---|
1647 | n/a | default_prefix+'h', default_prefix*2+'help', |
---|
1648 | n/a | action='help', default=SUPPRESS, |
---|
1649 | n/a | help=_('show this help message and exit')) |
---|
1650 | n/a | |
---|
1651 | n/a | # add parent arguments and defaults |
---|
1652 | n/a | for parent in parents: |
---|
1653 | n/a | self._add_container_actions(parent) |
---|
1654 | n/a | try: |
---|
1655 | n/a | defaults = parent._defaults |
---|
1656 | n/a | except AttributeError: |
---|
1657 | n/a | pass |
---|
1658 | n/a | else: |
---|
1659 | n/a | self._defaults.update(defaults) |
---|
1660 | n/a | |
---|
1661 | n/a | # ======================= |
---|
1662 | n/a | # Pretty __repr__ methods |
---|
1663 | n/a | # ======================= |
---|
1664 | n/a | def _get_kwargs(self): |
---|
1665 | n/a | names = [ |
---|
1666 | n/a | 'prog', |
---|
1667 | n/a | 'usage', |
---|
1668 | n/a | 'description', |
---|
1669 | n/a | 'formatter_class', |
---|
1670 | n/a | 'conflict_handler', |
---|
1671 | n/a | 'add_help', |
---|
1672 | n/a | ] |
---|
1673 | n/a | return [(name, getattr(self, name)) for name in names] |
---|
1674 | n/a | |
---|
1675 | n/a | # ================================== |
---|
1676 | n/a | # Optional/Positional adding methods |
---|
1677 | n/a | # ================================== |
---|
1678 | n/a | def add_subparsers(self, **kwargs): |
---|
1679 | n/a | if self._subparsers is not None: |
---|
1680 | n/a | self.error(_('cannot have multiple subparser arguments')) |
---|
1681 | n/a | |
---|
1682 | n/a | # add the parser class to the arguments if it's not present |
---|
1683 | n/a | kwargs.setdefault('parser_class', type(self)) |
---|
1684 | n/a | |
---|
1685 | n/a | if 'title' in kwargs or 'description' in kwargs: |
---|
1686 | n/a | title = _(kwargs.pop('title', 'subcommands')) |
---|
1687 | n/a | description = _(kwargs.pop('description', None)) |
---|
1688 | n/a | self._subparsers = self.add_argument_group(title, description) |
---|
1689 | n/a | else: |
---|
1690 | n/a | self._subparsers = self._positionals |
---|
1691 | n/a | |
---|
1692 | n/a | # prog defaults to the usage message of this parser, skipping |
---|
1693 | n/a | # optional arguments and with no "usage:" prefix |
---|
1694 | n/a | if kwargs.get('prog') is None: |
---|
1695 | n/a | formatter = self._get_formatter() |
---|
1696 | n/a | positionals = self._get_positional_actions() |
---|
1697 | n/a | groups = self._mutually_exclusive_groups |
---|
1698 | n/a | formatter.add_usage(self.usage, positionals, groups, '') |
---|
1699 | n/a | kwargs['prog'] = formatter.format_help().strip() |
---|
1700 | n/a | |
---|
1701 | n/a | # create the parsers action and add it to the positionals list |
---|
1702 | n/a | parsers_class = self._pop_action_class(kwargs, 'parsers') |
---|
1703 | n/a | action = parsers_class(option_strings=[], **kwargs) |
---|
1704 | n/a | self._subparsers._add_action(action) |
---|
1705 | n/a | |
---|
1706 | n/a | # return the created parsers action |
---|
1707 | n/a | return action |
---|
1708 | n/a | |
---|
1709 | n/a | def _add_action(self, action): |
---|
1710 | n/a | if action.option_strings: |
---|
1711 | n/a | self._optionals._add_action(action) |
---|
1712 | n/a | else: |
---|
1713 | n/a | self._positionals._add_action(action) |
---|
1714 | n/a | return action |
---|
1715 | n/a | |
---|
1716 | n/a | def _get_optional_actions(self): |
---|
1717 | n/a | return [action |
---|
1718 | n/a | for action in self._actions |
---|
1719 | n/a | if action.option_strings] |
---|
1720 | n/a | |
---|
1721 | n/a | def _get_positional_actions(self): |
---|
1722 | n/a | return [action |
---|
1723 | n/a | for action in self._actions |
---|
1724 | n/a | if not action.option_strings] |
---|
1725 | n/a | |
---|
1726 | n/a | # ===================================== |
---|
1727 | n/a | # Command line argument parsing methods |
---|
1728 | n/a | # ===================================== |
---|
1729 | n/a | def parse_args(self, args=None, namespace=None): |
---|
1730 | n/a | args, argv = self.parse_known_args(args, namespace) |
---|
1731 | n/a | if argv: |
---|
1732 | n/a | msg = _('unrecognized arguments: %s') |
---|
1733 | n/a | self.error(msg % ' '.join(argv)) |
---|
1734 | n/a | return args |
---|
1735 | n/a | |
---|
1736 | n/a | def parse_known_args(self, args=None, namespace=None): |
---|
1737 | n/a | if args is None: |
---|
1738 | n/a | # args default to the system args |
---|
1739 | n/a | args = _sys.argv[1:] |
---|
1740 | n/a | else: |
---|
1741 | n/a | # make sure that args are mutable |
---|
1742 | n/a | args = list(args) |
---|
1743 | n/a | |
---|
1744 | n/a | # default Namespace built from parser defaults |
---|
1745 | n/a | if namespace is None: |
---|
1746 | n/a | namespace = Namespace() |
---|
1747 | n/a | |
---|
1748 | n/a | # add any action defaults that aren't present |
---|
1749 | n/a | for action in self._actions: |
---|
1750 | n/a | if action.dest is not SUPPRESS: |
---|
1751 | n/a | if not hasattr(namespace, action.dest): |
---|
1752 | n/a | if action.default is not SUPPRESS: |
---|
1753 | n/a | setattr(namespace, action.dest, action.default) |
---|
1754 | n/a | |
---|
1755 | n/a | # add any parser defaults that aren't present |
---|
1756 | n/a | for dest in self._defaults: |
---|
1757 | n/a | if not hasattr(namespace, dest): |
---|
1758 | n/a | setattr(namespace, dest, self._defaults[dest]) |
---|
1759 | n/a | |
---|
1760 | n/a | # parse the arguments and exit if there are any errors |
---|
1761 | n/a | try: |
---|
1762 | n/a | namespace, args = self._parse_known_args(args, namespace) |
---|
1763 | n/a | if hasattr(namespace, _UNRECOGNIZED_ARGS_ATTR): |
---|
1764 | n/a | args.extend(getattr(namespace, _UNRECOGNIZED_ARGS_ATTR)) |
---|
1765 | n/a | delattr(namespace, _UNRECOGNIZED_ARGS_ATTR) |
---|
1766 | n/a | return namespace, args |
---|
1767 | n/a | except ArgumentError: |
---|
1768 | n/a | err = _sys.exc_info()[1] |
---|
1769 | n/a | self.error(str(err)) |
---|
1770 | n/a | |
---|
1771 | n/a | def _parse_known_args(self, arg_strings, namespace): |
---|
1772 | n/a | # replace arg strings that are file references |
---|
1773 | n/a | if self.fromfile_prefix_chars is not None: |
---|
1774 | n/a | arg_strings = self._read_args_from_files(arg_strings) |
---|
1775 | n/a | |
---|
1776 | n/a | # map all mutually exclusive arguments to the other arguments |
---|
1777 | n/a | # they can't occur with |
---|
1778 | n/a | action_conflicts = {} |
---|
1779 | n/a | for mutex_group in self._mutually_exclusive_groups: |
---|
1780 | n/a | group_actions = mutex_group._group_actions |
---|
1781 | n/a | for i, mutex_action in enumerate(mutex_group._group_actions): |
---|
1782 | n/a | conflicts = action_conflicts.setdefault(mutex_action, []) |
---|
1783 | n/a | conflicts.extend(group_actions[:i]) |
---|
1784 | n/a | conflicts.extend(group_actions[i + 1:]) |
---|
1785 | n/a | |
---|
1786 | n/a | # find all option indices, and determine the arg_string_pattern |
---|
1787 | n/a | # which has an 'O' if there is an option at an index, |
---|
1788 | n/a | # an 'A' if there is an argument, or a '-' if there is a '--' |
---|
1789 | n/a | option_string_indices = {} |
---|
1790 | n/a | arg_string_pattern_parts = [] |
---|
1791 | n/a | arg_strings_iter = iter(arg_strings) |
---|
1792 | n/a | for i, arg_string in enumerate(arg_strings_iter): |
---|
1793 | n/a | |
---|
1794 | n/a | # all args after -- are non-options |
---|
1795 | n/a | if arg_string == '--': |
---|
1796 | n/a | arg_string_pattern_parts.append('-') |
---|
1797 | n/a | for arg_string in arg_strings_iter: |
---|
1798 | n/a | arg_string_pattern_parts.append('A') |
---|
1799 | n/a | |
---|
1800 | n/a | # otherwise, add the arg to the arg strings |
---|
1801 | n/a | # and note the index if it was an option |
---|
1802 | n/a | else: |
---|
1803 | n/a | option_tuple = self._parse_optional(arg_string) |
---|
1804 | n/a | if option_tuple is None: |
---|
1805 | n/a | pattern = 'A' |
---|
1806 | n/a | else: |
---|
1807 | n/a | option_string_indices[i] = option_tuple |
---|
1808 | n/a | pattern = 'O' |
---|
1809 | n/a | arg_string_pattern_parts.append(pattern) |
---|
1810 | n/a | |
---|
1811 | n/a | # join the pieces together to form the pattern |
---|
1812 | n/a | arg_strings_pattern = ''.join(arg_string_pattern_parts) |
---|
1813 | n/a | |
---|
1814 | n/a | # converts arg strings to the appropriate and then takes the action |
---|
1815 | n/a | seen_actions = set() |
---|
1816 | n/a | seen_non_default_actions = set() |
---|
1817 | n/a | |
---|
1818 | n/a | def take_action(action, argument_strings, option_string=None): |
---|
1819 | n/a | seen_actions.add(action) |
---|
1820 | n/a | argument_values = self._get_values(action, argument_strings) |
---|
1821 | n/a | |
---|
1822 | n/a | # error if this argument is not allowed with other previously |
---|
1823 | n/a | # seen arguments, assuming that actions that use the default |
---|
1824 | n/a | # value don't really count as "present" |
---|
1825 | n/a | if argument_values is not action.default: |
---|
1826 | n/a | seen_non_default_actions.add(action) |
---|
1827 | n/a | for conflict_action in action_conflicts.get(action, []): |
---|
1828 | n/a | if conflict_action in seen_non_default_actions: |
---|
1829 | n/a | msg = _('not allowed with argument %s') |
---|
1830 | n/a | action_name = _get_action_name(conflict_action) |
---|
1831 | n/a | raise ArgumentError(action, msg % action_name) |
---|
1832 | n/a | |
---|
1833 | n/a | # take the action if we didn't receive a SUPPRESS value |
---|
1834 | n/a | # (e.g. from a default) |
---|
1835 | n/a | if argument_values is not SUPPRESS: |
---|
1836 | n/a | action(self, namespace, argument_values, option_string) |
---|
1837 | n/a | |
---|
1838 | n/a | # function to convert arg_strings into an optional action |
---|
1839 | n/a | def consume_optional(start_index): |
---|
1840 | n/a | |
---|
1841 | n/a | # get the optional identified at this index |
---|
1842 | n/a | option_tuple = option_string_indices[start_index] |
---|
1843 | n/a | action, option_string, explicit_arg = option_tuple |
---|
1844 | n/a | |
---|
1845 | n/a | # identify additional optionals in the same arg string |
---|
1846 | n/a | # (e.g. -xyz is the same as -x -y -z if no args are required) |
---|
1847 | n/a | match_argument = self._match_argument |
---|
1848 | n/a | action_tuples = [] |
---|
1849 | n/a | while True: |
---|
1850 | n/a | |
---|
1851 | n/a | # if we found no optional action, skip it |
---|
1852 | n/a | if action is None: |
---|
1853 | n/a | extras.append(arg_strings[start_index]) |
---|
1854 | n/a | return start_index + 1 |
---|
1855 | n/a | |
---|
1856 | n/a | # if there is an explicit argument, try to match the |
---|
1857 | n/a | # optional's string arguments to only this |
---|
1858 | n/a | if explicit_arg is not None: |
---|
1859 | n/a | arg_count = match_argument(action, 'A') |
---|
1860 | n/a | |
---|
1861 | n/a | # if the action is a single-dash option and takes no |
---|
1862 | n/a | # arguments, try to parse more single-dash options out |
---|
1863 | n/a | # of the tail of the option string |
---|
1864 | n/a | chars = self.prefix_chars |
---|
1865 | n/a | if arg_count == 0 and option_string[1] not in chars: |
---|
1866 | n/a | action_tuples.append((action, [], option_string)) |
---|
1867 | n/a | char = option_string[0] |
---|
1868 | n/a | option_string = char + explicit_arg[0] |
---|
1869 | n/a | new_explicit_arg = explicit_arg[1:] or None |
---|
1870 | n/a | optionals_map = self._option_string_actions |
---|
1871 | n/a | if option_string in optionals_map: |
---|
1872 | n/a | action = optionals_map[option_string] |
---|
1873 | n/a | explicit_arg = new_explicit_arg |
---|
1874 | n/a | else: |
---|
1875 | n/a | msg = _('ignored explicit argument %r') |
---|
1876 | n/a | raise ArgumentError(action, msg % explicit_arg) |
---|
1877 | n/a | |
---|
1878 | n/a | # if the action expect exactly one argument, we've |
---|
1879 | n/a | # successfully matched the option; exit the loop |
---|
1880 | n/a | elif arg_count == 1: |
---|
1881 | n/a | stop = start_index + 1 |
---|
1882 | n/a | args = [explicit_arg] |
---|
1883 | n/a | action_tuples.append((action, args, option_string)) |
---|
1884 | n/a | break |
---|
1885 | n/a | |
---|
1886 | n/a | # error if a double-dash option did not use the |
---|
1887 | n/a | # explicit argument |
---|
1888 | n/a | else: |
---|
1889 | n/a | msg = _('ignored explicit argument %r') |
---|
1890 | n/a | raise ArgumentError(action, msg % explicit_arg) |
---|
1891 | n/a | |
---|
1892 | n/a | # if there is no explicit argument, try to match the |
---|
1893 | n/a | # optional's string arguments with the following strings |
---|
1894 | n/a | # if successful, exit the loop |
---|
1895 | n/a | else: |
---|
1896 | n/a | start = start_index + 1 |
---|
1897 | n/a | selected_patterns = arg_strings_pattern[start:] |
---|
1898 | n/a | arg_count = match_argument(action, selected_patterns) |
---|
1899 | n/a | stop = start + arg_count |
---|
1900 | n/a | args = arg_strings[start:stop] |
---|
1901 | n/a | action_tuples.append((action, args, option_string)) |
---|
1902 | n/a | break |
---|
1903 | n/a | |
---|
1904 | n/a | # add the Optional to the list and return the index at which |
---|
1905 | n/a | # the Optional's string args stopped |
---|
1906 | n/a | assert action_tuples |
---|
1907 | n/a | for action, args, option_string in action_tuples: |
---|
1908 | n/a | take_action(action, args, option_string) |
---|
1909 | n/a | return stop |
---|
1910 | n/a | |
---|
1911 | n/a | # the list of Positionals left to be parsed; this is modified |
---|
1912 | n/a | # by consume_positionals() |
---|
1913 | n/a | positionals = self._get_positional_actions() |
---|
1914 | n/a | |
---|
1915 | n/a | # function to convert arg_strings into positional actions |
---|
1916 | n/a | def consume_positionals(start_index): |
---|
1917 | n/a | # match as many Positionals as possible |
---|
1918 | n/a | match_partial = self._match_arguments_partial |
---|
1919 | n/a | selected_pattern = arg_strings_pattern[start_index:] |
---|
1920 | n/a | arg_counts = match_partial(positionals, selected_pattern) |
---|
1921 | n/a | |
---|
1922 | n/a | # slice off the appropriate arg strings for each Positional |
---|
1923 | n/a | # and add the Positional and its args to the list |
---|
1924 | n/a | for action, arg_count in zip(positionals, arg_counts): |
---|
1925 | n/a | args = arg_strings[start_index: start_index + arg_count] |
---|
1926 | n/a | start_index += arg_count |
---|
1927 | n/a | take_action(action, args) |
---|
1928 | n/a | |
---|
1929 | n/a | # slice off the Positionals that we just parsed and return the |
---|
1930 | n/a | # index at which the Positionals' string args stopped |
---|
1931 | n/a | positionals[:] = positionals[len(arg_counts):] |
---|
1932 | n/a | return start_index |
---|
1933 | n/a | |
---|
1934 | n/a | # consume Positionals and Optionals alternately, until we have |
---|
1935 | n/a | # passed the last option string |
---|
1936 | n/a | extras = [] |
---|
1937 | n/a | start_index = 0 |
---|
1938 | n/a | if option_string_indices: |
---|
1939 | n/a | max_option_string_index = max(option_string_indices) |
---|
1940 | n/a | else: |
---|
1941 | n/a | max_option_string_index = -1 |
---|
1942 | n/a | while start_index <= max_option_string_index: |
---|
1943 | n/a | |
---|
1944 | n/a | # consume any Positionals preceding the next option |
---|
1945 | n/a | next_option_string_index = min([ |
---|
1946 | n/a | index |
---|
1947 | n/a | for index in option_string_indices |
---|
1948 | n/a | if index >= start_index]) |
---|
1949 | n/a | if start_index != next_option_string_index: |
---|
1950 | n/a | positionals_end_index = consume_positionals(start_index) |
---|
1951 | n/a | |
---|
1952 | n/a | # only try to parse the next optional if we didn't consume |
---|
1953 | n/a | # the option string during the positionals parsing |
---|
1954 | n/a | if positionals_end_index > start_index: |
---|
1955 | n/a | start_index = positionals_end_index |
---|
1956 | n/a | continue |
---|
1957 | n/a | else: |
---|
1958 | n/a | start_index = positionals_end_index |
---|
1959 | n/a | |
---|
1960 | n/a | # if we consumed all the positionals we could and we're not |
---|
1961 | n/a | # at the index of an option string, there were extra arguments |
---|
1962 | n/a | if start_index not in option_string_indices: |
---|
1963 | n/a | strings = arg_strings[start_index:next_option_string_index] |
---|
1964 | n/a | extras.extend(strings) |
---|
1965 | n/a | start_index = next_option_string_index |
---|
1966 | n/a | |
---|
1967 | n/a | # consume the next optional and any arguments for it |
---|
1968 | n/a | start_index = consume_optional(start_index) |
---|
1969 | n/a | |
---|
1970 | n/a | # consume any positionals following the last Optional |
---|
1971 | n/a | stop_index = consume_positionals(start_index) |
---|
1972 | n/a | |
---|
1973 | n/a | # if we didn't consume all the argument strings, there were extras |
---|
1974 | n/a | extras.extend(arg_strings[stop_index:]) |
---|
1975 | n/a | |
---|
1976 | n/a | # make sure all required actions were present and also convert |
---|
1977 | n/a | # action defaults which were not given as arguments |
---|
1978 | n/a | required_actions = [] |
---|
1979 | n/a | for action in self._actions: |
---|
1980 | n/a | if action not in seen_actions: |
---|
1981 | n/a | if action.required: |
---|
1982 | n/a | required_actions.append(_get_action_name(action)) |
---|
1983 | n/a | else: |
---|
1984 | n/a | # Convert action default now instead of doing it before |
---|
1985 | n/a | # parsing arguments to avoid calling convert functions |
---|
1986 | n/a | # twice (which may fail) if the argument was given, but |
---|
1987 | n/a | # only if it was defined already in the namespace |
---|
1988 | n/a | if (action.default is not None and |
---|
1989 | n/a | isinstance(action.default, str) and |
---|
1990 | n/a | hasattr(namespace, action.dest) and |
---|
1991 | n/a | action.default is getattr(namespace, action.dest)): |
---|
1992 | n/a | setattr(namespace, action.dest, |
---|
1993 | n/a | self._get_value(action, action.default)) |
---|
1994 | n/a | |
---|
1995 | n/a | if required_actions: |
---|
1996 | n/a | self.error(_('the following arguments are required: %s') % |
---|
1997 | n/a | ', '.join(required_actions)) |
---|
1998 | n/a | |
---|
1999 | n/a | # make sure all required groups had one option present |
---|
2000 | n/a | for group in self._mutually_exclusive_groups: |
---|
2001 | n/a | if group.required: |
---|
2002 | n/a | for action in group._group_actions: |
---|
2003 | n/a | if action in seen_non_default_actions: |
---|
2004 | n/a | break |
---|
2005 | n/a | |
---|
2006 | n/a | # if no actions were used, report the error |
---|
2007 | n/a | else: |
---|
2008 | n/a | names = [_get_action_name(action) |
---|
2009 | n/a | for action in group._group_actions |
---|
2010 | n/a | if action.help is not SUPPRESS] |
---|
2011 | n/a | msg = _('one of the arguments %s is required') |
---|
2012 | n/a | self.error(msg % ' '.join(names)) |
---|
2013 | n/a | |
---|
2014 | n/a | # return the updated namespace and the extra arguments |
---|
2015 | n/a | return namespace, extras |
---|
2016 | n/a | |
---|
2017 | n/a | def _read_args_from_files(self, arg_strings): |
---|
2018 | n/a | # expand arguments referencing files |
---|
2019 | n/a | new_arg_strings = [] |
---|
2020 | n/a | for arg_string in arg_strings: |
---|
2021 | n/a | |
---|
2022 | n/a | # for regular arguments, just add them back into the list |
---|
2023 | n/a | if not arg_string or arg_string[0] not in self.fromfile_prefix_chars: |
---|
2024 | n/a | new_arg_strings.append(arg_string) |
---|
2025 | n/a | |
---|
2026 | n/a | # replace arguments referencing files with the file content |
---|
2027 | n/a | else: |
---|
2028 | n/a | try: |
---|
2029 | n/a | with open(arg_string[1:]) as args_file: |
---|
2030 | n/a | arg_strings = [] |
---|
2031 | n/a | for arg_line in args_file.read().splitlines(): |
---|
2032 | n/a | for arg in self.convert_arg_line_to_args(arg_line): |
---|
2033 | n/a | arg_strings.append(arg) |
---|
2034 | n/a | arg_strings = self._read_args_from_files(arg_strings) |
---|
2035 | n/a | new_arg_strings.extend(arg_strings) |
---|
2036 | n/a | except OSError: |
---|
2037 | n/a | err = _sys.exc_info()[1] |
---|
2038 | n/a | self.error(str(err)) |
---|
2039 | n/a | |
---|
2040 | n/a | # return the modified argument list |
---|
2041 | n/a | return new_arg_strings |
---|
2042 | n/a | |
---|
2043 | n/a | def convert_arg_line_to_args(self, arg_line): |
---|
2044 | n/a | return [arg_line] |
---|
2045 | n/a | |
---|
2046 | n/a | def _match_argument(self, action, arg_strings_pattern): |
---|
2047 | n/a | # match the pattern for this action to the arg strings |
---|
2048 | n/a | nargs_pattern = self._get_nargs_pattern(action) |
---|
2049 | n/a | match = _re.match(nargs_pattern, arg_strings_pattern) |
---|
2050 | n/a | |
---|
2051 | n/a | # raise an exception if we weren't able to find a match |
---|
2052 | n/a | if match is None: |
---|
2053 | n/a | nargs_errors = { |
---|
2054 | n/a | None: _('expected one argument'), |
---|
2055 | n/a | OPTIONAL: _('expected at most one argument'), |
---|
2056 | n/a | ONE_OR_MORE: _('expected at least one argument'), |
---|
2057 | n/a | } |
---|
2058 | n/a | default = ngettext('expected %s argument', |
---|
2059 | n/a | 'expected %s arguments', |
---|
2060 | n/a | action.nargs) % action.nargs |
---|
2061 | n/a | msg = nargs_errors.get(action.nargs, default) |
---|
2062 | n/a | raise ArgumentError(action, msg) |
---|
2063 | n/a | |
---|
2064 | n/a | # return the number of arguments matched |
---|
2065 | n/a | return len(match.group(1)) |
---|
2066 | n/a | |
---|
2067 | n/a | def _match_arguments_partial(self, actions, arg_strings_pattern): |
---|
2068 | n/a | # progressively shorten the actions list by slicing off the |
---|
2069 | n/a | # final actions until we find a match |
---|
2070 | n/a | result = [] |
---|
2071 | n/a | for i in range(len(actions), 0, -1): |
---|
2072 | n/a | actions_slice = actions[:i] |
---|
2073 | n/a | pattern = ''.join([self._get_nargs_pattern(action) |
---|
2074 | n/a | for action in actions_slice]) |
---|
2075 | n/a | match = _re.match(pattern, arg_strings_pattern) |
---|
2076 | n/a | if match is not None: |
---|
2077 | n/a | result.extend([len(string) for string in match.groups()]) |
---|
2078 | n/a | break |
---|
2079 | n/a | |
---|
2080 | n/a | # return the list of arg string counts |
---|
2081 | n/a | return result |
---|
2082 | n/a | |
---|
2083 | n/a | def _parse_optional(self, arg_string): |
---|
2084 | n/a | # if it's an empty string, it was meant to be a positional |
---|
2085 | n/a | if not arg_string: |
---|
2086 | n/a | return None |
---|
2087 | n/a | |
---|
2088 | n/a | # if it doesn't start with a prefix, it was meant to be positional |
---|
2089 | n/a | if not arg_string[0] in self.prefix_chars: |
---|
2090 | n/a | return None |
---|
2091 | n/a | |
---|
2092 | n/a | # if the option string is present in the parser, return the action |
---|
2093 | n/a | if arg_string in self._option_string_actions: |
---|
2094 | n/a | action = self._option_string_actions[arg_string] |
---|
2095 | n/a | return action, arg_string, None |
---|
2096 | n/a | |
---|
2097 | n/a | # if it's just a single character, it was meant to be positional |
---|
2098 | n/a | if len(arg_string) == 1: |
---|
2099 | n/a | return None |
---|
2100 | n/a | |
---|
2101 | n/a | # if the option string before the "=" is present, return the action |
---|
2102 | n/a | if '=' in arg_string: |
---|
2103 | n/a | option_string, explicit_arg = arg_string.split('=', 1) |
---|
2104 | n/a | if option_string in self._option_string_actions: |
---|
2105 | n/a | action = self._option_string_actions[option_string] |
---|
2106 | n/a | return action, option_string, explicit_arg |
---|
2107 | n/a | |
---|
2108 | n/a | if self.allow_abbrev: |
---|
2109 | n/a | # search through all possible prefixes of the option string |
---|
2110 | n/a | # and all actions in the parser for possible interpretations |
---|
2111 | n/a | option_tuples = self._get_option_tuples(arg_string) |
---|
2112 | n/a | |
---|
2113 | n/a | # if multiple actions match, the option string was ambiguous |
---|
2114 | n/a | if len(option_tuples) > 1: |
---|
2115 | n/a | options = ', '.join([option_string |
---|
2116 | n/a | for action, option_string, explicit_arg in option_tuples]) |
---|
2117 | n/a | args = {'option': arg_string, 'matches': options} |
---|
2118 | n/a | msg = _('ambiguous option: %(option)s could match %(matches)s') |
---|
2119 | n/a | self.error(msg % args) |
---|
2120 | n/a | |
---|
2121 | n/a | # if exactly one action matched, this segmentation is good, |
---|
2122 | n/a | # so return the parsed action |
---|
2123 | n/a | elif len(option_tuples) == 1: |
---|
2124 | n/a | option_tuple, = option_tuples |
---|
2125 | n/a | return option_tuple |
---|
2126 | n/a | |
---|
2127 | n/a | # if it was not found as an option, but it looks like a negative |
---|
2128 | n/a | # number, it was meant to be positional |
---|
2129 | n/a | # unless there are negative-number-like options |
---|
2130 | n/a | if self._negative_number_matcher.match(arg_string): |
---|
2131 | n/a | if not self._has_negative_number_optionals: |
---|
2132 | n/a | return None |
---|
2133 | n/a | |
---|
2134 | n/a | # if it contains a space, it was meant to be a positional |
---|
2135 | n/a | if ' ' in arg_string: |
---|
2136 | n/a | return None |
---|
2137 | n/a | |
---|
2138 | n/a | # it was meant to be an optional but there is no such option |
---|
2139 | n/a | # in this parser (though it might be a valid option in a subparser) |
---|
2140 | n/a | return None, arg_string, None |
---|
2141 | n/a | |
---|
2142 | n/a | def _get_option_tuples(self, option_string): |
---|
2143 | n/a | result = [] |
---|
2144 | n/a | |
---|
2145 | n/a | # option strings starting with two prefix characters are only |
---|
2146 | n/a | # split at the '=' |
---|
2147 | n/a | chars = self.prefix_chars |
---|
2148 | n/a | if option_string[0] in chars and option_string[1] in chars: |
---|
2149 | n/a | if '=' in option_string: |
---|
2150 | n/a | option_prefix, explicit_arg = option_string.split('=', 1) |
---|
2151 | n/a | else: |
---|
2152 | n/a | option_prefix = option_string |
---|
2153 | n/a | explicit_arg = None |
---|
2154 | n/a | for option_string in self._option_string_actions: |
---|
2155 | n/a | if option_string.startswith(option_prefix): |
---|
2156 | n/a | action = self._option_string_actions[option_string] |
---|
2157 | n/a | tup = action, option_string, explicit_arg |
---|
2158 | n/a | result.append(tup) |
---|
2159 | n/a | |
---|
2160 | n/a | # single character options can be concatenated with their arguments |
---|
2161 | n/a | # but multiple character options always have to have their argument |
---|
2162 | n/a | # separate |
---|
2163 | n/a | elif option_string[0] in chars and option_string[1] not in chars: |
---|
2164 | n/a | option_prefix = option_string |
---|
2165 | n/a | explicit_arg = None |
---|
2166 | n/a | short_option_prefix = option_string[:2] |
---|
2167 | n/a | short_explicit_arg = option_string[2:] |
---|
2168 | n/a | |
---|
2169 | n/a | for option_string in self._option_string_actions: |
---|
2170 | n/a | if option_string == short_option_prefix: |
---|
2171 | n/a | action = self._option_string_actions[option_string] |
---|
2172 | n/a | tup = action, option_string, short_explicit_arg |
---|
2173 | n/a | result.append(tup) |
---|
2174 | n/a | elif option_string.startswith(option_prefix): |
---|
2175 | n/a | action = self._option_string_actions[option_string] |
---|
2176 | n/a | tup = action, option_string, explicit_arg |
---|
2177 | n/a | result.append(tup) |
---|
2178 | n/a | |
---|
2179 | n/a | # shouldn't ever get here |
---|
2180 | n/a | else: |
---|
2181 | n/a | self.error(_('unexpected option string: %s') % option_string) |
---|
2182 | n/a | |
---|
2183 | n/a | # return the collected option tuples |
---|
2184 | n/a | return result |
---|
2185 | n/a | |
---|
2186 | n/a | def _get_nargs_pattern(self, action): |
---|
2187 | n/a | # in all examples below, we have to allow for '--' args |
---|
2188 | n/a | # which are represented as '-' in the pattern |
---|
2189 | n/a | nargs = action.nargs |
---|
2190 | n/a | |
---|
2191 | n/a | # the default (None) is assumed to be a single argument |
---|
2192 | n/a | if nargs is None: |
---|
2193 | n/a | nargs_pattern = '(-*A-*)' |
---|
2194 | n/a | |
---|
2195 | n/a | # allow zero or one arguments |
---|
2196 | n/a | elif nargs == OPTIONAL: |
---|
2197 | n/a | nargs_pattern = '(-*A?-*)' |
---|
2198 | n/a | |
---|
2199 | n/a | # allow zero or more arguments |
---|
2200 | n/a | elif nargs == ZERO_OR_MORE: |
---|
2201 | n/a | nargs_pattern = '(-*[A-]*)' |
---|
2202 | n/a | |
---|
2203 | n/a | # allow one or more arguments |
---|
2204 | n/a | elif nargs == ONE_OR_MORE: |
---|
2205 | n/a | nargs_pattern = '(-*A[A-]*)' |
---|
2206 | n/a | |
---|
2207 | n/a | # allow any number of options or arguments |
---|
2208 | n/a | elif nargs == REMAINDER: |
---|
2209 | n/a | nargs_pattern = '([-AO]*)' |
---|
2210 | n/a | |
---|
2211 | n/a | # allow one argument followed by any number of options or arguments |
---|
2212 | n/a | elif nargs == PARSER: |
---|
2213 | n/a | nargs_pattern = '(-*A[-AO]*)' |
---|
2214 | n/a | |
---|
2215 | n/a | # all others should be integers |
---|
2216 | n/a | else: |
---|
2217 | n/a | nargs_pattern = '(-*%s-*)' % '-*'.join('A' * nargs) |
---|
2218 | n/a | |
---|
2219 | n/a | # if this is an optional action, -- is not allowed |
---|
2220 | n/a | if action.option_strings: |
---|
2221 | n/a | nargs_pattern = nargs_pattern.replace('-*', '') |
---|
2222 | n/a | nargs_pattern = nargs_pattern.replace('-', '') |
---|
2223 | n/a | |
---|
2224 | n/a | # return the pattern |
---|
2225 | n/a | return nargs_pattern |
---|
2226 | n/a | |
---|
2227 | n/a | # ======================== |
---|
2228 | n/a | # Value conversion methods |
---|
2229 | n/a | # ======================== |
---|
2230 | n/a | def _get_values(self, action, arg_strings): |
---|
2231 | n/a | # for everything but PARSER, REMAINDER args, strip out first '--' |
---|
2232 | n/a | if action.nargs not in [PARSER, REMAINDER]: |
---|
2233 | n/a | try: |
---|
2234 | n/a | arg_strings.remove('--') |
---|
2235 | n/a | except ValueError: |
---|
2236 | n/a | pass |
---|
2237 | n/a | |
---|
2238 | n/a | # optional argument produces a default when not present |
---|
2239 | n/a | if not arg_strings and action.nargs == OPTIONAL: |
---|
2240 | n/a | if action.option_strings: |
---|
2241 | n/a | value = action.const |
---|
2242 | n/a | else: |
---|
2243 | n/a | value = action.default |
---|
2244 | n/a | if isinstance(value, str): |
---|
2245 | n/a | value = self._get_value(action, value) |
---|
2246 | n/a | self._check_value(action, value) |
---|
2247 | n/a | |
---|
2248 | n/a | # when nargs='*' on a positional, if there were no command-line |
---|
2249 | n/a | # args, use the default if it is anything other than None |
---|
2250 | n/a | elif (not arg_strings and action.nargs == ZERO_OR_MORE and |
---|
2251 | n/a | not action.option_strings): |
---|
2252 | n/a | if action.default is not None: |
---|
2253 | n/a | value = action.default |
---|
2254 | n/a | else: |
---|
2255 | n/a | value = arg_strings |
---|
2256 | n/a | self._check_value(action, value) |
---|
2257 | n/a | |
---|
2258 | n/a | # single argument or optional argument produces a single value |
---|
2259 | n/a | elif len(arg_strings) == 1 and action.nargs in [None, OPTIONAL]: |
---|
2260 | n/a | arg_string, = arg_strings |
---|
2261 | n/a | value = self._get_value(action, arg_string) |
---|
2262 | n/a | self._check_value(action, value) |
---|
2263 | n/a | |
---|
2264 | n/a | # REMAINDER arguments convert all values, checking none |
---|
2265 | n/a | elif action.nargs == REMAINDER: |
---|
2266 | n/a | value = [self._get_value(action, v) for v in arg_strings] |
---|
2267 | n/a | |
---|
2268 | n/a | # PARSER arguments convert all values, but check only the first |
---|
2269 | n/a | elif action.nargs == PARSER: |
---|
2270 | n/a | value = [self._get_value(action, v) for v in arg_strings] |
---|
2271 | n/a | self._check_value(action, value[0]) |
---|
2272 | n/a | |
---|
2273 | n/a | # all other types of nargs produce a list |
---|
2274 | n/a | else: |
---|
2275 | n/a | value = [self._get_value(action, v) for v in arg_strings] |
---|
2276 | n/a | for v in value: |
---|
2277 | n/a | self._check_value(action, v) |
---|
2278 | n/a | |
---|
2279 | n/a | # return the converted value |
---|
2280 | n/a | return value |
---|
2281 | n/a | |
---|
2282 | n/a | def _get_value(self, action, arg_string): |
---|
2283 | n/a | type_func = self._registry_get('type', action.type, action.type) |
---|
2284 | n/a | if not callable(type_func): |
---|
2285 | n/a | msg = _('%r is not callable') |
---|
2286 | n/a | raise ArgumentError(action, msg % type_func) |
---|
2287 | n/a | |
---|
2288 | n/a | # convert the value to the appropriate type |
---|
2289 | n/a | try: |
---|
2290 | n/a | result = type_func(arg_string) |
---|
2291 | n/a | |
---|
2292 | n/a | # ArgumentTypeErrors indicate errors |
---|
2293 | n/a | except ArgumentTypeError: |
---|
2294 | n/a | name = getattr(action.type, '__name__', repr(action.type)) |
---|
2295 | n/a | msg = str(_sys.exc_info()[1]) |
---|
2296 | n/a | raise ArgumentError(action, msg) |
---|
2297 | n/a | |
---|
2298 | n/a | # TypeErrors or ValueErrors also indicate errors |
---|
2299 | n/a | except (TypeError, ValueError): |
---|
2300 | n/a | name = getattr(action.type, '__name__', repr(action.type)) |
---|
2301 | n/a | args = {'type': name, 'value': arg_string} |
---|
2302 | n/a | msg = _('invalid %(type)s value: %(value)r') |
---|
2303 | n/a | raise ArgumentError(action, msg % args) |
---|
2304 | n/a | |
---|
2305 | n/a | # return the converted value |
---|
2306 | n/a | return result |
---|
2307 | n/a | |
---|
2308 | n/a | def _check_value(self, action, value): |
---|
2309 | n/a | # converted value must be one of the choices (if specified) |
---|
2310 | n/a | if action.choices is not None and value not in action.choices: |
---|
2311 | n/a | args = {'value': value, |
---|
2312 | n/a | 'choices': ', '.join(map(repr, action.choices))} |
---|
2313 | n/a | msg = _('invalid choice: %(value)r (choose from %(choices)s)') |
---|
2314 | n/a | raise ArgumentError(action, msg % args) |
---|
2315 | n/a | |
---|
2316 | n/a | # ======================= |
---|
2317 | n/a | # Help-formatting methods |
---|
2318 | n/a | # ======================= |
---|
2319 | n/a | def format_usage(self): |
---|
2320 | n/a | formatter = self._get_formatter() |
---|
2321 | n/a | formatter.add_usage(self.usage, self._actions, |
---|
2322 | n/a | self._mutually_exclusive_groups) |
---|
2323 | n/a | return formatter.format_help() |
---|
2324 | n/a | |
---|
2325 | n/a | def format_help(self): |
---|
2326 | n/a | formatter = self._get_formatter() |
---|
2327 | n/a | |
---|
2328 | n/a | # usage |
---|
2329 | n/a | formatter.add_usage(self.usage, self._actions, |
---|
2330 | n/a | self._mutually_exclusive_groups) |
---|
2331 | n/a | |
---|
2332 | n/a | # description |
---|
2333 | n/a | formatter.add_text(self.description) |
---|
2334 | n/a | |
---|
2335 | n/a | # positionals, optionals and user-defined groups |
---|
2336 | n/a | for action_group in self._action_groups: |
---|
2337 | n/a | formatter.start_section(action_group.title) |
---|
2338 | n/a | formatter.add_text(action_group.description) |
---|
2339 | n/a | formatter.add_arguments(action_group._group_actions) |
---|
2340 | n/a | formatter.end_section() |
---|
2341 | n/a | |
---|
2342 | n/a | # epilog |
---|
2343 | n/a | formatter.add_text(self.epilog) |
---|
2344 | n/a | |
---|
2345 | n/a | # determine help from format above |
---|
2346 | n/a | return formatter.format_help() |
---|
2347 | n/a | |
---|
2348 | n/a | def _get_formatter(self): |
---|
2349 | n/a | return self.formatter_class(prog=self.prog) |
---|
2350 | n/a | |
---|
2351 | n/a | # ===================== |
---|
2352 | n/a | # Help-printing methods |
---|
2353 | n/a | # ===================== |
---|
2354 | n/a | def print_usage(self, file=None): |
---|
2355 | n/a | if file is None: |
---|
2356 | n/a | file = _sys.stdout |
---|
2357 | n/a | self._print_message(self.format_usage(), file) |
---|
2358 | n/a | |
---|
2359 | n/a | def print_help(self, file=None): |
---|
2360 | n/a | if file is None: |
---|
2361 | n/a | file = _sys.stdout |
---|
2362 | n/a | self._print_message(self.format_help(), file) |
---|
2363 | n/a | |
---|
2364 | n/a | def _print_message(self, message, file=None): |
---|
2365 | n/a | if message: |
---|
2366 | n/a | if file is None: |
---|
2367 | n/a | file = _sys.stderr |
---|
2368 | n/a | file.write(message) |
---|
2369 | n/a | |
---|
2370 | n/a | # =============== |
---|
2371 | n/a | # Exiting methods |
---|
2372 | n/a | # =============== |
---|
2373 | n/a | def exit(self, status=0, message=None): |
---|
2374 | n/a | if message: |
---|
2375 | n/a | self._print_message(message, _sys.stderr) |
---|
2376 | n/a | _sys.exit(status) |
---|
2377 | n/a | |
---|
2378 | n/a | def error(self, message): |
---|
2379 | n/a | """error(message: string) |
---|
2380 | n/a | |
---|
2381 | n/a | Prints a usage message incorporating the message to stderr and |
---|
2382 | n/a | exits. |
---|
2383 | n/a | |
---|
2384 | n/a | If you override this in a subclass, it should not return -- it |
---|
2385 | n/a | should either exit or raise an exception. |
---|
2386 | n/a | """ |
---|
2387 | n/a | self.print_usage(_sys.stderr) |
---|
2388 | n/a | args = {'prog': self.prog, 'message': message} |
---|
2389 | n/a | self.exit(2, _('%(prog)s: error: %(message)s\n') % args) |
---|