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