Back to index

python3.2  3.2.2
Public Member Functions | Public Attributes | Private Member Functions | Private Attributes
argparse.ArgumentParser Class Reference
Inheritance diagram for argparse.ArgumentParser:
Inheritance graph
[legend]
Collaboration diagram for argparse.ArgumentParser:
Collaboration graph
[legend]

List of all members.

Public Member Functions

def __init__
def add_subparsers
def parse_args
def parse_known_args
def convert_arg_line_to_args
def format_usage
def format_help
def format_version
def print_usage
def print_help
def print_version
def exit
def error
def __repr__
def register
def set_defaults
def get_default
def add_argument
def add_argument_group
def add_mutually_exclusive_group

Public Attributes

 prog
 usage
 epilog
 version
 formatter_class
 fromfile_prefix_chars
 add_help
_PyObject_HEAD_EXTRA Py_ssize_t ob_refcnt
struct _typeobjectob_type
 description
 argument_default
 prefix_chars
 conflict_handler
_PyObject_HEAD_EXTRA Py_ssize_t ob_refcnt
struct _typeobjectob_type

Private Member Functions

def _get_kwargs
def _add_action
def _get_optional_actions
def _get_positional_actions
def _parse_known_args
def _read_args_from_files
def _match_argument
def _match_arguments_partial
def _parse_optional
def _get_option_tuples
def _get_nargs_pattern
def _get_values
def _get_value
def _check_value
def _get_formatter
def _print_message

Private Attributes

 _positionals
 _optionals
 _subparsers

Detailed Description

Object for parsing command line strings into Python objects.

Keyword Arguments:
    - prog -- The name of the program (default: sys.argv[0])
    - usage -- A usage message (default: auto-generated from arguments)
    - description -- A description of what the program does
    - epilog -- Text following the argument descriptions
    - parents -- Parsers whose arguments should be copied into this one
    - formatter_class -- HelpFormatter class for printing help messages
    - prefix_chars -- Characters that prefix optional arguments
    - fromfile_prefix_chars -- Characters that prefix files containing
        additional arguments
    - argument_default -- The default value for all arguments
    - conflict_handler -- String indicating how to handle conflicts
    - add_help -- Add a -h/-help option

Definition at line 1538 of file argparse.py.


Constructor & Destructor Documentation

def argparse.ArgumentParser.__init__ (   self,
  prog = None,
  usage = None,
  description = None,
  epilog = None,
  version = None,
  parents = [],
  formatter_class = HelpFormatter,
  prefix_chars = '-',
  fromfile_prefix_chars = None,
  argument_default = None,
  conflict_handler = 'error',
  add_help = True 
)

Definition at line 1568 of file argparse.py.

01568 
01569                  add_help=True):
01570 
01571         if version is not None:
01572             import warnings
01573             warnings.warn(
01574                 """The "version" argument to ArgumentParser is deprecated. """
01575                 """Please use """
01576                 """"add_argument(..., action='version', version="N", ...)" """
01577                 """instead""", DeprecationWarning)
01578 
01579         superinit = super(ArgumentParser, self).__init__
01580         superinit(description=description,
01581                   prefix_chars=prefix_chars,
01582                   argument_default=argument_default,
01583                   conflict_handler=conflict_handler)
01584 
01585         # default setting for prog
01586         if prog is None:
01587             prog = _os.path.basename(_sys.argv[0])
01588 
01589         self.prog = prog
01590         self.usage = usage
01591         self.epilog = epilog
01592         self.version = version
01593         self.formatter_class = formatter_class
01594         self.fromfile_prefix_chars = fromfile_prefix_chars
01595         self.add_help = add_help
01596 
01597         add_group = self.add_argument_group
01598         self._positionals = add_group(_('positional arguments'))
01599         self._optionals = add_group(_('optional arguments'))
01600         self._subparsers = None
01601 
01602         # register types
01603         def identity(string):
01604             return string
01605         self.register('type', None, identity)
01606 
01607         # add help and version arguments if necessary
01608         # (using explicit default to override global argument_default)
01609         default_prefix = '-' if '-' in prefix_chars else prefix_chars[0]
01610         if self.add_help:
01611             self.add_argument(
01612                 default_prefix+'h', default_prefix*2+'help',
01613                 action='help', default=SUPPRESS,
01614                 help=_('show this help message and exit'))
01615         if self.version:
01616             self.add_argument(
01617                 default_prefix+'v', default_prefix*2+'version',
01618                 action='version', default=SUPPRESS,
01619                 version=self.version,
01620                 help=_("show program's version number and exit"))
01621 
01622         # add parent arguments and defaults
01623         for parent in parents:
01624             self._add_container_actions(parent)
01625             try:
01626                 defaults = parent._defaults
01627             except AttributeError:
01628                 pass
01629             else:
01630                 self._defaults.update(defaults)

Here is the call graph for this function:

Here is the caller graph for this function:


Member Function Documentation

def argparse._AttributeHolder.__repr__ (   self) [inherited]

Definition at line 121 of file argparse.py.

00121 
00122     def __repr__(self):
00123         type_name = type(self).__name__
00124         arg_strings = []
00125         for arg in self._get_args():
00126             arg_strings.append(repr(arg))
00127         for name, value in self._get_kwargs():
00128             arg_strings.append('%s=%r' % (name, value))
00129         return '%s(%s)' % (type_name, ', '.join(arg_strings))

Here is the call graph for this function:

def argparse.ArgumentParser._add_action (   self,
  action 
) [private]

Reimplemented from argparse._ActionsContainer.

Definition at line 1680 of file argparse.py.

01680 
01681     def _add_action(self, action):
01682         if action.option_strings:
01683             self._optionals._add_action(action)
01684         else:
01685             self._positionals._add_action(action)
01686         return action

def argparse.ArgumentParser._check_value (   self,
  action,
  value 
) [private]

Definition at line 2267 of file argparse.py.

02267 
02268     def _check_value(self, action, value):
02269         # converted value must be one of the choices (if specified)
02270         if action.choices is not None and value not in action.choices:
02271             args = {'value': value,
02272                     'choices': ', '.join(map(repr, action.choices))}
02273             msg = _('invalid choice: %(value)r (choose from %(choices)s)')
02274             raise ArgumentError(action, msg % args)

Here is the caller graph for this function:

def argparse.ArgumentParser._get_formatter (   self) [private]

Definition at line 2317 of file argparse.py.

02317 
02318     def _get_formatter(self):
02319         return self.formatter_class(prog=self.prog)

Here is the caller graph for this function:

def argparse.ArgumentParser._get_kwargs (   self) [private]

Reimplemented from argparse._AttributeHolder.

Definition at line 1634 of file argparse.py.

01634 
01635     def _get_kwargs(self):
01636         names = [
01637             'prog',
01638             'usage',
01639             'description',
01640             'version',
01641             'formatter_class',
01642             'conflict_handler',
01643             'add_help',
01644         ]
01645         return [(name, getattr(self, name)) for name in names]

Here is the call graph for this function:

def argparse.ArgumentParser._get_nargs_pattern (   self,
  action 
) [private]

Definition at line 2148 of file argparse.py.

02148 
02149     def _get_nargs_pattern(self, action):
02150         # in all examples below, we have to allow for '--' args
02151         # which are represented as '-' in the pattern
02152         nargs = action.nargs
02153 
02154         # the default (None) is assumed to be a single argument
02155         if nargs is None:
02156             nargs_pattern = '(-*A-*)'
02157 
02158         # allow zero or one arguments
02159         elif nargs == OPTIONAL:
02160             nargs_pattern = '(-*A?-*)'
02161 
02162         # allow zero or more arguments
02163         elif nargs == ZERO_OR_MORE:
02164             nargs_pattern = '(-*[A-]*)'
02165 
02166         # allow one or more arguments
02167         elif nargs == ONE_OR_MORE:
02168             nargs_pattern = '(-*A[A-]*)'
02169 
02170         # allow any number of options or arguments
02171         elif nargs == REMAINDER:
02172             nargs_pattern = '([-AO]*)'
02173 
02174         # allow one argument followed by any number of options or arguments
02175         elif nargs == PARSER:
02176             nargs_pattern = '(-*A[-AO]*)'
02177 
02178         # all others should be integers
02179         else:
02180             nargs_pattern = '(-*%s-*)' % '-*'.join('A' * nargs)
02181 
02182         # if this is an optional action, -- is not allowed
02183         if action.option_strings:
02184             nargs_pattern = nargs_pattern.replace('-*', '')
02185             nargs_pattern = nargs_pattern.replace('-', '')
02186 
02187         # return the pattern
02188         return nargs_pattern

Here is the caller graph for this function:

def argparse.ArgumentParser._get_option_tuples (   self,
  option_string 
) [private]

Definition at line 2104 of file argparse.py.

02104 
02105     def _get_option_tuples(self, option_string):
02106         result = []
02107 
02108         # option strings starting with two prefix characters are only
02109         # split at the '='
02110         chars = self.prefix_chars
02111         if option_string[0] in chars and option_string[1] in chars:
02112             if '=' in option_string:
02113                 option_prefix, explicit_arg = option_string.split('=', 1)
02114             else:
02115                 option_prefix = option_string
02116                 explicit_arg = None
02117             for option_string in self._option_string_actions:
02118                 if option_string.startswith(option_prefix):
02119                     action = self._option_string_actions[option_string]
02120                     tup = action, option_string, explicit_arg
02121                     result.append(tup)
02122 
02123         # single character options can be concatenated with their arguments
02124         # but multiple character options always have to have their argument
02125         # separate
02126         elif option_string[0] in chars and option_string[1] not in chars:
02127             option_prefix = option_string
02128             explicit_arg = None
02129             short_option_prefix = option_string[:2]
02130             short_explicit_arg = option_string[2:]
02131 
02132             for option_string in self._option_string_actions:
02133                 if option_string == short_option_prefix:
02134                     action = self._option_string_actions[option_string]
02135                     tup = action, option_string, short_explicit_arg
02136                     result.append(tup)
02137                 elif option_string.startswith(option_prefix):
02138                     action = self._option_string_actions[option_string]
02139                     tup = action, option_string, explicit_arg
02140                     result.append(tup)
02141 
02142         # shouldn't ever get here
02143         else:
02144             self.error(_('unexpected option string: %s') % option_string)
02145 
02146         # return the collected option tuples
02147         return result

Here is the call graph for this function:

Here is the caller graph for this function:

Definition at line 1687 of file argparse.py.

01687 
01688     def _get_optional_actions(self):
01689         return [action
01690                 for action in self._actions
01691                 if action.option_strings]

Definition at line 1692 of file argparse.py.

01692 
01693     def _get_positional_actions(self):
01694         return [action
01695                 for action in self._actions
01696                 if not action.option_strings]

Here is the caller graph for this function:

def argparse.ArgumentParser._get_value (   self,
  action,
  arg_string 
) [private]

Definition at line 2241 of file argparse.py.

02241 
02242     def _get_value(self, action, arg_string):
02243         type_func = self._registry_get('type', action.type, action.type)
02244         if not _callable(type_func):
02245             msg = _('%r is not callable')
02246             raise ArgumentError(action, msg % type_func)
02247 
02248         # convert the value to the appropriate type
02249         try:
02250             result = type_func(arg_string)
02251 
02252         # ArgumentTypeErrors indicate errors
02253         except ArgumentTypeError:
02254             name = getattr(action.type, '__name__', repr(action.type))
02255             msg = str(_sys.exc_info()[1])
02256             raise ArgumentError(action, msg)
02257 
02258         # TypeErrors or ValueErrors also indicate errors
02259         except (TypeError, ValueError):
02260             name = getattr(action.type, '__name__', repr(action.type))
02261             args = {'type': name, 'value': arg_string}
02262             msg = _('invalid %(type)s value: %(value)r')
02263             raise ArgumentError(action, msg % args)
02264 
02265         # return the converted value
02266         return result

Here is the call graph for this function:

Here is the caller graph for this function:

def argparse.ArgumentParser._get_values (   self,
  action,
  arg_strings 
) [private]

Definition at line 2192 of file argparse.py.

02192 
02193     def _get_values(self, action, arg_strings):
02194         # for everything but PARSER args, strip out '--'
02195         if action.nargs not in [PARSER, REMAINDER]:
02196             arg_strings = [s for s in arg_strings if s != '--']
02197 
02198         # optional argument produces a default when not present
02199         if not arg_strings and action.nargs == OPTIONAL:
02200             if action.option_strings:
02201                 value = action.const
02202             else:
02203                 value = action.default
02204             if isinstance(value, str):
02205                 value = self._get_value(action, value)
02206                 self._check_value(action, value)
02207 
02208         # when nargs='*' on a positional, if there were no command-line
02209         # args, use the default if it is anything other than None
02210         elif (not arg_strings and action.nargs == ZERO_OR_MORE and
02211               not action.option_strings):
02212             if action.default is not None:
02213                 value = action.default
02214             else:
02215                 value = arg_strings
02216             self._check_value(action, value)
02217 
02218         # single argument or optional argument produces a single value
02219         elif len(arg_strings) == 1 and action.nargs in [None, OPTIONAL]:
02220             arg_string, = arg_strings
02221             value = self._get_value(action, arg_string)
02222             self._check_value(action, value)
02223 
02224         # REMAINDER arguments convert all values, checking none
02225         elif action.nargs == REMAINDER:
02226             value = [self._get_value(action, v) for v in arg_strings]
02227 
02228         # PARSER arguments convert all values, but check only the first
02229         elif action.nargs == PARSER:
02230             value = [self._get_value(action, v) for v in arg_strings]
02231             self._check_value(action, value[0])
02232 
02233         # all other types of nargs produce a list
02234         else:
02235             value = [self._get_value(action, v) for v in arg_strings]
02236             for v in value:
02237                 self._check_value(action, v)
02238 
02239         # return the converted value
02240         return value

Here is the call graph for this function:

Here is the caller graph for this function:

def argparse.ArgumentParser._match_argument (   self,
  action,
  arg_strings_pattern 
) [private]

Definition at line 2009 of file argparse.py.

02009 
02010     def _match_argument(self, action, arg_strings_pattern):
02011         # match the pattern for this action to the arg strings
02012         nargs_pattern = self._get_nargs_pattern(action)
02013         match = _re.match(nargs_pattern, arg_strings_pattern)
02014 
02015         # raise an exception if we weren't able to find a match
02016         if match is None:
02017             nargs_errors = {
02018                 None: _('expected one argument'),
02019                 OPTIONAL: _('expected at most one argument'),
02020                 ONE_OR_MORE: _('expected at least one argument'),
02021             }
02022             default = ngettext('expected %s argument',
02023                                'expected %s arguments',
02024                                action.nargs) % action.nargs
02025             msg = nargs_errors.get(action.nargs, default)
02026             raise ArgumentError(action, msg)
02027 
02028         # return the number of arguments matched
02029         return len(match.group(1))

Here is the call graph for this function:

Here is the caller graph for this function:

def argparse.ArgumentParser._match_arguments_partial (   self,
  actions,
  arg_strings_pattern 
) [private]

Definition at line 2030 of file argparse.py.

02030 
02031     def _match_arguments_partial(self, actions, arg_strings_pattern):
02032         # progressively shorten the actions list by slicing off the
02033         # final actions until we find a match
02034         result = []
02035         for i in range(len(actions), 0, -1):
02036             actions_slice = actions[:i]
02037             pattern = ''.join([self._get_nargs_pattern(action)
02038                                for action in actions_slice])
02039             match = _re.match(pattern, arg_strings_pattern)
02040             if match is not None:
02041                 result.extend([len(string) for string in match.groups()])
02042                 break
02043 
02044         # return the list of arg string counts
02045         return result

Here is the call graph for this function:

Here is the caller graph for this function:

def argparse.ArgumentParser._parse_known_args (   self,
  arg_strings,
  namespace 
) [private]

Definition at line 1742 of file argparse.py.

01742 
01743     def _parse_known_args(self, arg_strings, namespace):
01744         # replace arg strings that are file references
01745         if self.fromfile_prefix_chars is not None:
01746             arg_strings = self._read_args_from_files(arg_strings)
01747 
01748         # map all mutually exclusive arguments to the other arguments
01749         # they can't occur with
01750         action_conflicts = {}
01751         for mutex_group in self._mutually_exclusive_groups:
01752             group_actions = mutex_group._group_actions
01753             for i, mutex_action in enumerate(mutex_group._group_actions):
01754                 conflicts = action_conflicts.setdefault(mutex_action, [])
01755                 conflicts.extend(group_actions[:i])
01756                 conflicts.extend(group_actions[i + 1:])
01757 
01758         # find all option indices, and determine the arg_string_pattern
01759         # which has an 'O' if there is an option at an index,
01760         # an 'A' if there is an argument, or a '-' if there is a '--'
01761         option_string_indices = {}
01762         arg_string_pattern_parts = []
01763         arg_strings_iter = iter(arg_strings)
01764         for i, arg_string in enumerate(arg_strings_iter):
01765 
01766             # all args after -- are non-options
01767             if arg_string == '--':
01768                 arg_string_pattern_parts.append('-')
01769                 for arg_string in arg_strings_iter:
01770                     arg_string_pattern_parts.append('A')
01771 
01772             # otherwise, add the arg to the arg strings
01773             # and note the index if it was an option
01774             else:
01775                 option_tuple = self._parse_optional(arg_string)
01776                 if option_tuple is None:
01777                     pattern = 'A'
01778                 else:
01779                     option_string_indices[i] = option_tuple
01780                     pattern = 'O'
01781                 arg_string_pattern_parts.append(pattern)
01782 
01783         # join the pieces together to form the pattern
01784         arg_strings_pattern = ''.join(arg_string_pattern_parts)
01785 
01786         # converts arg strings to the appropriate and then takes the action
01787         seen_actions = set()
01788         seen_non_default_actions = set()
01789 
01790         def take_action(action, argument_strings, option_string=None):
01791             seen_actions.add(action)
01792             argument_values = self._get_values(action, argument_strings)
01793 
01794             # error if this argument is not allowed with other previously
01795             # seen arguments, assuming that actions that use the default
01796             # value don't really count as "present"
01797             if argument_values is not action.default:
01798                 seen_non_default_actions.add(action)
01799                 for conflict_action in action_conflicts.get(action, []):
01800                     if conflict_action in seen_non_default_actions:
01801                         msg = _('not allowed with argument %s')
01802                         action_name = _get_action_name(conflict_action)
01803                         raise ArgumentError(action, msg % action_name)
01804 
01805             # take the action if we didn't receive a SUPPRESS value
01806             # (e.g. from a default)
01807             if argument_values is not SUPPRESS:
01808                 action(self, namespace, argument_values, option_string)
01809 
01810         # function to convert arg_strings into an optional action
01811         def consume_optional(start_index):
01812 
01813             # get the optional identified at this index
01814             option_tuple = option_string_indices[start_index]
01815             action, option_string, explicit_arg = option_tuple
01816 
01817             # identify additional optionals in the same arg string
01818             # (e.g. -xyz is the same as -x -y -z if no args are required)
01819             match_argument = self._match_argument
01820             action_tuples = []
01821             while True:
01822 
01823                 # if we found no optional action, skip it
01824                 if action is None:
01825                     extras.append(arg_strings[start_index])
01826                     return start_index + 1
01827 
01828                 # if there is an explicit argument, try to match the
01829                 # optional's string arguments to only this
01830                 if explicit_arg is not None:
01831                     arg_count = match_argument(action, 'A')
01832 
01833                     # if the action is a single-dash option and takes no
01834                     # arguments, try to parse more single-dash options out
01835                     # of the tail of the option string
01836                     chars = self.prefix_chars
01837                     if arg_count == 0 and option_string[1] not in chars:
01838                         action_tuples.append((action, [], option_string))
01839                         char = option_string[0]
01840                         option_string = char + explicit_arg[0]
01841                         new_explicit_arg = explicit_arg[1:] or None
01842                         optionals_map = self._option_string_actions
01843                         if option_string in optionals_map:
01844                             action = optionals_map[option_string]
01845                             explicit_arg = new_explicit_arg
01846                         else:
01847                             msg = _('ignored explicit argument %r')
01848                             raise ArgumentError(action, msg % explicit_arg)
01849 
01850                     # if the action expect exactly one argument, we've
01851                     # successfully matched the option; exit the loop
01852                     elif arg_count == 1:
01853                         stop = start_index + 1
01854                         args = [explicit_arg]
01855                         action_tuples.append((action, args, option_string))
01856                         break
01857 
01858                     # error if a double-dash option did not use the
01859                     # explicit argument
01860                     else:
01861                         msg = _('ignored explicit argument %r')
01862                         raise ArgumentError(action, msg % explicit_arg)
01863 
01864                 # if there is no explicit argument, try to match the
01865                 # optional's string arguments with the following strings
01866                 # if successful, exit the loop
01867                 else:
01868                     start = start_index + 1
01869                     selected_patterns = arg_strings_pattern[start:]
01870                     arg_count = match_argument(action, selected_patterns)
01871                     stop = start + arg_count
01872                     args = arg_strings[start:stop]
01873                     action_tuples.append((action, args, option_string))
01874                     break
01875 
01876             # add the Optional to the list and return the index at which
01877             # the Optional's string args stopped
01878             assert action_tuples
01879             for action, args, option_string in action_tuples:
01880                 take_action(action, args, option_string)
01881             return stop
01882 
01883         # the list of Positionals left to be parsed; this is modified
01884         # by consume_positionals()
01885         positionals = self._get_positional_actions()
01886 
01887         # function to convert arg_strings into positional actions
01888         def consume_positionals(start_index):
01889             # match as many Positionals as possible
01890             match_partial = self._match_arguments_partial
01891             selected_pattern = arg_strings_pattern[start_index:]
01892             arg_counts = match_partial(positionals, selected_pattern)
01893 
01894             # slice off the appropriate arg strings for each Positional
01895             # and add the Positional and its args to the list
01896             for action, arg_count in zip(positionals, arg_counts):
01897                 args = arg_strings[start_index: start_index + arg_count]
01898                 start_index += arg_count
01899                 take_action(action, args)
01900 
01901             # slice off the Positionals that we just parsed and return the
01902             # index at which the Positionals' string args stopped
01903             positionals[:] = positionals[len(arg_counts):]
01904             return start_index
01905 
01906         # consume Positionals and Optionals alternately, until we have
01907         # passed the last option string
01908         extras = []
01909         start_index = 0
01910         if option_string_indices:
01911             max_option_string_index = max(option_string_indices)
01912         else:
01913             max_option_string_index = -1
01914         while start_index <= max_option_string_index:
01915 
01916             # consume any Positionals preceding the next option
01917             next_option_string_index = min([
01918                 index
01919                 for index in option_string_indices
01920                 if index >= start_index])
01921             if start_index != next_option_string_index:
01922                 positionals_end_index = consume_positionals(start_index)
01923 
01924                 # only try to parse the next optional if we didn't consume
01925                 # the option string during the positionals parsing
01926                 if positionals_end_index > start_index:
01927                     start_index = positionals_end_index
01928                     continue
01929                 else:
01930                     start_index = positionals_end_index
01931 
01932             # if we consumed all the positionals we could and we're not
01933             # at the index of an option string, there were extra arguments
01934             if start_index not in option_string_indices:
01935                 strings = arg_strings[start_index:next_option_string_index]
01936                 extras.extend(strings)
01937                 start_index = next_option_string_index
01938 
01939             # consume the next optional and any arguments for it
01940             start_index = consume_optional(start_index)
01941 
01942         # consume any positionals following the last Optional
01943         stop_index = consume_positionals(start_index)
01944 
01945         # if we didn't consume all the argument strings, there were extras
01946         extras.extend(arg_strings[stop_index:])
01947 
01948         # if we didn't use all the Positional objects, there were too few
01949         # arg strings supplied.
01950         if positionals:
01951             self.error(_('too few arguments'))
01952 
01953         # make sure all required actions were present
01954         for action in self._actions:
01955             if action.required:
01956                 if action not in seen_actions:
01957                     name = _get_action_name(action)
01958                     self.error(_('argument %s is required') % name)
01959 
01960         # make sure all required groups had one option present
01961         for group in self._mutually_exclusive_groups:
01962             if group.required:
01963                 for action in group._group_actions:
01964                     if action in seen_non_default_actions:
01965                         break
01966 
01967                 # if no actions were used, report the error
01968                 else:
01969                     names = [_get_action_name(action)
01970                              for action in group._group_actions
01971                              if action.help is not SUPPRESS]
01972                     msg = _('one of the arguments %s is required')
01973                     self.error(msg % ' '.join(names))
01974 
01975         # return the updated namespace and the extra arguments
01976         return namespace, extras

Here is the call graph for this function:

Here is the caller graph for this function:

def argparse.ArgumentParser._parse_optional (   self,
  arg_string 
) [private]

Definition at line 2046 of file argparse.py.

02046 
02047     def _parse_optional(self, arg_string):
02048         # if it's an empty string, it was meant to be a positional
02049         if not arg_string:
02050             return None
02051 
02052         # if it doesn't start with a prefix, it was meant to be positional
02053         if not arg_string[0] in self.prefix_chars:
02054             return None
02055 
02056         # if the option string is present in the parser, return the action
02057         if arg_string in self._option_string_actions:
02058             action = self._option_string_actions[arg_string]
02059             return action, arg_string, None
02060 
02061         # if it's just a single character, it was meant to be positional
02062         if len(arg_string) == 1:
02063             return None
02064 
02065         # if the option string before the "=" is present, return the action
02066         if '=' in arg_string:
02067             option_string, explicit_arg = arg_string.split('=', 1)
02068             if option_string in self._option_string_actions:
02069                 action = self._option_string_actions[option_string]
02070                 return action, option_string, explicit_arg
02071 
02072         # search through all possible prefixes of the option string
02073         # and all actions in the parser for possible interpretations
02074         option_tuples = self._get_option_tuples(arg_string)
02075 
02076         # if multiple actions match, the option string was ambiguous
02077         if len(option_tuples) > 1:
02078             options = ', '.join([option_string
02079                 for action, option_string, explicit_arg in option_tuples])
02080             args = {'option': arg_string, 'matches': options}
02081             msg = _('ambiguous option: %(option)s could match %(matches)s')
02082             self.error(msg % args)
02083 
02084         # if exactly one action matched, this segmentation is good,
02085         # so return the parsed action
02086         elif len(option_tuples) == 1:
02087             option_tuple, = option_tuples
02088             return option_tuple
02089 
02090         # if it was not found as an option, but it looks like a negative
02091         # number, it was meant to be positional
02092         # unless there are negative-number-like options
02093         if self._negative_number_matcher.match(arg_string):
02094             if not self._has_negative_number_optionals:
02095                 return None
02096 
02097         # if it contains a space, it was meant to be a positional
02098         if ' ' in arg_string:
02099             return None
02100 
02101         # it was meant to be an optional but there is no such option
02102         # in this parser (though it might be a valid option in a subparser)
02103         return None, arg_string, None

Here is the call graph for this function:

Here is the caller graph for this function:

def argparse.ArgumentParser._print_message (   self,
  message,
  file = None 
) [private]

Definition at line 2341 of file argparse.py.

02341 
02342     def _print_message(self, message, file=None):
02343         if message:
02344             if file is None:
02345                 file = _sys.stderr
02346             file.write(message)

Here is the caller graph for this function:

def argparse.ArgumentParser._read_args_from_files (   self,
  arg_strings 
) [private]

Definition at line 1977 of file argparse.py.

01977 
01978     def _read_args_from_files(self, arg_strings):
01979         # expand arguments referencing files
01980         new_arg_strings = []
01981         for arg_string in arg_strings:
01982 
01983             # for regular arguments, just add them back into the list
01984             if arg_string[0] not in self.fromfile_prefix_chars:
01985                 new_arg_strings.append(arg_string)
01986 
01987             # replace arguments referencing files with the file content
01988             else:
01989                 try:
01990                     args_file = open(arg_string[1:])
01991                     try:
01992                         arg_strings = []
01993                         for arg_line in args_file.read().splitlines():
01994                             for arg in self.convert_arg_line_to_args(arg_line):
01995                                 arg_strings.append(arg)
01996                         arg_strings = self._read_args_from_files(arg_strings)
01997                         new_arg_strings.extend(arg_strings)
01998                     finally:
01999                         args_file.close()
02000                 except IOError:
02001                     err = _sys.exc_info()[1]
02002                     self.error(str(err))
02003 
02004         # return the modified argument list
02005         return new_arg_strings

Here is the call graph for this function:

Here is the caller graph for this function:

def argparse._ActionsContainer.add_argument (   self,
  args,
  kwargs 
) [inherited]
add_argument(dest, ..., name=value, ...)
add_argument(option_string, option_string, ..., name=value, ...)

Definition at line 1260 of file argparse.py.

01260 
01261     def add_argument(self, *args, **kwargs):
01262         """
01263         add_argument(dest, ..., name=value, ...)
01264         add_argument(option_string, option_string, ..., name=value, ...)
01265         """
01266 
01267         # if no positional args are supplied or only one is supplied and
01268         # it doesn't look like an option string, parse a positional
01269         # argument
01270         chars = self.prefix_chars
01271         if not args or len(args) == 1 and args[0][0] not in chars:
01272             if args and 'dest' in kwargs:
01273                 raise ValueError('dest supplied twice for positional argument')
01274             kwargs = self._get_positional_kwargs(*args, **kwargs)
01275 
01276         # otherwise, we're adding an optional argument
01277         else:
01278             kwargs = self._get_optional_kwargs(*args, **kwargs)
01279 
01280         # if no default was supplied, use the parser-level default
01281         if 'default' not in kwargs:
01282             dest = kwargs['dest']
01283             if dest in self._defaults:
01284                 kwargs['default'] = self._defaults[dest]
01285             elif self.argument_default is not None:
01286                 kwargs['default'] = self.argument_default
01287 
01288         # create the action object, and add it to the parser
01289         action_class = self._pop_action_class(kwargs)
01290         if not _callable(action_class):
01291             raise ValueError('unknown action "%s"' % (action_class,))
01292         action = action_class(**kwargs)
01293 
01294         # raise an error if the action type is not callable
01295         type_func = self._registry_get('type', action.type, action.type)
01296         if not _callable(type_func):
01297             raise ValueError('%r is not callable' % (type_func,))
01298 
01299         # raise an error if the metavar does not match the type
01300         if hasattr(self, "_get_formatter"):
01301             try:
01302                 self._get_formatter()._format_args(action, None)
01303             except TypeError:
01304                 raise ValueError("length of metavar tuple does not match nargs")
01305 
01306         return self._add_action(action)

Here is the call graph for this function:

def argparse._ActionsContainer.add_argument_group (   self,
  args,
  kwargs 
) [inherited]

Definition at line 1307 of file argparse.py.

01307 
01308     def add_argument_group(self, *args, **kwargs):
01309         group = _ArgumentGroup(self, *args, **kwargs)
01310         self._action_groups.append(group)
01311         return group

Here is the caller graph for this function:

def argparse._ActionsContainer.add_mutually_exclusive_group (   self,
  kwargs 
) [inherited]

Definition at line 1312 of file argparse.py.

01312 
01313     def add_mutually_exclusive_group(self, **kwargs):
01314         group = _MutuallyExclusiveGroup(self, **kwargs)
01315         self._mutually_exclusive_groups.append(group)
01316         return group

Here is the caller graph for this function:

def argparse.ArgumentParser.add_subparsers (   self,
  kwargs 
)

Definition at line 1649 of file argparse.py.

01649 
01650     def add_subparsers(self, **kwargs):
01651         if self._subparsers is not None:
01652             self.error(_('cannot have multiple subparser arguments'))
01653 
01654         # add the parser class to the arguments if it's not present
01655         kwargs.setdefault('parser_class', type(self))
01656 
01657         if 'title' in kwargs or 'description' in kwargs:
01658             title = _(kwargs.pop('title', 'subcommands'))
01659             description = _(kwargs.pop('description', None))
01660             self._subparsers = self.add_argument_group(title, description)
01661         else:
01662             self._subparsers = self._positionals
01663 
01664         # prog defaults to the usage message of this parser, skipping
01665         # optional arguments and with no "usage:" prefix
01666         if kwargs.get('prog') is None:
01667             formatter = self._get_formatter()
01668             positionals = self._get_positional_actions()
01669             groups = self._mutually_exclusive_groups
01670             formatter.add_usage(self.usage, positionals, groups, '')
01671             kwargs['prog'] = formatter.format_help().strip()
01672 
01673         # create the parsers action and add it to the positionals list
01674         parsers_class = self._pop_action_class(kwargs, 'parsers')
01675         action = parsers_class(option_strings=[], **kwargs)
01676         self._subparsers._add_action(action)
01677 
01678         # return the created parsers action
01679         return action

Here is the call graph for this function:

def argparse.ArgumentParser.convert_arg_line_to_args (   self,
  arg_line 
)

Reimplemented in test.test_argparse.TestArgumentsFromFileConverter.FromFileConverterArgumentParser.

Definition at line 2006 of file argparse.py.

02006 
02007     def convert_arg_line_to_args(self, arg_line):
02008         return [arg_line]

Here is the caller graph for this function:

def argparse.ArgumentParser.error (   self,
  message 
)
error(message: string)

Prints a usage message incorporating the message to stderr and
exits.

If you override this in a subclass, it should not return -- it
should either exit or raise an exception.

Definition at line 2355 of file argparse.py.

02355 
02356     def error(self, message):
02357         """error(message: string)
02358 
02359         Prints a usage message incorporating the message to stderr and
02360         exits.
02361 
02362         If you override this in a subclass, it should not return -- it
02363         should either exit or raise an exception.
02364         """
02365         self.print_usage(_sys.stderr)
02366         args = {'prog': self.prog, 'message': message}
02367         self.exit(2, _('%(prog)s: error: %(message)s\n') % args)

Here is the call graph for this function:

Here is the caller graph for this function:

def argparse.ArgumentParser.exit (   self,
  status = 0,
  message = None 
)

Reimplemented in test.test_argparse.ErrorRaisingArgumentParser.

Definition at line 2350 of file argparse.py.

02350 
02351     def exit(self, status=0, message=None):
02352         if message:
02353             self._print_message(message, _sys.stderr)
02354         _sys.exit(status)

Here is the call graph for this function:

Here is the caller graph for this function:

Definition at line 2284 of file argparse.py.

02284 
02285     def format_help(self):
02286         formatter = self._get_formatter()
02287 
02288         # usage
02289         formatter.add_usage(self.usage, self._actions,
02290                             self._mutually_exclusive_groups)
02291 
02292         # description
02293         formatter.add_text(self.description)
02294 
02295         # positionals, optionals and user-defined groups
02296         for action_group in self._action_groups:
02297             formatter.start_section(action_group.title)
02298             formatter.add_text(action_group.description)
02299             formatter.add_arguments(action_group._group_actions)
02300             formatter.end_section()
02301 
02302         # epilog
02303         formatter.add_text(self.epilog)
02304 
02305         # determine help from format above
02306         return formatter.format_help()

Here is the call graph for this function:

Here is the caller graph for this function:

Definition at line 2278 of file argparse.py.

02278 
02279     def format_usage(self):
02280         formatter = self._get_formatter()
02281         formatter.add_usage(self.usage, self._actions,
02282                             self._mutually_exclusive_groups)
02283         return formatter.format_help()

Here is the call graph for this function:

Here is the caller graph for this function:

Definition at line 2307 of file argparse.py.

02307 
02308     def format_version(self):
02309         import warnings
02310         warnings.warn(
02311             'The format_version method is deprecated -- the "version" '
02312             'argument to ArgumentParser is no longer supported.',
02313             DeprecationWarning)
02314         formatter = self._get_formatter()
02315         formatter.add_text(self.version)
02316         return formatter.format_help()

Here is the call graph for this function:

Here is the caller graph for this function:

def argparse._ActionsContainer.get_default (   self,
  dest 
) [inherited]

Definition at line 1250 of file argparse.py.

01250 
01251     def get_default(self, dest):
01252         for action in self._actions:
01253             if action.dest == dest and action.default is not None:
01254                 return action.default
01255         return self._defaults.get(dest, None)
01256 

def argparse.ArgumentParser.parse_args (   self,
  args = None,
  namespace = None 
)

Reimplemented in test.test_argparse.ErrorRaisingArgumentParser.

Definition at line 1700 of file argparse.py.

01700 
01701     def parse_args(self, args=None, namespace=None):
01702         args, argv = self.parse_known_args(args, namespace)
01703         if argv:
01704             msg = _('unrecognized arguments: %s')
01705             self.error(msg % ' '.join(argv))
01706         return args

Here is the call graph for this function:

def argparse.ArgumentParser.parse_known_args (   self,
  args = None,
  namespace = None 
)

Definition at line 1707 of file argparse.py.

01707 
01708     def parse_known_args(self, args=None, namespace=None):
01709         # args default to the system args
01710         if args is None:
01711             args = _sys.argv[1:]
01712 
01713         # default Namespace built from parser defaults
01714         if namespace is None:
01715             namespace = Namespace()
01716 
01717         # add any action defaults that aren't present
01718         for action in self._actions:
01719             if action.dest is not SUPPRESS:
01720                 if not hasattr(namespace, action.dest):
01721                     if action.default is not SUPPRESS:
01722                         default = action.default
01723                         if isinstance(action.default, str):
01724                             default = self._get_value(action, default)
01725                         setattr(namespace, action.dest, default)
01726 
01727         # add any parser defaults that aren't present
01728         for dest in self._defaults:
01729             if not hasattr(namespace, dest):
01730                 setattr(namespace, dest, self._defaults[dest])
01731 
01732         # parse the arguments and exit if there are any errors
01733         try:
01734             namespace, args = self._parse_known_args(args, namespace)
01735             if hasattr(namespace, _UNRECOGNIZED_ARGS_ATTR):
01736                 args.extend(getattr(namespace, _UNRECOGNIZED_ARGS_ATTR))
01737                 delattr(namespace, _UNRECOGNIZED_ARGS_ATTR)
01738             return namespace, args
01739         except ArgumentError:
01740             err = _sys.exc_info()[1]
01741             self.error(str(err))

Here is the call graph for this function:

Here is the caller graph for this function:

def argparse.ArgumentParser.print_help (   self,
  file = None 
)

Definition at line 2328 of file argparse.py.

02328 
02329     def print_help(self, file=None):
02330         if file is None:
02331             file = _sys.stdout
02332         self._print_message(self.format_help(), file)

Here is the call graph for this function:

def argparse.ArgumentParser.print_usage (   self,
  file = None 
)

Definition at line 2323 of file argparse.py.

02323 
02324     def print_usage(self, file=None):
02325         if file is None:
02326             file = _sys.stdout
02327         self._print_message(self.format_usage(), file)

Here is the call graph for this function:

Here is the caller graph for this function:

def argparse.ArgumentParser.print_version (   self,
  file = None 
)

Definition at line 2333 of file argparse.py.

02333 
02334     def print_version(self, file=None):
02335         import warnings
02336         warnings.warn(
02337             'The print_version method is deprecated -- the "version" '
02338             'argument to ArgumentParser is no longer supported.',
02339             DeprecationWarning)
02340         self._print_message(self.format_version(), file)

Here is the call graph for this function:

def argparse._ActionsContainer.register (   self,
  registry_name,
  value,
  object 
) [inherited]

Definition at line 1231 of file argparse.py.

01231 
01232     def register(self, registry_name, value, object):
01233         registry = self._registries.setdefault(registry_name, {})
01234         registry[value] = object

Here is the caller graph for this function:

def argparse._ActionsContainer.set_defaults (   self,
  kwargs 
) [inherited]

Definition at line 1241 of file argparse.py.

01241 
01242     def set_defaults(self, **kwargs):
01243         self._defaults.update(kwargs)
01244 
01245         # if these defaults match any existing arguments, replace
01246         # the previous default on the object with the new one
01247         for action in self._actions:
01248             if action.dest in kwargs:
01249                 action.default = kwargs[action.dest]


Member Data Documentation

Definition at line 1598 of file argparse.py.

Definition at line 1597 of file argparse.py.

Definition at line 1599 of file argparse.py.

Definition at line 1594 of file argparse.py.

Definition at line 1187 of file argparse.py.

Definition at line 1189 of file argparse.py.

Definition at line 1186 of file argparse.py.

Definition at line 1590 of file argparse.py.

Definition at line 1592 of file argparse.py.

Definition at line 1593 of file argparse.py.

Definition at line 107 of file object.h.

Definition at line 107 of file object.h.

struct _typeobject* _object::ob_type [inherited]

Definition at line 108 of file object.h.

struct _typeobject* _object::ob_type [inherited]

Definition at line 108 of file object.h.

Definition at line 1188 of file argparse.py.

Definition at line 1588 of file argparse.py.

Definition at line 1589 of file argparse.py.

Definition at line 1591 of file argparse.py.


The documentation for this class was generated from the following file: