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