$treeview $search $mathjax $extrastylesheet
otsdaq_utilities
v2_03_00
$projectbrief
|
$projectbrief
|
$searchbox |
00001 # Author: Steven J. Bethard <steven.bethard@gmail.com>. 00002 00003 """Command-line parsing library 00004 00005 This module is an optparse-inspired command-line parsing library that: 00006 00007 - handles both optional and positional arguments 00008 - produces highly informative usage messages 00009 - supports parsers that dispatch to sub-parsers 00010 00011 The following is a simple usage example that sums integers from the 00012 command-line and writes the result to a file:: 00013 00014 parser = argparse.ArgumentParser( 00015 description='sum the integers at the command line') 00016 parser.add_argument( 00017 'integers', metavar='int', nargs='+', type=int, 00018 help='an integer to be summed') 00019 parser.add_argument( 00020 '--log', default=sys.stdout, type=argparse.FileType('w'), 00021 help='the file where the sum should be written') 00022 args = parser.parse_args() 00023 args.log.write('%s' % sum(args.integers)) 00024 args.log.close() 00025 00026 The module contains the following public classes: 00027 00028 - ArgumentParser -- The main entry point for command-line parsing. As the 00029 example above shows, the add_argument() method is used to populate 00030 the parser with actions for optional and positional arguments. Then 00031 the parse_args() method is invoked to convert the args at the 00032 command-line into an object with attributes. 00033 00034 - ArgumentError -- The exception raised by ArgumentParser objects when 00035 there are errors with the parser's actions. Errors raised while 00036 parsing the command-line are caught by ArgumentParser and emitted 00037 as command-line messages. 00038 00039 - FileType -- A factory for defining types of files to be created. As the 00040 example above shows, instances of FileType are typically passed as 00041 the type= argument of add_argument() calls. 00042 00043 - Action -- The base class for parser actions. Typically actions are 00044 selected by passing strings like 'store_true' or 'append_const' to 00045 the action= argument of add_argument(). However, for greater 00046 customization of ArgumentParser actions, subclasses of Action may 00047 be defined and passed as the action= argument. 00048 00049 - HelpFormatter, RawDescriptionHelpFormatter, RawTextHelpFormatter, 00050 ArgumentDefaultsHelpFormatter -- Formatter classes which 00051 may be passed as the formatter_class= argument to the 00052 ArgumentParser constructor. HelpFormatter is the default, 00053 RawDescriptionHelpFormatter and RawTextHelpFormatter tell the parser 00054 not to change the formatting for help text, and 00055 ArgumentDefaultsHelpFormatter adds information about argument defaults 00056 to the help. 00057 00058 All other classes in this module are considered implementation details. 00059 (Also note that HelpFormatter and RawDescriptionHelpFormatter are only 00060 considered public as object names -- the API of the formatter objects is 00061 still considered an implementation detail.) 00062 """ 00063 00064 __version__ = '1.1' 00065 __all__ = [ 00066 'ArgumentParser', 00067 'ArgumentError', 00068 'ArgumentTypeError', 00069 'FileType', 00070 'HelpFormatter', 00071 'ArgumentDefaultsHelpFormatter', 00072 'RawDescriptionHelpFormatter', 00073 'RawTextHelpFormatter', 00074 'Namespace', 00075 'Action', 00076 'ONE_OR_MORE', 00077 'OPTIONAL', 00078 'PARSER', 00079 'REMAINDER', 00080 'SUPPRESS', 00081 'ZERO_OR_MORE', 00082 ] 00083 00084 00085 import collections as _collections 00086 import copy as _copy 00087 import os as _os 00088 import re as _re 00089 import sys as _sys 00090 import textwrap as _textwrap 00091 00092 from gettext import gettext as _ 00093 00094 00095 def _callable(obj): 00096 return hasattr(obj, '__call__') or hasattr(obj, '__bases__') 00097 00098 00099 SUPPRESS = '==SUPPRESS==' 00100 00101 OPTIONAL = '?' 00102 ZERO_OR_MORE = '*' 00103 ONE_OR_MORE = '+' 00104 PARSER = 'A...' 00105 REMAINDER = '...' 00106 _UNRECOGNIZED_ARGS_ATTR = '_unrecognized_args' 00107 00108 # ============================= 00109 # Utility functions and classes 00110 # ============================= 00111 00112 class _AttributeHolder(object): 00113 """Abstract base class that provides __repr__. 00114 00115 The __repr__ method returns a string in the format:: 00116 ClassName(attr=name, attr=name, ...) 00117 The attributes are determined either by a class-level attribute, 00118 '_kwarg_names', or by inspecting the instance __dict__. 00119 """ 00120 00121 def __repr__(self): 00122 type_name = type(self).__name__ 00123 arg_strings = [] 00124 for arg in self._get_args(): 00125 arg_strings.append(repr(arg)) 00126 for name, value in self._get_kwargs(): 00127 arg_strings.append('%s=%r' % (name, value)) 00128 return '%s(%s)' % (type_name, ', '.join(arg_strings)) 00129 00130 def _get_kwargs(self): 00131 return sorted(self.__dict__.items()) 00132 00133 def _get_args(self): 00134 return [] 00135 00136 00137 def _ensure_value(namespace, name, value): 00138 if getattr(namespace, name, None) is None: 00139 setattr(namespace, name, value) 00140 return getattr(namespace, name) 00141 00142 00143 # =============== 00144 # Formatting Help 00145 # =============== 00146 00147 class HelpFormatter(object): 00148 """Formatter for generating usage messages and argument help strings. 00149 00150 Only the name of this class is considered a public API. All the methods 00151 provided by the class are considered an implementation detail. 00152 """ 00153 00154 def __init__(self, 00155 prog, 00156 indent_increment=2, 00157 max_help_position=24, 00158 width=None): 00159 00160 # default setting for width 00161 if width is None: 00162 try: 00163 width = int(_os.environ['COLUMNS']) 00164 except (KeyError, ValueError): 00165 width = 80 00166 width -= 2 00167 00168 self._prog = prog 00169 self._indent_increment = indent_increment 00170 self._max_help_position = max_help_position 00171 self._max_help_position = min(max_help_position, 00172 max(width - 20, indent_increment * 2)) 00173 self._width = width 00174 00175 self._current_indent = 0 00176 self._level = 0 00177 self._action_max_length = 0 00178 00179 self._root_section = self._Section(self, None) 00180 self._current_section = self._root_section 00181 00182 self._whitespace_matcher = _re.compile(r'\s+') 00183 self._long_break_matcher = _re.compile(r'\n\n\n+') 00184 00185 # =============================== 00186 # Section and indentation methods 00187 # =============================== 00188 def _indent(self): 00189 self._current_indent += self._indent_increment 00190 self._level += 1 00191 00192 def _dedent(self): 00193 self._current_indent -= self._indent_increment 00194 assert self._current_indent >= 0, 'Indent decreased below 0.' 00195 self._level -= 1 00196 00197 class _Section(object): 00198 00199 def __init__(self, formatter, parent, heading=None): 00200 self.formatter = formatter 00201 self.parent = parent 00202 self.heading = heading 00203 self.items = [] 00204 00205 def format_help(self): 00206 # format the indented section 00207 if self.parent is not None: 00208 self.formatter._indent() 00209 join = self.formatter._join_parts 00210 for func, args in self.items: 00211 func(*args) 00212 item_help = join([func(*args) for func, args in self.items]) 00213 if self.parent is not None: 00214 self.formatter._dedent() 00215 00216 # return nothing if the section was empty 00217 if not item_help: 00218 return '' 00219 00220 # add the heading if the section was non-empty 00221 if self.heading is not SUPPRESS and self.heading is not None: 00222 current_indent = self.formatter._current_indent 00223 heading = '%*s%s:\n' % (current_indent, '', self.heading) 00224 else: 00225 heading = '' 00226 00227 # join the section-initial newline, the heading and the help 00228 return join(['\n', heading, item_help, '\n']) 00229 00230 def _add_item(self, func, args): 00231 self._current_section.items.append((func, args)) 00232 00233 # ======================== 00234 # Message building methods 00235 # ======================== 00236 def start_section(self, heading): 00237 self._indent() 00238 section = self._Section(self, self._current_section, heading) 00239 self._add_item(section.format_help, []) 00240 self._current_section = section 00241 00242 def end_section(self): 00243 self._current_section = self._current_section.parent 00244 self._dedent() 00245 00246 def add_text(self, text): 00247 if text is not SUPPRESS and text is not None: 00248 self._add_item(self._format_text, [text]) 00249 00250 def add_usage(self, usage, actions, groups, prefix=None): 00251 if usage is not SUPPRESS: 00252 args = usage, actions, groups, prefix 00253 self._add_item(self._format_usage, args) 00254 00255 def add_argument(self, action): 00256 if action.help is not SUPPRESS: 00257 00258 # find all invocations 00259 get_invocation = self._format_action_invocation 00260 invocations = [get_invocation(action)] 00261 for subaction in self._iter_indented_subactions(action): 00262 invocations.append(get_invocation(subaction)) 00263 00264 # update the maximum item length 00265 invocation_length = max([len(s) for s in invocations]) 00266 action_length = invocation_length + self._current_indent 00267 self._action_max_length = max(self._action_max_length, 00268 action_length) 00269 00270 # add the item to the list 00271 self._add_item(self._format_action, [action]) 00272 00273 def add_arguments(self, actions): 00274 for action in actions: 00275 self.add_argument(action) 00276 00277 # ======================= 00278 # Help-formatting methods 00279 # ======================= 00280 def format_help(self): 00281 help = self._root_section.format_help() 00282 if help: 00283 help = self._long_break_matcher.sub('\n\n', help) 00284 help = help.strip('\n') + '\n' 00285 return help 00286 00287 def _join_parts(self, part_strings): 00288 return ''.join([part 00289 for part in part_strings 00290 if part and part is not SUPPRESS]) 00291 00292 def _format_usage(self, usage, actions, groups, prefix): 00293 if prefix is None: 00294 prefix = _('usage: ') 00295 00296 # if usage is specified, use that 00297 if usage is not None: 00298 usage = usage % dict(prog=self._prog) 00299 00300 # if no optionals or positionals are available, usage is just prog 00301 elif usage is None and not actions: 00302 usage = '%(prog)s' % dict(prog=self._prog) 00303 00304 # if optionals and positionals are available, calculate usage 00305 elif usage is None: 00306 prog = '%(prog)s' % dict(prog=self._prog) 00307 00308 # split optionals from positionals 00309 optionals = [] 00310 positionals = [] 00311 for action in actions: 00312 if action.option_strings: 00313 optionals.append(action) 00314 else: 00315 positionals.append(action) 00316 00317 # build full usage string 00318 format = self._format_actions_usage 00319 action_usage = format(optionals + positionals, groups) 00320 usage = ' '.join([s for s in [prog, action_usage] if s]) 00321 00322 # wrap the usage parts if it's too long 00323 text_width = self._width - self._current_indent 00324 if len(prefix) + len(usage) > text_width: 00325 00326 # break usage into wrappable parts 00327 part_regexp = r'\(.*?\)+|\[.*?\]+|\S+' 00328 opt_usage = format(optionals, groups) 00329 pos_usage = format(positionals, groups) 00330 opt_parts = _re.findall(part_regexp, opt_usage) 00331 pos_parts = _re.findall(part_regexp, pos_usage) 00332 assert ' '.join(opt_parts) == opt_usage 00333 assert ' '.join(pos_parts) == pos_usage 00334 00335 # helper for wrapping lines 00336 def get_lines(parts, indent, prefix=None): 00337 lines = [] 00338 line = [] 00339 if prefix is not None: 00340 line_len = len(prefix) - 1 00341 else: 00342 line_len = len(indent) - 1 00343 for part in parts: 00344 if line_len + 1 + len(part) > text_width and line: 00345 lines.append(indent + ' '.join(line)) 00346 line = [] 00347 line_len = len(indent) - 1 00348 line.append(part) 00349 line_len += len(part) + 1 00350 if line: 00351 lines.append(indent + ' '.join(line)) 00352 if prefix is not None: 00353 lines[0] = lines[0][len(indent):] 00354 return lines 00355 00356 # if prog is short, follow it with optionals or positionals 00357 if len(prefix) + len(prog) <= 0.75 * text_width: 00358 indent = ' ' * (len(prefix) + len(prog) + 1) 00359 if opt_parts: 00360 lines = get_lines([prog] + opt_parts, indent, prefix) 00361 lines.extend(get_lines(pos_parts, indent)) 00362 elif pos_parts: 00363 lines = get_lines([prog] + pos_parts, indent, prefix) 00364 else: 00365 lines = [prog] 00366 00367 # if prog is long, put it on its own line 00368 else: 00369 indent = ' ' * len(prefix) 00370 parts = opt_parts + pos_parts 00371 lines = get_lines(parts, indent) 00372 if len(lines) > 1: 00373 lines = [] 00374 lines.extend(get_lines(opt_parts, indent)) 00375 lines.extend(get_lines(pos_parts, indent)) 00376 lines = [prog] + lines 00377 00378 # join lines into usage 00379 usage = '\n'.join(lines) 00380 00381 # prefix with 'usage:' 00382 return '%s%s\n\n' % (prefix, usage) 00383 00384 def _format_actions_usage(self, actions, groups): 00385 # find group indices and identify actions in groups 00386 group_actions = set() 00387 inserts = {} 00388 for group in groups: 00389 try: 00390 start = actions.index(group._group_actions[0]) 00391 except ValueError: 00392 continue 00393 else: 00394 end = start + len(group._group_actions) 00395 if actions[start:end] == group._group_actions: 00396 for action in group._group_actions: 00397 group_actions.add(action) 00398 if not group.required: 00399 if start in inserts: 00400 inserts[start] += ' [' 00401 else: 00402 inserts[start] = '[' 00403 inserts[end] = ']' 00404 else: 00405 if start in inserts: 00406 inserts[start] += ' (' 00407 else: 00408 inserts[start] = '(' 00409 inserts[end] = ')' 00410 for i in range(start + 1, end): 00411 inserts[i] = '|' 00412 00413 # collect all actions format strings 00414 parts = [] 00415 for i, action in enumerate(actions): 00416 00417 # suppressed arguments are marked with None 00418 # remove | separators for suppressed arguments 00419 if action.help is SUPPRESS: 00420 parts.append(None) 00421 if inserts.get(i) == '|': 00422 inserts.pop(i) 00423 elif inserts.get(i + 1) == '|': 00424 inserts.pop(i + 1) 00425 00426 # produce all arg strings 00427 elif not action.option_strings: 00428 part = self._format_args(action, action.dest) 00429 00430 # if it's in a group, strip the outer [] 00431 if action in group_actions: 00432 if part[0] == '[' and part[-1] == ']': 00433 part = part[1:-1] 00434 00435 # add the action string to the list 00436 parts.append(part) 00437 00438 # produce the first way to invoke the option in brackets 00439 else: 00440 option_string = action.option_strings[0] 00441 00442 # if the Optional doesn't take a value, format is: 00443 # -s or --long 00444 if action.nargs == 0: 00445 part = '%s' % option_string 00446 00447 # if the Optional takes a value, format is: 00448 # -s ARGS or --long ARGS 00449 else: 00450 default = action.dest.upper() 00451 args_string = self._format_args(action, default) 00452 part = '%s %s' % (option_string, args_string) 00453 00454 # make it look optional if it's not required or in a group 00455 if not action.required and action not in group_actions: 00456 part = '[%s]' % part 00457 00458 # add the action string to the list 00459 parts.append(part) 00460 00461 # insert things at the necessary indices 00462 for i in sorted(inserts, reverse=True): 00463 parts[i:i] = [inserts[i]] 00464 00465 # join all the action items with spaces 00466 text = ' '.join([item for item in parts if item is not None]) 00467 00468 # clean up separators for mutually exclusive groups 00469 open = r'[\[(]' 00470 close = r'[\])]' 00471 text = _re.sub(r'(%s) ' % open, r'\1', text) 00472 text = _re.sub(r' (%s)' % close, r'\1', text) 00473 text = _re.sub(r'%s *%s' % (open, close), r'', text) 00474 text = _re.sub(r'\(([^|]*)\)', r'\1', text) 00475 text = text.strip() 00476 00477 # return the text 00478 return text 00479 00480 def _format_text(self, text): 00481 if '%(prog)' in text: 00482 text = text % dict(prog=self._prog) 00483 text_width = max(self._width - self._current_indent, 11) 00484 indent = ' ' * self._current_indent 00485 return self._fill_text(text, text_width, indent) + '\n\n' 00486 00487 def _format_action(self, action): 00488 # determine the required width and the entry label 00489 help_position = min(self._action_max_length + 2, 00490 self._max_help_position) 00491 help_width = max(self._width - help_position, 11) 00492 action_width = help_position - self._current_indent - 2 00493 action_header = self._format_action_invocation(action) 00494 00495 # ho nelp; start on same line and add a final newline 00496 if not action.help: 00497 tup = self._current_indent, '', action_header 00498 action_header = '%*s%s\n' % tup 00499 00500 # short action name; start on the same line and pad two spaces 00501 elif len(action_header) <= action_width: 00502 tup = self._current_indent, '', action_width, action_header 00503 action_header = '%*s%-*s ' % tup 00504 indent_first = 0 00505 00506 # long action name; start on the next line 00507 else: 00508 tup = self._current_indent, '', action_header 00509 action_header = '%*s%s\n' % tup 00510 indent_first = help_position 00511 00512 # collect the pieces of the action help 00513 parts = [action_header] 00514 00515 # if there was help for the action, add lines of help text 00516 if action.help: 00517 help_text = self._expand_help(action) 00518 help_lines = self._split_lines(help_text, help_width) 00519 parts.append('%*s%s\n' % (indent_first, '', help_lines[0])) 00520 for line in help_lines[1:]: 00521 parts.append('%*s%s\n' % (help_position, '', line)) 00522 00523 # or add a newline if the description doesn't end with one 00524 elif not action_header.endswith('\n'): 00525 parts.append('\n') 00526 00527 # if there are any sub-actions, add their help as well 00528 for subaction in self._iter_indented_subactions(action): 00529 parts.append(self._format_action(subaction)) 00530 00531 # return a single string 00532 return self._join_parts(parts) 00533 00534 def _format_action_invocation(self, action): 00535 if not action.option_strings: 00536 metavar, = self._metavar_formatter(action, action.dest)(1) 00537 return metavar 00538 00539 else: 00540 parts = [] 00541 00542 # if the Optional doesn't take a value, format is: 00543 # -s, --long 00544 if action.nargs == 0: 00545 parts.extend(action.option_strings) 00546 00547 # if the Optional takes a value, format is: 00548 # -s ARGS, --long ARGS 00549 else: 00550 default = action.dest.upper() 00551 args_string = self._format_args(action, default) 00552 for option_string in action.option_strings: 00553 parts.append('%s %s' % (option_string, args_string)) 00554 00555 return ', '.join(parts) 00556 00557 def _metavar_formatter(self, action, default_metavar): 00558 if action.metavar is not None: 00559 result = action.metavar 00560 elif action.choices is not None: 00561 choice_strs = [str(choice) for choice in action.choices] 00562 result = '{%s}' % ','.join(choice_strs) 00563 else: 00564 result = default_metavar 00565 00566 def format(tuple_size): 00567 if isinstance(result, tuple): 00568 return result 00569 else: 00570 return (result, ) * tuple_size 00571 return format 00572 00573 def _format_args(self, action, default_metavar): 00574 get_metavar = self._metavar_formatter(action, default_metavar) 00575 if action.nargs is None: 00576 result = '%s' % get_metavar(1) 00577 elif action.nargs == OPTIONAL: 00578 result = '[%s]' % get_metavar(1) 00579 elif action.nargs == ZERO_OR_MORE: 00580 result = '[%s [%s ...]]' % get_metavar(2) 00581 elif action.nargs == ONE_OR_MORE: 00582 result = '%s [%s ...]' % get_metavar(2) 00583 elif action.nargs == REMAINDER: 00584 result = '...' 00585 elif action.nargs == PARSER: 00586 result = '%s ...' % get_metavar(1) 00587 else: 00588 formats = ['%s' for _ in range(action.nargs)] 00589 result = ' '.join(formats) % get_metavar(action.nargs) 00590 return result 00591 00592 def _expand_help(self, action): 00593 params = dict(vars(action), prog=self._prog) 00594 for name in list(params): 00595 if params[name] is SUPPRESS: 00596 del params[name] 00597 for name in list(params): 00598 if hasattr(params[name], '__name__'): 00599 params[name] = params[name].__name__ 00600 if params.get('choices') is not None: 00601 choices_str = ', '.join([str(c) for c in params['choices']]) 00602 params['choices'] = choices_str 00603 return self._get_help_string(action) % params 00604 00605 def _iter_indented_subactions(self, action): 00606 try: 00607 get_subactions = action._get_subactions 00608 except AttributeError: 00609 pass 00610 else: 00611 self._indent() 00612 for subaction in get_subactions(): 00613 yield subaction 00614 self._dedent() 00615 00616 def _split_lines(self, text, width): 00617 text = self._whitespace_matcher.sub(' ', text).strip() 00618 return _textwrap.wrap(text, width) 00619 00620 def _fill_text(self, text, width, indent): 00621 text = self._whitespace_matcher.sub(' ', text).strip() 00622 return _textwrap.fill(text, width, initial_indent=indent, 00623 subsequent_indent=indent) 00624 00625 def _get_help_string(self, action): 00626 return action.help 00627 00628 00629 class RawDescriptionHelpFormatter(HelpFormatter): 00630 """Help message formatter which retains any formatting in descriptions. 00631 00632 Only the name of this class is considered a public API. All the methods 00633 provided by the class are considered an implementation detail. 00634 """ 00635 00636 def _fill_text(self, text, width, indent): 00637 return ''.join([indent + line for line in text.splitlines(True)]) 00638 00639 00640 class RawTextHelpFormatter(RawDescriptionHelpFormatter): 00641 """Help message formatter which retains formatting of all help text. 00642 00643 Only the name of this class is considered a public API. All the methods 00644 provided by the class are considered an implementation detail. 00645 """ 00646 00647 def _split_lines(self, text, width): 00648 return text.splitlines() 00649 00650 00651 class ArgumentDefaultsHelpFormatter(HelpFormatter): 00652 """Help message formatter which adds default values to argument help. 00653 00654 Only the name of this class is considered a public API. All the methods 00655 provided by the class are considered an implementation detail. 00656 """ 00657 00658 def _get_help_string(self, action): 00659 help = action.help 00660 if '%(default)' not in action.help: 00661 if action.default is not SUPPRESS: 00662 defaulting_nargs = [OPTIONAL, ZERO_OR_MORE] 00663 if action.option_strings or action.nargs in defaulting_nargs: 00664 help += ' (default: %(default)s)' 00665 return help 00666 00667 00668 # ===================== 00669 # Options and Arguments 00670 # ===================== 00671 00672 def _get_action_name(argument): 00673 if argument is None: 00674 return None 00675 elif argument.option_strings: 00676 return '/'.join(argument.option_strings) 00677 elif argument.metavar not in (None, SUPPRESS): 00678 return argument.metavar 00679 elif argument.dest not in (None, SUPPRESS): 00680 return argument.dest 00681 else: 00682 return None 00683 00684 00685 class ArgumentError(Exception): 00686 """An error from creating or using an argument (optional or positional). 00687 00688 The string value of this exception is the message, augmented with 00689 information about the argument that caused it. 00690 """ 00691 00692 def __init__(self, argument, message): 00693 self.argument_name = _get_action_name(argument) 00694 self.message = message 00695 00696 def __str__(self): 00697 if self.argument_name is None: 00698 format = '%(message)s' 00699 else: 00700 format = 'argument %(argument_name)s: %(message)s' 00701 return format % dict(message=self.message, 00702 argument_name=self.argument_name) 00703 00704 00705 class ArgumentTypeError(Exception): 00706 """An error from trying to convert a command line string to a type.""" 00707 pass 00708 00709 00710 # ============== 00711 # Action classes 00712 # ============== 00713 00714 class Action(_AttributeHolder): 00715 """Information about how to convert command line strings to Python objects. 00716 00717 Action objects are used by an ArgumentParser to represent the information 00718 needed to parse a single argument from one or more strings from the 00719 command line. The keyword arguments to the Action constructor are also 00720 all attributes of Action instances. 00721 00722 Keyword Arguments: 00723 00724 - option_strings -- A list of command-line option strings which 00725 should be associated with this action. 00726 00727 - dest -- The name of the attribute to hold the created object(s) 00728 00729 - nargs -- The number of command-line arguments that should be 00730 consumed. By default, one argument will be consumed and a single 00731 value will be produced. Other values include: 00732 - N (an integer) consumes N arguments (and produces a list) 00733 - '?' consumes zero or one arguments 00734 - '*' consumes zero or more arguments (and produces a list) 00735 - '+' consumes one or more arguments (and produces a list) 00736 Note that the difference between the default and nargs=1 is that 00737 with the default, a single value will be produced, while with 00738 nargs=1, a list containing a single value will be produced. 00739 00740 - const -- The value to be produced if the option is specified and the 00741 option uses an action that takes no values. 00742 00743 - default -- The value to be produced if the option is not specified. 00744 00745 - type -- A callable that accepts a single string argument, and 00746 returns the converted value. The standard Python types str, int, 00747 float, and complex are useful examples of such callables. If None, 00748 str is used. 00749 00750 - choices -- A container of values that should be allowed. If not None, 00751 after a command-line argument has been converted to the appropriate 00752 type, an exception will be raised if it is not a member of this 00753 collection. 00754 00755 - required -- True if the action must always be specified at the 00756 command line. This is only meaningful for optional command-line 00757 arguments. 00758 00759 - help -- The help string describing the argument. 00760 00761 - metavar -- The name to be used for the option's argument with the 00762 help string. If None, the 'dest' value will be used as the name. 00763 """ 00764 00765 def __init__(self, 00766 option_strings, 00767 dest, 00768 nargs=None, 00769 const=None, 00770 default=None, 00771 type=None, 00772 choices=None, 00773 required=False, 00774 help=None, 00775 metavar=None): 00776 self.option_strings = option_strings 00777 self.dest = dest 00778 self.nargs = nargs 00779 self.const = const 00780 self.default = default 00781 self.type = type 00782 self.choices = choices 00783 self.required = required 00784 self.help = help 00785 self.metavar = metavar 00786 00787 def _get_kwargs(self): 00788 names = [ 00789 'option_strings', 00790 'dest', 00791 'nargs', 00792 'const', 00793 'default', 00794 'type', 00795 'choices', 00796 'help', 00797 'metavar', 00798 ] 00799 return [(name, getattr(self, name)) for name in names] 00800 00801 def __call__(self, parser, namespace, values, option_string=None): 00802 raise NotImplementedError(_('.__call__() not defined')) 00803 00804 00805 class _StoreAction(Action): 00806 00807 def __init__(self, 00808 option_strings, 00809 dest, 00810 nargs=None, 00811 const=None, 00812 default=None, 00813 type=None, 00814 choices=None, 00815 required=False, 00816 help=None, 00817 metavar=None): 00818 if nargs == 0: 00819 raise ValueError('nargs for store actions must be > 0; if you ' 00820 'have nothing to store, actions such as store ' 00821 'true or store const may be more appropriate') 00822 if const is not None and nargs != OPTIONAL: 00823 raise ValueError('nargs must be %r to supply const' % OPTIONAL) 00824 super(_StoreAction, self).__init__( 00825 option_strings=option_strings, 00826 dest=dest, 00827 nargs=nargs, 00828 const=const, 00829 default=default, 00830 type=type, 00831 choices=choices, 00832 required=required, 00833 help=help, 00834 metavar=metavar) 00835 00836 def __call__(self, parser, namespace, values, option_string=None): 00837 setattr(namespace, self.dest, values) 00838 00839 00840 class _StoreConstAction(Action): 00841 00842 def __init__(self, 00843 option_strings, 00844 dest, 00845 const, 00846 default=None, 00847 required=False, 00848 help=None, 00849 metavar=None): 00850 super(_StoreConstAction, self).__init__( 00851 option_strings=option_strings, 00852 dest=dest, 00853 nargs=0, 00854 const=const, 00855 default=default, 00856 required=required, 00857 help=help) 00858 00859 def __call__(self, parser, namespace, values, option_string=None): 00860 setattr(namespace, self.dest, self.const) 00861 00862 00863 class _StoreTrueAction(_StoreConstAction): 00864 00865 def __init__(self, 00866 option_strings, 00867 dest, 00868 default=False, 00869 required=False, 00870 help=None): 00871 super(_StoreTrueAction, self).__init__( 00872 option_strings=option_strings, 00873 dest=dest, 00874 const=True, 00875 default=default, 00876 required=required, 00877 help=help) 00878 00879 00880 class _StoreFalseAction(_StoreConstAction): 00881 00882 def __init__(self, 00883 option_strings, 00884 dest, 00885 default=True, 00886 required=False, 00887 help=None): 00888 super(_StoreFalseAction, self).__init__( 00889 option_strings=option_strings, 00890 dest=dest, 00891 const=False, 00892 default=default, 00893 required=required, 00894 help=help) 00895 00896 00897 class _AppendAction(Action): 00898 00899 def __init__(self, 00900 option_strings, 00901 dest, 00902 nargs=None, 00903 const=None, 00904 default=None, 00905 type=None, 00906 choices=None, 00907 required=False, 00908 help=None, 00909 metavar=None): 00910 if nargs == 0: 00911 raise ValueError('nargs for append actions must be > 0; if arg ' 00912 'strings are not supplying the value to append, ' 00913 'the append const action may be more appropriate') 00914 if const is not None and nargs != OPTIONAL: 00915 raise ValueError('nargs must be %r to supply const' % OPTIONAL) 00916 super(_AppendAction, self).__init__( 00917 option_strings=option_strings, 00918 dest=dest, 00919 nargs=nargs, 00920 const=const, 00921 default=default, 00922 type=type, 00923 choices=choices, 00924 required=required, 00925 help=help, 00926 metavar=metavar) 00927 00928 def __call__(self, parser, namespace, values, option_string=None): 00929 items = _copy.copy(_ensure_value(namespace, self.dest, [])) 00930 items.append(values) 00931 setattr(namespace, self.dest, items) 00932 00933 00934 class _AppendConstAction(Action): 00935 00936 def __init__(self, 00937 option_strings, 00938 dest, 00939 const, 00940 default=None, 00941 required=False, 00942 help=None, 00943 metavar=None): 00944 super(_AppendConstAction, self).__init__( 00945 option_strings=option_strings, 00946 dest=dest, 00947 nargs=0, 00948 const=const, 00949 default=default, 00950 required=required, 00951 help=help, 00952 metavar=metavar) 00953 00954 def __call__(self, parser, namespace, values, option_string=None): 00955 items = _copy.copy(_ensure_value(namespace, self.dest, [])) 00956 items.append(self.const) 00957 setattr(namespace, self.dest, items) 00958 00959 00960 class _CountAction(Action): 00961 00962 def __init__(self, 00963 option_strings, 00964 dest, 00965 default=None, 00966 required=False, 00967 help=None): 00968 super(_CountAction, self).__init__( 00969 option_strings=option_strings, 00970 dest=dest, 00971 nargs=0, 00972 default=default, 00973 required=required, 00974 help=help) 00975 00976 def __call__(self, parser, namespace, values, option_string=None): 00977 new_count = _ensure_value(namespace, self.dest, 0) + 1 00978 setattr(namespace, self.dest, new_count) 00979 00980 00981 class _HelpAction(Action): 00982 00983 def __init__(self, 00984 option_strings, 00985 dest=SUPPRESS, 00986 default=SUPPRESS, 00987 help=None): 00988 super(_HelpAction, self).__init__( 00989 option_strings=option_strings, 00990 dest=dest, 00991 default=default, 00992 nargs=0, 00993 help=help) 00994 00995 def __call__(self, parser, namespace, values, option_string=None): 00996 parser.print_help() 00997 parser.exit() 00998 00999 01000 class _VersionAction(Action): 01001 01002 def __init__(self, 01003 option_strings, 01004 version=None, 01005 dest=SUPPRESS, 01006 default=SUPPRESS, 01007 help="show program's version number and exit"): 01008 super(_VersionAction, self).__init__( 01009 option_strings=option_strings, 01010 dest=dest, 01011 default=default, 01012 nargs=0, 01013 help=help) 01014 self.version = version 01015 01016 def __call__(self, parser, namespace, values, option_string=None): 01017 version = self.version 01018 if version is None: 01019 version = parser.version 01020 formatter = parser._get_formatter() 01021 formatter.add_text(version) 01022 parser.exit(message=formatter.format_help()) 01023 01024 01025 class _SubParsersAction(Action): 01026 01027 class _ChoicesPseudoAction(Action): 01028 01029 def __init__(self, name, help): 01030 sup = super(_SubParsersAction._ChoicesPseudoAction, self) 01031 sup.__init__(option_strings=[], dest=name, help=help) 01032 01033 def __init__(self, 01034 option_strings, 01035 prog, 01036 parser_class, 01037 dest=SUPPRESS, 01038 help=None, 01039 metavar=None): 01040 01041 self._prog_prefix = prog 01042 self._parser_class = parser_class 01043 self._name_parser_map = _collections.OrderedDict() 01044 self._choices_actions = [] 01045 01046 super(_SubParsersAction, self).__init__( 01047 option_strings=option_strings, 01048 dest=dest, 01049 nargs=PARSER, 01050 choices=self._name_parser_map, 01051 help=help, 01052 metavar=metavar) 01053 01054 def add_parser(self, name, **kwargs): 01055 # set prog from the existing prefix 01056 if kwargs.get('prog') is None: 01057 kwargs['prog'] = '%s %s' % (self._prog_prefix, name) 01058 01059 # create a pseudo-action to hold the choice help 01060 if 'help' in kwargs: 01061 help = kwargs.pop('help') 01062 choice_action = self._ChoicesPseudoAction(name, help) 01063 self._choices_actions.append(choice_action) 01064 01065 # create the parser and add it to the map 01066 parser = self._parser_class(**kwargs) 01067 self._name_parser_map[name] = parser 01068 return parser 01069 01070 def _get_subactions(self): 01071 return self._choices_actions 01072 01073 def __call__(self, parser, namespace, values, option_string=None): 01074 parser_name = values[0] 01075 arg_strings = values[1:] 01076 01077 # set the parser name if requested 01078 if self.dest is not SUPPRESS: 01079 setattr(namespace, self.dest, parser_name) 01080 01081 # select the parser 01082 try: 01083 parser = self._name_parser_map[parser_name] 01084 except KeyError: 01085 tup = parser_name, ', '.join(self._name_parser_map) 01086 msg = _('unknown parser %r (choices: %s)') % tup 01087 raise ArgumentError(self, msg) 01088 01089 # parse all the remaining options into the namespace 01090 # store any unrecognized options on the object, so that the top 01091 # level parser can decide what to do with them 01092 01093 # In case this subparser defines new defaults, we parse them 01094 # in a new namespace object and then update the original 01095 # namespace for the relevant parts. 01096 subnamespace, arg_strings = parser.parse_known_args(arg_strings, None) 01097 for key, value in vars(subnamespace).items(): 01098 setattr(namespace, key, value) 01099 01100 if arg_strings: 01101 vars(namespace).setdefault(_UNRECOGNIZED_ARGS_ATTR, []) 01102 getattr(namespace, _UNRECOGNIZED_ARGS_ATTR).extend(arg_strings) 01103 01104 01105 # ============== 01106 # Type classes 01107 # ============== 01108 01109 class FileType(object): 01110 """Factory for creating file object types 01111 01112 Instances of FileType are typically passed as type= arguments to the 01113 ArgumentParser add_argument() method. 01114 01115 Keyword Arguments: 01116 - mode -- A string indicating how the file is to be opened. Accepts the 01117 same values as the builtin open() function. 01118 - bufsize -- The file's desired buffer size. Accepts the same values as 01119 the builtin open() function. 01120 """ 01121 01122 def __init__(self, mode='r', bufsize=-1): 01123 self._mode = mode 01124 self._bufsize = bufsize 01125 01126 def __call__(self, string): 01127 # the special argument "-" means sys.std{in,out} 01128 if string == '-': 01129 if 'r' in self._mode: 01130 return _sys.stdin 01131 elif 'w' in self._mode: 01132 return _sys.stdout 01133 else: 01134 msg = _('argument "-" with mode %r') % self._mode 01135 raise ValueError(msg) 01136 01137 # all other arguments are used as file names 01138 try: 01139 return open(string, self._mode, self._bufsize) 01140 except IOError as e: 01141 message = _("can't open '%s': %s") 01142 raise ArgumentTypeError(message % (string, e)) 01143 01144 def __repr__(self): 01145 args = self._mode, self._bufsize 01146 args_str = ', '.join(repr(arg) for arg in args if arg != -1) 01147 return '%s(%s)' % (type(self).__name__, args_str) 01148 01149 # =========================== 01150 # Optional and Positional Parsing 01151 # =========================== 01152 01153 class Namespace(_AttributeHolder): 01154 """Simple object for storing attributes. 01155 01156 Implements equality by attribute names and values, and provides a simple 01157 string representation. 01158 """ 01159 01160 def __init__(self, **kwargs): 01161 for name in kwargs: 01162 setattr(self, name, kwargs[name]) 01163 01164 __hash__ = None 01165 01166 def __eq__(self, other): 01167 if not isinstance(other, Namespace): 01168 return NotImplemented 01169 return vars(self) == vars(other) 01170 01171 def __ne__(self, other): 01172 if not isinstance(other, Namespace): 01173 return NotImplemented 01174 return not (self == other) 01175 01176 def __contains__(self, key): 01177 return key in self.__dict__ 01178 01179 01180 class _ActionsContainer(object): 01181 01182 def __init__(self, 01183 description, 01184 prefix_chars, 01185 argument_default, 01186 conflict_handler): 01187 super(_ActionsContainer, self).__init__() 01188 01189 self.description = description 01190 self.argument_default = argument_default 01191 self.prefix_chars = prefix_chars 01192 self.conflict_handler = conflict_handler 01193 01194 # set up registries 01195 self._registries = {} 01196 01197 # register actions 01198 self.register('action', None, _StoreAction) 01199 self.register('action', 'store', _StoreAction) 01200 self.register('action', 'store_const', _StoreConstAction) 01201 self.register('action', 'store_true', _StoreTrueAction) 01202 self.register('action', 'store_false', _StoreFalseAction) 01203 self.register('action', 'append', _AppendAction) 01204 self.register('action', 'append_const', _AppendConstAction) 01205 self.register('action', 'count', _CountAction) 01206 self.register('action', 'help', _HelpAction) 01207 self.register('action', 'version', _VersionAction) 01208 self.register('action', 'parsers', _SubParsersAction) 01209 01210 # raise an exception if the conflict handler is invalid 01211 self._get_handler() 01212 01213 # action storage 01214 self._actions = [] 01215 self._option_string_actions = {} 01216 01217 # groups 01218 self._action_groups = [] 01219 self._mutually_exclusive_groups = [] 01220 01221 # defaults storage 01222 self._defaults = {} 01223 01224 # determines whether an "option" looks like a negative number 01225 self._negative_number_matcher = _re.compile(r'^-\d+$|^-\d*\.\d+$') 01226 01227 # whether or not there are any optionals that look like negative 01228 # numbers -- uses a list so it can be shared and edited 01229 self._has_negative_number_optionals = [] 01230 01231 # ==================== 01232 # Registration methods 01233 # ==================== 01234 def register(self, registry_name, value, object): 01235 registry = self._registries.setdefault(registry_name, {}) 01236 registry[value] = object 01237 01238 def _registry_get(self, registry_name, value, default=None): 01239 return self._registries[registry_name].get(value, default) 01240 01241 # ================================== 01242 # Namespace default accessor methods 01243 # ================================== 01244 def set_defaults(self, **kwargs): 01245 self._defaults.update(kwargs) 01246 01247 # if these defaults match any existing arguments, replace 01248 # the previous default on the object with the new one 01249 for action in self._actions: 01250 if action.dest in kwargs: 01251 action.default = kwargs[action.dest] 01252 01253 def get_default(self, dest): 01254 for action in self._actions: 01255 if action.dest == dest and action.default is not None: 01256 return action.default 01257 return self._defaults.get(dest, None) 01258 01259 01260 # ======================= 01261 # Adding argument actions 01262 # ======================= 01263 def add_argument(self, *args, **kwargs): 01264 """ 01265 add_argument(dest, ..., name=value, ...) 01266 add_argument(option_string, option_string, ..., name=value, ...) 01267 """ 01268 01269 # if no positional args are supplied or only one is supplied and 01270 # it doesn't look like an option string, parse a positional 01271 # argument 01272 chars = self.prefix_chars 01273 if not args or len(args) == 1 and args[0][0] not in chars: 01274 if args and 'dest' in kwargs: 01275 raise ValueError('dest supplied twice for positional argument') 01276 kwargs = self._get_positional_kwargs(*args, **kwargs) 01277 01278 # otherwise, we're adding an optional argument 01279 else: 01280 kwargs = self._get_optional_kwargs(*args, **kwargs) 01281 01282 # if no default was supplied, use the parser-level default 01283 if 'default' not in kwargs: 01284 dest = kwargs['dest'] 01285 if dest in self._defaults: 01286 kwargs['default'] = self._defaults[dest] 01287 elif self.argument_default is not None: 01288 kwargs['default'] = self.argument_default 01289 01290 # create the action object, and add it to the parser 01291 action_class = self._pop_action_class(kwargs) 01292 if not _callable(action_class): 01293 raise ValueError('unknown action "%s"' % (action_class,)) 01294 action = action_class(**kwargs) 01295 01296 # raise an error if the action type is not callable 01297 type_func = self._registry_get('type', action.type, action.type) 01298 if not _callable(type_func): 01299 raise ValueError('%r is not callable' % (type_func,)) 01300 01301 # raise an error if the metavar does not match the type 01302 if hasattr(self, "_get_formatter"): 01303 try: 01304 self._get_formatter()._format_args(action, None) 01305 except TypeError: 01306 raise ValueError("length of metavar tuple does not match nargs") 01307 01308 return self._add_action(action) 01309 01310 def add_argument_group(self, *args, **kwargs): 01311 group = _ArgumentGroup(self, *args, **kwargs) 01312 self._action_groups.append(group) 01313 return group 01314 01315 def add_mutually_exclusive_group(self, **kwargs): 01316 group = _MutuallyExclusiveGroup(self, **kwargs) 01317 self._mutually_exclusive_groups.append(group) 01318 return group 01319 01320 def _add_action(self, action): 01321 # resolve any conflicts 01322 self._check_conflict(action) 01323 01324 # add to actions list 01325 self._actions.append(action) 01326 action.container = self 01327 01328 # index the action by any option strings it has 01329 for option_string in action.option_strings: 01330 self._option_string_actions[option_string] = action 01331 01332 # set the flag if any option strings look like negative numbers 01333 for option_string in action.option_strings: 01334 if self._negative_number_matcher.match(option_string): 01335 if not self._has_negative_number_optionals: 01336 self._has_negative_number_optionals.append(True) 01337 01338 # return the created action 01339 return action 01340 01341 def _remove_action(self, action): 01342 self._actions.remove(action) 01343 01344 def _add_container_actions(self, container): 01345 # collect groups by titles 01346 title_group_map = {} 01347 for group in self._action_groups: 01348 if group.title in title_group_map: 01349 msg = _('cannot merge actions - two groups are named %r') 01350 raise ValueError(msg % (group.title)) 01351 title_group_map[group.title] = group 01352 01353 # map each action to its group 01354 group_map = {} 01355 for group in container._action_groups: 01356 01357 # if a group with the title exists, use that, otherwise 01358 # create a new group matching the container's group 01359 if group.title not in title_group_map: 01360 title_group_map[group.title] = self.add_argument_group( 01361 title=group.title, 01362 description=group.description, 01363 conflict_handler=group.conflict_handler) 01364 01365 # map the actions to their new group 01366 for action in group._group_actions: 01367 group_map[action] = title_group_map[group.title] 01368 01369 # add container's mutually exclusive groups 01370 # NOTE: if add_mutually_exclusive_group ever gains title= and 01371 # description= then this code will need to be expanded as above 01372 for group in container._mutually_exclusive_groups: 01373 mutex_group = self.add_mutually_exclusive_group( 01374 required=group.required) 01375 01376 # map the actions to their new mutex group 01377 for action in group._group_actions: 01378 group_map[action] = mutex_group 01379 01380 # add all actions to this container or their group 01381 for action in container._actions: 01382 group_map.get(action, self)._add_action(action) 01383 01384 def _get_positional_kwargs(self, dest, **kwargs): 01385 # make sure required is not specified 01386 if 'required' in kwargs: 01387 msg = _("'required' is an invalid argument for positionals") 01388 raise TypeError(msg) 01389 01390 # mark positional arguments as required if at least one is 01391 # always required 01392 if kwargs.get('nargs') not in [OPTIONAL, ZERO_OR_MORE]: 01393 kwargs['required'] = True 01394 if kwargs.get('nargs') == ZERO_OR_MORE and 'default' not in kwargs: 01395 kwargs['required'] = True 01396 01397 # return the keyword arguments with no option strings 01398 return dict(kwargs, dest=dest, option_strings=[]) 01399 01400 def _get_optional_kwargs(self, *args, **kwargs): 01401 # determine short and long option strings 01402 option_strings = [] 01403 long_option_strings = [] 01404 for option_string in args: 01405 # error on strings that don't start with an appropriate prefix 01406 if not option_string[0] in self.prefix_chars: 01407 msg = _('invalid option string %r: ' 01408 'must start with a character %r') 01409 tup = option_string, self.prefix_chars 01410 raise ValueError(msg % tup) 01411 01412 # strings starting with two prefix characters are long options 01413 option_strings.append(option_string) 01414 if option_string[0] in self.prefix_chars: 01415 if len(option_string) > 1: 01416 if option_string[1] in self.prefix_chars: 01417 long_option_strings.append(option_string) 01418 01419 # infer destination, '--foo-bar' -> 'foo_bar' and '-x' -> 'x' 01420 dest = kwargs.pop('dest', None) 01421 if dest is None: 01422 if long_option_strings: 01423 dest_option_string = long_option_strings[0] 01424 else: 01425 dest_option_string = option_strings[0] 01426 dest = dest_option_string.lstrip(self.prefix_chars) 01427 if not dest: 01428 msg = _('dest= is required for options like %r') 01429 raise ValueError(msg % option_string) 01430 dest = dest.replace('-', '_') 01431 01432 # return the updated keyword arguments 01433 return dict(kwargs, dest=dest, option_strings=option_strings) 01434 01435 def _pop_action_class(self, kwargs, default=None): 01436 action = kwargs.pop('action', default) 01437 return self._registry_get('action', action, action) 01438 01439 def _get_handler(self): 01440 # determine function from conflict handler string 01441 handler_func_name = '_handle_conflict_%s' % self.conflict_handler 01442 try: 01443 return getattr(self, handler_func_name) 01444 except AttributeError: 01445 msg = _('invalid conflict_resolution value: %r') 01446 raise ValueError(msg % self.conflict_handler) 01447 01448 def _check_conflict(self, action): 01449 01450 # find all options that conflict with this option 01451 confl_optionals = [] 01452 for option_string in action.option_strings: 01453 if option_string in self._option_string_actions: 01454 confl_optional = self._option_string_actions[option_string] 01455 confl_optionals.append((option_string, confl_optional)) 01456 01457 # resolve any conflicts 01458 if confl_optionals: 01459 conflict_handler = self._get_handler() 01460 conflict_handler(action, confl_optionals) 01461 01462 def _handle_conflict_error(self, action, conflicting_actions): 01463 message = _('conflicting option string(s): %s') 01464 conflict_string = ', '.join([option_string 01465 for option_string, action 01466 in conflicting_actions]) 01467 raise ArgumentError(action, message % conflict_string) 01468 01469 def _handle_conflict_resolve(self, action, conflicting_actions): 01470 01471 # remove all conflicting options 01472 for option_string, action in conflicting_actions: 01473 01474 # remove the conflicting option 01475 action.option_strings.remove(option_string) 01476 self._option_string_actions.pop(option_string, None) 01477 01478 # if the option now has no option string, remove it from the 01479 # container holding it 01480 if not action.option_strings: 01481 action.container._remove_action(action) 01482 01483 01484 class _ArgumentGroup(_ActionsContainer): 01485 01486 def __init__(self, container, title=None, description=None, **kwargs): 01487 # add any missing keyword arguments by checking the container 01488 update = kwargs.setdefault 01489 update('conflict_handler', container.conflict_handler) 01490 update('prefix_chars', container.prefix_chars) 01491 update('argument_default', container.argument_default) 01492 super_init = super(_ArgumentGroup, self).__init__ 01493 super_init(description=description, **kwargs) 01494 01495 # group attributes 01496 self.title = title 01497 self._group_actions = [] 01498 01499 # share most attributes with the container 01500 self._registries = container._registries 01501 self._actions = container._actions 01502 self._option_string_actions = container._option_string_actions 01503 self._defaults = container._defaults 01504 self._has_negative_number_optionals = \ 01505 container._has_negative_number_optionals 01506 self._mutually_exclusive_groups = container._mutually_exclusive_groups 01507 01508 def _add_action(self, action): 01509 action = super(_ArgumentGroup, self)._add_action(action) 01510 self._group_actions.append(action) 01511 return action 01512 01513 def _remove_action(self, action): 01514 super(_ArgumentGroup, self)._remove_action(action) 01515 self._group_actions.remove(action) 01516 01517 01518 class _MutuallyExclusiveGroup(_ArgumentGroup): 01519 01520 def __init__(self, container, required=False): 01521 super(_MutuallyExclusiveGroup, self).__init__(container) 01522 self.required = required 01523 self._container = container 01524 01525 def _add_action(self, action): 01526 if action.required: 01527 msg = _('mutually exclusive arguments must be optional') 01528 raise ValueError(msg) 01529 action = self._container._add_action(action) 01530 self._group_actions.append(action) 01531 return action 01532 01533 def _remove_action(self, action): 01534 self._container._remove_action(action) 01535 self._group_actions.remove(action) 01536 01537 01538 class ArgumentParser(_AttributeHolder, _ActionsContainer): 01539 """Object for parsing command line strings into Python objects. 01540 01541 Keyword Arguments: 01542 - prog -- The name of the program (default: sys.argv[0]) 01543 - usage -- A usage message (default: auto-generated from arguments) 01544 - description -- A description of what the program does 01545 - epilog -- Text following the argument descriptions 01546 - parents -- Parsers whose arguments should be copied into this one 01547 - formatter_class -- HelpFormatter class for printing help messages 01548 - prefix_chars -- Characters that prefix optional arguments 01549 - fromfile_prefix_chars -- Characters that prefix files containing 01550 additional arguments 01551 - argument_default -- The default value for all arguments 01552 - conflict_handler -- String indicating how to handle conflicts 01553 - add_help -- Add a -h/-help option 01554 """ 01555 01556 def __init__(self, 01557 prog=None, 01558 usage=None, 01559 description=None, 01560 epilog=None, 01561 version=None, 01562 parents=[], 01563 formatter_class=HelpFormatter, 01564 prefix_chars='-', 01565 fromfile_prefix_chars=None, 01566 argument_default=None, 01567 conflict_handler='error', 01568 add_help=True): 01569 01570 if version is not None: 01571 import warnings 01572 warnings.warn( 01573 """The "version" argument to ArgumentParser is deprecated. """ 01574 """Please use """ 01575 """"add_argument(..., action='version', version="N", ...)" """ 01576 """instead""", DeprecationWarning) 01577 01578 superinit = super(ArgumentParser, self).__init__ 01579 superinit(description=description, 01580 prefix_chars=prefix_chars, 01581 argument_default=argument_default, 01582 conflict_handler=conflict_handler) 01583 01584 # default setting for prog 01585 if prog is None: 01586 prog = _os.path.basename(_sys.argv[0]) 01587 01588 self.prog = prog 01589 self.usage = usage 01590 self.epilog = epilog 01591 self.version = version 01592 self.formatter_class = formatter_class 01593 self.fromfile_prefix_chars = fromfile_prefix_chars 01594 self.add_help = add_help 01595 01596 add_group = self.add_argument_group 01597 self._positionals = add_group(_('positional arguments')) 01598 self._optionals = add_group(_('optional arguments')) 01599 self._subparsers = None 01600 01601 # register types 01602 def identity(string): 01603 return string 01604 self.register('type', None, identity) 01605 01606 # add help and version arguments if necessary 01607 # (using explicit default to override global argument_default) 01608 default_prefix = '-' if '-' in prefix_chars else prefix_chars[0] 01609 if self.add_help: 01610 self.add_argument( 01611 default_prefix+'h', default_prefix*2+'help', 01612 action='help', default=SUPPRESS, 01613 help=_('show this help message and exit')) 01614 if self.version: 01615 self.add_argument( 01616 default_prefix+'v', default_prefix*2+'version', 01617 action='version', default=SUPPRESS, 01618 version=self.version, 01619 help=_("show program's version number and exit")) 01620 01621 # add parent arguments and defaults 01622 for parent in parents: 01623 self._add_container_actions(parent) 01624 try: 01625 defaults = parent._defaults 01626 except AttributeError: 01627 pass 01628 else: 01629 self._defaults.update(defaults) 01630 01631 # ======================= 01632 # Pretty __repr__ methods 01633 # ======================= 01634 def _get_kwargs(self): 01635 names = [ 01636 'prog', 01637 'usage', 01638 'description', 01639 'version', 01640 'formatter_class', 01641 'conflict_handler', 01642 'add_help', 01643 ] 01644 return [(name, getattr(self, name)) for name in names] 01645 01646 # ================================== 01647 # Optional/Positional adding methods 01648 # ================================== 01649 def add_subparsers(self, **kwargs): 01650 if self._subparsers is not None: 01651 self.error(_('cannot have multiple subparser arguments')) 01652 01653 # add the parser class to the arguments if it's not present 01654 kwargs.setdefault('parser_class', type(self)) 01655 01656 if 'title' in kwargs or 'description' in kwargs: 01657 title = _(kwargs.pop('title', 'subcommands')) 01658 description = _(kwargs.pop('description', None)) 01659 self._subparsers = self.add_argument_group(title, description) 01660 else: 01661 self._subparsers = self._positionals 01662 01663 # prog defaults to the usage message of this parser, skipping 01664 # optional arguments and with no "usage:" prefix 01665 if kwargs.get('prog') is None: 01666 formatter = self._get_formatter() 01667 positionals = self._get_positional_actions() 01668 groups = self._mutually_exclusive_groups 01669 formatter.add_usage(self.usage, positionals, groups, '') 01670 kwargs['prog'] = formatter.format_help().strip() 01671 01672 # create the parsers action and add it to the positionals list 01673 parsers_class = self._pop_action_class(kwargs, 'parsers') 01674 action = parsers_class(option_strings=[], **kwargs) 01675 self._subparsers._add_action(action) 01676 01677 # return the created parsers action 01678 return action 01679 01680 def _add_action(self, action): 01681 if action.option_strings: 01682 self._optionals._add_action(action) 01683 else: 01684 self._positionals._add_action(action) 01685 return action 01686 01687 def _get_optional_actions(self): 01688 return [action 01689 for action in self._actions 01690 if action.option_strings] 01691 01692 def _get_positional_actions(self): 01693 return [action 01694 for action in self._actions 01695 if not action.option_strings] 01696 01697 # ===================================== 01698 # Command line argument parsing methods 01699 # ===================================== 01700 def parse_args(self, args=None, namespace=None): 01701 args, argv = self.parse_known_args(args, namespace) 01702 if argv: 01703 msg = _('unrecognized arguments: %s') 01704 self.error(msg % ' '.join(argv)) 01705 return args 01706 01707 def parse_known_args(self, args=None, namespace=None): 01708 if args is None: 01709 # args default to the system args 01710 args = _sys.argv[1:] 01711 else: 01712 # make sure that args are mutable 01713 args = list(args) 01714 01715 # default Namespace built from parser defaults 01716 if namespace is None: 01717 namespace = Namespace() 01718 01719 # add any action defaults that aren't present 01720 for action in self._actions: 01721 if action.dest is not SUPPRESS: 01722 if not hasattr(namespace, action.dest): 01723 if action.default is not SUPPRESS: 01724 setattr(namespace, action.dest, action.default) 01725 01726 # add any parser defaults that aren't present 01727 for dest in self._defaults: 01728 if not hasattr(namespace, dest): 01729 setattr(namespace, dest, self._defaults[dest]) 01730 01731 # parse the arguments and exit if there are any errors 01732 try: 01733 namespace, args = self._parse_known_args(args, namespace) 01734 if hasattr(namespace, _UNRECOGNIZED_ARGS_ATTR): 01735 args.extend(getattr(namespace, _UNRECOGNIZED_ARGS_ATTR)) 01736 delattr(namespace, _UNRECOGNIZED_ARGS_ATTR) 01737 return namespace, args 01738 except ArgumentError: 01739 err = _sys.exc_info()[1] 01740 self.error(str(err)) 01741 01742 def _parse_known_args(self, arg_strings, namespace): 01743 # replace arg strings that are file references 01744 if self.fromfile_prefix_chars is not None: 01745 arg_strings = self._read_args_from_files(arg_strings) 01746 01747 # map all mutually exclusive arguments to the other arguments 01748 # they can't occur with 01749 action_conflicts = {} 01750 for mutex_group in self._mutually_exclusive_groups: 01751 group_actions = mutex_group._group_actions 01752 for i, mutex_action in enumerate(mutex_group._group_actions): 01753 conflicts = action_conflicts.setdefault(mutex_action, []) 01754 conflicts.extend(group_actions[:i]) 01755 conflicts.extend(group_actions[i + 1:]) 01756 01757 # find all option indices, and determine the arg_string_pattern 01758 # which has an 'O' if there is an option at an index, 01759 # an 'A' if there is an argument, or a '-' if there is a '--' 01760 option_string_indices = {} 01761 arg_string_pattern_parts = [] 01762 arg_strings_iter = iter(arg_strings) 01763 for i, arg_string in enumerate(arg_strings_iter): 01764 01765 # all args after -- are non-options 01766 if arg_string == '--': 01767 arg_string_pattern_parts.append('-') 01768 for arg_string in arg_strings_iter: 01769 arg_string_pattern_parts.append('A') 01770 01771 # otherwise, add the arg to the arg strings 01772 # and note the index if it was an option 01773 else: 01774 option_tuple = self._parse_optional(arg_string) 01775 if option_tuple is None: 01776 pattern = 'A' 01777 else: 01778 option_string_indices[i] = option_tuple 01779 pattern = 'O' 01780 arg_string_pattern_parts.append(pattern) 01781 01782 # join the pieces together to form the pattern 01783 arg_strings_pattern = ''.join(arg_string_pattern_parts) 01784 01785 # converts arg strings to the appropriate and then takes the action 01786 seen_actions = set() 01787 seen_non_default_actions = set() 01788 01789 def take_action(action, argument_strings, option_string=None): 01790 seen_actions.add(action) 01791 argument_values = self._get_values(action, argument_strings) 01792 01793 # error if this argument is not allowed with other previously 01794 # seen arguments, assuming that actions that use the default 01795 # value don't really count as "present" 01796 if argument_values is not action.default: 01797 seen_non_default_actions.add(action) 01798 for conflict_action in action_conflicts.get(action, []): 01799 if conflict_action in seen_non_default_actions: 01800 msg = _('not allowed with argument %s') 01801 action_name = _get_action_name(conflict_action) 01802 raise ArgumentError(action, msg % action_name) 01803 01804 # take the action if we didn't receive a SUPPRESS value 01805 # (e.g. from a default) 01806 if argument_values is not SUPPRESS: 01807 action(self, namespace, argument_values, option_string) 01808 01809 # function to convert arg_strings into an optional action 01810 def consume_optional(start_index): 01811 01812 # get the optional identified at this index 01813 option_tuple = option_string_indices[start_index] 01814 action, option_string, explicit_arg = option_tuple 01815 01816 # identify additional optionals in the same arg string 01817 # (e.g. -xyz is the same as -x -y -z if no args are required) 01818 match_argument = self._match_argument 01819 action_tuples = [] 01820 while True: 01821 01822 # if we found no optional action, skip it 01823 if action is None: 01824 extras.append(arg_strings[start_index]) 01825 return start_index + 1 01826 01827 # if there is an explicit argument, try to match the 01828 # optional's string arguments to only this 01829 if explicit_arg is not None: 01830 arg_count = match_argument(action, 'A') 01831 01832 # if the action is a single-dash option and takes no 01833 # arguments, try to parse more single-dash options out 01834 # of the tail of the option string 01835 chars = self.prefix_chars 01836 if arg_count == 0 and option_string[1] not in chars: 01837 action_tuples.append((action, [], option_string)) 01838 char = option_string[0] 01839 option_string = char + explicit_arg[0] 01840 new_explicit_arg = explicit_arg[1:] or None 01841 optionals_map = self._option_string_actions 01842 if option_string in optionals_map: 01843 action = optionals_map[option_string] 01844 explicit_arg = new_explicit_arg 01845 else: 01846 msg = _('ignored explicit argument %r') 01847 raise ArgumentError(action, msg % explicit_arg) 01848 01849 # if the action expect exactly one argument, we've 01850 # successfully matched the option; exit the loop 01851 elif arg_count == 1: 01852 stop = start_index + 1 01853 args = [explicit_arg] 01854 action_tuples.append((action, args, option_string)) 01855 break 01856 01857 # error if a double-dash option did not use the 01858 # explicit argument 01859 else: 01860 msg = _('ignored explicit argument %r') 01861 raise ArgumentError(action, msg % explicit_arg) 01862 01863 # if there is no explicit argument, try to match the 01864 # optional's string arguments with the following strings 01865 # if successful, exit the loop 01866 else: 01867 start = start_index + 1 01868 selected_patterns = arg_strings_pattern[start:] 01869 arg_count = match_argument(action, selected_patterns) 01870 stop = start + arg_count 01871 args = arg_strings[start:stop] 01872 action_tuples.append((action, args, option_string)) 01873 break 01874 01875 # add the Optional to the list and return the index at which 01876 # the Optional's string args stopped 01877 assert action_tuples 01878 for action, args, option_string in action_tuples: 01879 take_action(action, args, option_string) 01880 return stop 01881 01882 # the list of Positionals left to be parsed; this is modified 01883 # by consume_positionals() 01884 positionals = self._get_positional_actions() 01885 01886 # function to convert arg_strings into positional actions 01887 def consume_positionals(start_index): 01888 # match as many Positionals as possible 01889 match_partial = self._match_arguments_partial 01890 selected_pattern = arg_strings_pattern[start_index:] 01891 arg_counts = match_partial(positionals, selected_pattern) 01892 01893 # slice off the appropriate arg strings for each Positional 01894 # and add the Positional and its args to the list 01895 for action, arg_count in zip(positionals, arg_counts): 01896 args = arg_strings[start_index: start_index + arg_count] 01897 start_index += arg_count 01898 take_action(action, args) 01899 01900 # slice off the Positionals that we just parsed and return the 01901 # index at which the Positionals' string args stopped 01902 positionals[:] = positionals[len(arg_counts):] 01903 return start_index 01904 01905 # consume Positionals and Optionals alternately, until we have 01906 # passed the last option string 01907 extras = [] 01908 start_index = 0 01909 if option_string_indices: 01910 max_option_string_index = max(option_string_indices) 01911 else: 01912 max_option_string_index = -1 01913 while start_index <= max_option_string_index: 01914 01915 # consume any Positionals preceding the next option 01916 next_option_string_index = min([ 01917 index 01918 for index in option_string_indices 01919 if index >= start_index]) 01920 if start_index != next_option_string_index: 01921 positionals_end_index = consume_positionals(start_index) 01922 01923 # only try to parse the next optional if we didn't consume 01924 # the option string during the positionals parsing 01925 if positionals_end_index > start_index: 01926 start_index = positionals_end_index 01927 continue 01928 else: 01929 start_index = positionals_end_index 01930 01931 # if we consumed all the positionals we could and we're not 01932 # at the index of an option string, there were extra arguments 01933 if start_index not in option_string_indices: 01934 strings = arg_strings[start_index:next_option_string_index] 01935 extras.extend(strings) 01936 start_index = next_option_string_index 01937 01938 # consume the next optional and any arguments for it 01939 start_index = consume_optional(start_index) 01940 01941 # consume any positionals following the last Optional 01942 stop_index = consume_positionals(start_index) 01943 01944 # if we didn't consume all the argument strings, there were extras 01945 extras.extend(arg_strings[stop_index:]) 01946 01947 # if we didn't use all the Positional objects, there were too few 01948 # arg strings supplied. 01949 if positionals: 01950 self.error(_('too few arguments')) 01951 01952 # make sure all required actions were present, and convert defaults. 01953 for action in self._actions: 01954 if action not in seen_actions: 01955 if action.required: 01956 name = _get_action_name(action) 01957 self.error(_('argument %s is required') % name) 01958 else: 01959 # Convert action default now instead of doing it before 01960 # parsing arguments to avoid calling convert functions 01961 # twice (which may fail) if the argument was given, but 01962 # only if it was defined already in the namespace 01963 if (action.default is not None and 01964 isinstance(action.default, basestring) and 01965 hasattr(namespace, action.dest) and 01966 action.default is getattr(namespace, action.dest)): 01967 setattr(namespace, action.dest, 01968 self._get_value(action, action.default)) 01969 01970 # make sure all required groups had one option present 01971 for group in self._mutually_exclusive_groups: 01972 if group.required: 01973 for action in group._group_actions: 01974 if action in seen_non_default_actions: 01975 break 01976 01977 # if no actions were used, report the error 01978 else: 01979 names = [_get_action_name(action) 01980 for action in group._group_actions 01981 if action.help is not SUPPRESS] 01982 msg = _('one of the arguments %s is required') 01983 self.error(msg % ' '.join(names)) 01984 01985 # return the updated namespace and the extra arguments 01986 return namespace, extras 01987 01988 def _read_args_from_files(self, arg_strings): 01989 # expand arguments referencing files 01990 new_arg_strings = [] 01991 for arg_string in arg_strings: 01992 01993 # for regular arguments, just add them back into the list 01994 if not arg_string or arg_string[0] not in self.fromfile_prefix_chars: 01995 new_arg_strings.append(arg_string) 01996 01997 # replace arguments referencing files with the file content 01998 else: 01999 try: 02000 args_file = open(arg_string[1:]) 02001 try: 02002 arg_strings = [] 02003 for arg_line in args_file.read().splitlines(): 02004 for arg in self.convert_arg_line_to_args(arg_line): 02005 arg_strings.append(arg) 02006 arg_strings = self._read_args_from_files(arg_strings) 02007 new_arg_strings.extend(arg_strings) 02008 finally: 02009 args_file.close() 02010 except IOError: 02011 err = _sys.exc_info()[1] 02012 self.error(str(err)) 02013 02014 # return the modified argument list 02015 return new_arg_strings 02016 02017 def convert_arg_line_to_args(self, arg_line): 02018 return [arg_line] 02019 02020 def _match_argument(self, action, arg_strings_pattern): 02021 # match the pattern for this action to the arg strings 02022 nargs_pattern = self._get_nargs_pattern(action) 02023 match = _re.match(nargs_pattern, arg_strings_pattern) 02024 02025 # raise an exception if we weren't able to find a match 02026 if match is None: 02027 nargs_errors = { 02028 None: _('expected one argument'), 02029 OPTIONAL: _('expected at most one argument'), 02030 ONE_OR_MORE: _('expected at least one argument'), 02031 } 02032 default = _('expected %s argument(s)') % action.nargs 02033 msg = nargs_errors.get(action.nargs, default) 02034 raise ArgumentError(action, msg) 02035 02036 # return the number of arguments matched 02037 return len(match.group(1)) 02038 02039 def _match_arguments_partial(self, actions, arg_strings_pattern): 02040 # progressively shorten the actions list by slicing off the 02041 # final actions until we find a match 02042 result = [] 02043 for i in range(len(actions), 0, -1): 02044 actions_slice = actions[:i] 02045 pattern = ''.join([self._get_nargs_pattern(action) 02046 for action in actions_slice]) 02047 match = _re.match(pattern, arg_strings_pattern) 02048 if match is not None: 02049 result.extend([len(string) for string in match.groups()]) 02050 break 02051 02052 # return the list of arg string counts 02053 return result 02054 02055 def _parse_optional(self, arg_string): 02056 # if it's an empty string, it was meant to be a positional 02057 if not arg_string: 02058 return None 02059 02060 # if it doesn't start with a prefix, it was meant to be positional 02061 if not arg_string[0] in self.prefix_chars: 02062 return None 02063 02064 # if the option string is present in the parser, return the action 02065 if arg_string in self._option_string_actions: 02066 action = self._option_string_actions[arg_string] 02067 return action, arg_string, None 02068 02069 # if it's just a single character, it was meant to be positional 02070 if len(arg_string) == 1: 02071 return None 02072 02073 # if the option string before the "=" is present, return the action 02074 if '=' in arg_string: 02075 option_string, explicit_arg = arg_string.split('=', 1) 02076 if option_string in self._option_string_actions: 02077 action = self._option_string_actions[option_string] 02078 return action, option_string, explicit_arg 02079 02080 # search through all possible prefixes of the option string 02081 # and all actions in the parser for possible interpretations 02082 option_tuples = self._get_option_tuples(arg_string) 02083 02084 # if multiple actions match, the option string was ambiguous 02085 if len(option_tuples) > 1: 02086 options = ', '.join([option_string 02087 for action, option_string, explicit_arg in option_tuples]) 02088 tup = arg_string, options 02089 self.error(_('ambiguous option: %s could match %s') % tup) 02090 02091 # if exactly one action matched, this segmentation is good, 02092 # so return the parsed action 02093 elif len(option_tuples) == 1: 02094 option_tuple, = option_tuples 02095 return option_tuple 02096 02097 # if it was not found as an option, but it looks like a negative 02098 # number, it was meant to be positional 02099 # unless there are negative-number-like options 02100 if self._negative_number_matcher.match(arg_string): 02101 if not self._has_negative_number_optionals: 02102 return None 02103 02104 # if it contains a space, it was meant to be a positional 02105 if ' ' in arg_string: 02106 return None 02107 02108 # it was meant to be an optional but there is no such option 02109 # in this parser (though it might be a valid option in a subparser) 02110 return None, arg_string, None 02111 02112 def _get_option_tuples(self, option_string): 02113 result = [] 02114 02115 # option strings starting with two prefix characters are only 02116 # split at the '=' 02117 chars = self.prefix_chars 02118 if option_string[0] in chars and option_string[1] in chars: 02119 if '=' in option_string: 02120 option_prefix, explicit_arg = option_string.split('=', 1) 02121 else: 02122 option_prefix = option_string 02123 explicit_arg = None 02124 for option_string in self._option_string_actions: 02125 if option_string.startswith(option_prefix): 02126 action = self._option_string_actions[option_string] 02127 tup = action, option_string, explicit_arg 02128 result.append(tup) 02129 02130 # single character options can be concatenated with their arguments 02131 # but multiple character options always have to have their argument 02132 # separate 02133 elif option_string[0] in chars and option_string[1] not in chars: 02134 option_prefix = option_string 02135 explicit_arg = None 02136 short_option_prefix = option_string[:2] 02137 short_explicit_arg = option_string[2:] 02138 02139 for option_string in self._option_string_actions: 02140 if option_string == short_option_prefix: 02141 action = self._option_string_actions[option_string] 02142 tup = action, option_string, short_explicit_arg 02143 result.append(tup) 02144 elif option_string.startswith(option_prefix): 02145 action = self._option_string_actions[option_string] 02146 tup = action, option_string, explicit_arg 02147 result.append(tup) 02148 02149 # shouldn't ever get here 02150 else: 02151 self.error(_('unexpected option string: %s') % option_string) 02152 02153 # return the collected option tuples 02154 return result 02155 02156 def _get_nargs_pattern(self, action): 02157 # in all examples below, we have to allow for '--' args 02158 # which are represented as '-' in the pattern 02159 nargs = action.nargs 02160 02161 # the default (None) is assumed to be a single argument 02162 if nargs is None: 02163 nargs_pattern = '(-*A-*)' 02164 02165 # allow zero or one arguments 02166 elif nargs == OPTIONAL: 02167 nargs_pattern = '(-*A?-*)' 02168 02169 # allow zero or more arguments 02170 elif nargs == ZERO_OR_MORE: 02171 nargs_pattern = '(-*[A-]*)' 02172 02173 # allow one or more arguments 02174 elif nargs == ONE_OR_MORE: 02175 nargs_pattern = '(-*A[A-]*)' 02176 02177 # allow any number of options or arguments 02178 elif nargs == REMAINDER: 02179 nargs_pattern = '([-AO]*)' 02180 02181 # allow one argument followed by any number of options or arguments 02182 elif nargs == PARSER: 02183 nargs_pattern = '(-*A[-AO]*)' 02184 02185 # all others should be integers 02186 else: 02187 nargs_pattern = '(-*%s-*)' % '-*'.join('A' * nargs) 02188 02189 # if this is an optional action, -- is not allowed 02190 if action.option_strings: 02191 nargs_pattern = nargs_pattern.replace('-*', '') 02192 nargs_pattern = nargs_pattern.replace('-', '') 02193 02194 # return the pattern 02195 return nargs_pattern 02196 02197 # ======================== 02198 # Value conversion methods 02199 # ======================== 02200 def _get_values(self, action, arg_strings): 02201 # for everything but PARSER, REMAINDER args, strip out first '--' 02202 if action.nargs not in [PARSER, REMAINDER]: 02203 try: 02204 arg_strings.remove('--') 02205 except ValueError: 02206 pass 02207 02208 # optional argument produces a default when not present 02209 if not arg_strings and action.nargs == OPTIONAL: 02210 if action.option_strings: 02211 value = action.const 02212 else: 02213 value = action.default 02214 if isinstance(value, basestring): 02215 value = self._get_value(action, value) 02216 self._check_value(action, value) 02217 02218 # when nargs='*' on a positional, if there were no command-line 02219 # args, use the default if it is anything other than None 02220 elif (not arg_strings and action.nargs == ZERO_OR_MORE and 02221 not action.option_strings): 02222 if action.default is not None: 02223 value = action.default 02224 else: 02225 value = arg_strings 02226 self._check_value(action, value) 02227 02228 # single argument or optional argument produces a single value 02229 elif len(arg_strings) == 1 and action.nargs in [None, OPTIONAL]: 02230 arg_string, = arg_strings 02231 value = self._get_value(action, arg_string) 02232 self._check_value(action, value) 02233 02234 # REMAINDER arguments convert all values, checking none 02235 elif action.nargs == REMAINDER: 02236 value = [self._get_value(action, v) for v in arg_strings] 02237 02238 # PARSER arguments convert all values, but check only the first 02239 elif action.nargs == PARSER: 02240 value = [self._get_value(action, v) for v in arg_strings] 02241 self._check_value(action, value[0]) 02242 02243 # all other types of nargs produce a list 02244 else: 02245 value = [self._get_value(action, v) for v in arg_strings] 02246 for v in value: 02247 self._check_value(action, v) 02248 02249 # return the converted value 02250 return value 02251 02252 def _get_value(self, action, arg_string): 02253 type_func = self._registry_get('type', action.type, action.type) 02254 if not _callable(type_func): 02255 msg = _('%r is not callable') 02256 raise ArgumentError(action, msg % type_func) 02257 02258 # convert the value to the appropriate type 02259 try: 02260 result = type_func(arg_string) 02261 02262 # ArgumentTypeErrors indicate errors 02263 except ArgumentTypeError: 02264 name = getattr(action.type, '__name__', repr(action.type)) 02265 msg = str(_sys.exc_info()[1]) 02266 raise ArgumentError(action, msg) 02267 02268 # TypeErrors or ValueErrors also indicate errors 02269 except (TypeError, ValueError): 02270 name = getattr(action.type, '__name__', repr(action.type)) 02271 msg = _('invalid %s value: %r') 02272 raise ArgumentError(action, msg % (name, arg_string)) 02273 02274 # return the converted value 02275 return result 02276 02277 def _check_value(self, action, value): 02278 # converted value must be one of the choices (if specified) 02279 if action.choices is not None and value not in action.choices: 02280 tup = value, ', '.join(map(repr, action.choices)) 02281 msg = _('invalid choice: %r (choose from %s)') % tup 02282 raise ArgumentError(action, msg) 02283 02284 # ======================= 02285 # Help-formatting methods 02286 # ======================= 02287 def format_usage(self): 02288 formatter = self._get_formatter() 02289 formatter.add_usage(self.usage, self._actions, 02290 self._mutually_exclusive_groups) 02291 return formatter.format_help() 02292 02293 def format_help(self): 02294 formatter = self._get_formatter() 02295 02296 # usage 02297 formatter.add_usage(self.usage, self._actions, 02298 self._mutually_exclusive_groups) 02299 02300 # description 02301 formatter.add_text(self.description) 02302 02303 # positionals, optionals and user-defined groups 02304 for action_group in self._action_groups: 02305 formatter.start_section(action_group.title) 02306 formatter.add_text(action_group.description) 02307 formatter.add_arguments(action_group._group_actions) 02308 formatter.end_section() 02309 02310 # epilog 02311 formatter.add_text(self.epilog) 02312 02313 # determine help from format above 02314 return formatter.format_help() 02315 02316 def format_version(self): 02317 import warnings 02318 warnings.warn( 02319 'The format_version method is deprecated -- the "version" ' 02320 'argument to ArgumentParser is no longer supported.', 02321 DeprecationWarning) 02322 formatter = self._get_formatter() 02323 formatter.add_text(self.version) 02324 return formatter.format_help() 02325 02326 def _get_formatter(self): 02327 return self.formatter_class(prog=self.prog) 02328 02329 # ===================== 02330 # Help-printing methods 02331 # ===================== 02332 def print_usage(self, file=None): 02333 if file is None: 02334 file = _sys.stdout 02335 self._print_message(self.format_usage(), file) 02336 02337 def print_help(self, file=None): 02338 if file is None: 02339 file = _sys.stdout 02340 self._print_message(self.format_help(), file) 02341 02342 def print_version(self, file=None): 02343 import warnings 02344 warnings.warn( 02345 'The print_version method is deprecated -- the "version" ' 02346 'argument to ArgumentParser is no longer supported.', 02347 DeprecationWarning) 02348 self._print_message(self.format_version(), file) 02349 02350 def _print_message(self, message, file=None): 02351 if message: 02352 if file is None: 02353 file = _sys.stderr 02354 file.write(message) 02355 02356 # =============== 02357 # Exiting methods 02358 # =============== 02359 def exit(self, status=0, message=None): 02360 if message: 02361 self._print_message(message, _sys.stderr) 02362 _sys.exit(status) 02363 02364 def error(self, message): 02365 """error(message: string) 02366 02367 Prints a usage message incorporating the message to stderr and 02368 exits. 02369 02370 If you override this in a subclass, it should not return -- it 02371 should either exit or raise an exception. 02372 """ 02373 self.print_usage(_sys.stderr) 02374 self.exit(2, _('%s: error: %s\n') % (self.prog, message))