Back to index

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

List of all members.

Classes

class  _Section

Public Member Functions

def __init__
def start_section
def end_section
def add_text
def add_usage
def add_argument
def add_arguments
def format_help

Public Attributes

_PyObject_HEAD_EXTRA Py_ssize_t ob_refcnt
struct _typeobjectob_type

Private Member Functions

def _indent
def _dedent
def _add_item
def _join_parts
def _format_usage
def _format_actions_usage
def _format_text
def _format_action
def _format_action_invocation
def _metavar_formatter
def _format_args
def _expand_help
def _iter_indented_subactions
def _split_lines
def _fill_text
def _get_help_string

Private Attributes

 _prog
 _indent_increment
 _max_help_position
 _width
 _current_indent
 _level
 _action_max_length
 _root_section
 _current_section
 _whitespace_matcher
 _long_break_matcher

Detailed Description

Formatter for generating usage messages and argument help strings.

Only the name of this class is considered a public API. All the methods
provided by the class are considered an implementation detail.

Definition at line 147 of file argparse.py.


Constructor & Destructor Documentation

def argparse.HelpFormatter.__init__ (   self,
  prog,
  indent_increment = 2,
  max_help_position = 24,
  width = None 
)

Definition at line 158 of file argparse.py.

00158 
00159                  width=None):
00160 
00161         # default setting for width
00162         if width is None:
00163             try:
00164                 width = int(_os.environ['COLUMNS'])
00165             except (KeyError, ValueError):
00166                 width = 80
00167             width -= 2
00168 
00169         self._prog = prog
00170         self._indent_increment = indent_increment
00171         self._max_help_position = max_help_position
00172         self._width = width
00173 
00174         self._current_indent = 0
00175         self._level = 0
00176         self._action_max_length = 0
00177 
00178         self._root_section = self._Section(self, None)
00179         self._current_section = self._root_section
00180 
00181         self._whitespace_matcher = _re.compile(r'\s+')
00182         self._long_break_matcher = _re.compile(r'\n\n\n+')

Here is the caller graph for this function:


Member Function Documentation

def argparse.HelpFormatter._add_item (   self,
  func,
  args 
) [private]

Definition at line 228 of file argparse.py.

00228 
00229     def _add_item(self, func, args):
00230         self._current_section.items.append((func, args))

Here is the caller graph for this function:

def argparse.HelpFormatter._dedent (   self) [private]

Definition at line 190 of file argparse.py.

00190 
00191     def _dedent(self):
00192         self._current_indent -= self._indent_increment
00193         assert self._current_indent >= 0, 'Indent decreased below 0.'
00194         self._level -= 1

Here is the caller graph for this function:

def argparse.HelpFormatter._expand_help (   self,
  action 
) [private]

Definition at line 590 of file argparse.py.

00590 
00591     def _expand_help(self, action):
00592         params = dict(vars(action), prog=self._prog)
00593         for name in list(params):
00594             if params[name] is SUPPRESS:
00595                 del params[name]
00596         for name in list(params):
00597             if hasattr(params[name], '__name__'):
00598                 params[name] = params[name].__name__
00599         if params.get('choices') is not None:
00600             choices_str = ', '.join([str(c) for c in params['choices']])
00601             params['choices'] = choices_str
00602         return self._get_help_string(action) % params

Here is the call graph for this function:

Here is the caller graph for this function:

def argparse.HelpFormatter._fill_text (   self,
  text,
  width,
  indent 
) [private]

Reimplemented in argparse.RawDescriptionHelpFormatter.

Definition at line 618 of file argparse.py.

00618 
00619     def _fill_text(self, text, width, indent):
00620         text = self._whitespace_matcher.sub(' ', text).strip()
00621         return _textwrap.fill(text, width, initial_indent=indent,
00622                                            subsequent_indent=indent)

Here is the caller graph for this function:

def argparse.HelpFormatter._format_action (   self,
  action 
) [private]

Definition at line 485 of file argparse.py.

00485 
00486     def _format_action(self, action):
00487         # determine the required width and the entry label
00488         help_position = min(self._action_max_length + 2,
00489                             self._max_help_position)
00490         help_width = self._width - help_position
00491         action_width = help_position - self._current_indent - 2
00492         action_header = self._format_action_invocation(action)
00493 
00494         # ho nelp; start on same line and add a final newline
00495         if not action.help:
00496             tup = self._current_indent, '', action_header
00497             action_header = '%*s%s\n' % tup
00498 
00499         # short action name; start on the same line and pad two spaces
00500         elif len(action_header) <= action_width:
00501             tup = self._current_indent, '', action_width, action_header
00502             action_header = '%*s%-*s  ' % tup
00503             indent_first = 0
00504 
00505         # long action name; start on the next line
00506         else:
00507             tup = self._current_indent, '', action_header
00508             action_header = '%*s%s\n' % tup
00509             indent_first = help_position
00510 
00511         # collect the pieces of the action help
00512         parts = [action_header]
00513 
00514         # if there was help for the action, add lines of help text
00515         if action.help:
00516             help_text = self._expand_help(action)
00517             help_lines = self._split_lines(help_text, help_width)
00518             parts.append('%*s%s\n' % (indent_first, '', help_lines[0]))
00519             for line in help_lines[1:]:
00520                 parts.append('%*s%s\n' % (help_position, '', line))
00521 
00522         # or add a newline if the description doesn't end with one
00523         elif not action_header.endswith('\n'):
00524             parts.append('\n')
00525 
00526         # if there are any sub-actions, add their help as well
00527         for subaction in self._iter_indented_subactions(action):
00528             parts.append(self._format_action(subaction))
00529 
00530         # return a single string
00531         return self._join_parts(parts)

Here is the call graph for this function:

Here is the caller graph for this function:

def argparse.HelpFormatter._format_action_invocation (   self,
  action 
) [private]

Definition at line 532 of file argparse.py.

00532 
00533     def _format_action_invocation(self, action):
00534         if not action.option_strings:
00535             metavar, = self._metavar_formatter(action, action.dest)(1)
00536             return metavar
00537 
00538         else:
00539             parts = []
00540 
00541             # if the Optional doesn't take a value, format is:
00542             #    -s, --long
00543             if action.nargs == 0:
00544                 parts.extend(action.option_strings)
00545 
00546             # if the Optional takes a value, format is:
00547             #    -s ARGS, --long ARGS
00548             else:
00549                 default = action.dest.upper()
00550                 args_string = self._format_args(action, default)
00551                 for option_string in action.option_strings:
00552                     parts.append('%s %s' % (option_string, args_string))
00553 
00554             return ', '.join(parts)

Here is the call graph for this function:

Here is the caller graph for this function:

def argparse.HelpFormatter._format_actions_usage (   self,
  actions,
  groups 
) [private]

Definition at line 382 of file argparse.py.

00382 
00383     def _format_actions_usage(self, actions, groups):
00384         # find group indices and identify actions in groups
00385         group_actions = set()
00386         inserts = {}
00387         for group in groups:
00388             try:
00389                 start = actions.index(group._group_actions[0])
00390             except ValueError:
00391                 continue
00392             else:
00393                 end = start + len(group._group_actions)
00394                 if actions[start:end] == group._group_actions:
00395                     for action in group._group_actions:
00396                         group_actions.add(action)
00397                     if not group.required:
00398                         if start in inserts:
00399                             inserts[start] += ' ['
00400                         else:
00401                             inserts[start] = '['
00402                         inserts[end] = ']'
00403                     else:
00404                         if start in inserts:
00405                             inserts[start] += ' ('
00406                         else:
00407                             inserts[start] = '('
00408                         inserts[end] = ')'
00409                     for i in range(start + 1, end):
00410                         inserts[i] = '|'
00411 
00412         # collect all actions format strings
00413         parts = []
00414         for i, action in enumerate(actions):
00415 
00416             # suppressed arguments are marked with None
00417             # remove | separators for suppressed arguments
00418             if action.help is SUPPRESS:
00419                 parts.append(None)
00420                 if inserts.get(i) == '|':
00421                     inserts.pop(i)
00422                 elif inserts.get(i + 1) == '|':
00423                     inserts.pop(i + 1)
00424 
00425             # produce all arg strings
00426             elif not action.option_strings:
00427                 part = self._format_args(action, action.dest)
00428 
00429                 # if it's in a group, strip the outer []
00430                 if action in group_actions:
00431                     if part[0] == '[' and part[-1] == ']':
00432                         part = part[1:-1]
00433 
00434                 # add the action string to the list
00435                 parts.append(part)
00436 
00437             # produce the first way to invoke the option in brackets
00438             else:
00439                 option_string = action.option_strings[0]
00440 
00441                 # if the Optional doesn't take a value, format is:
00442                 #    -s or --long
00443                 if action.nargs == 0:
00444                     part = '%s' % option_string
00445 
00446                 # if the Optional takes a value, format is:
00447                 #    -s ARGS or --long ARGS
00448                 else:
00449                     default = action.dest.upper()
00450                     args_string = self._format_args(action, default)
00451                     part = '%s %s' % (option_string, args_string)
00452 
00453                 # make it look optional if it's not required or in a group
00454                 if not action.required and action not in group_actions:
00455                     part = '[%s]' % part
00456 
00457                 # add the action string to the list
00458                 parts.append(part)
00459 
00460         # insert things at the necessary indices
00461         for i in sorted(inserts, reverse=True):
00462             parts[i:i] = [inserts[i]]
00463 
00464         # join all the action items with spaces
00465         text = ' '.join([item for item in parts if item is not None])
00466 
00467         # clean up separators for mutually exclusive groups
00468         open = r'[\[(]'
00469         close = r'[\])]'
00470         text = _re.sub(r'(%s) ' % open, r'\1', text)
00471         text = _re.sub(r' (%s)' % close, r'\1', text)
00472         text = _re.sub(r'%s *%s' % (open, close), r'', text)
00473         text = _re.sub(r'\(([^|]*)\)', r'\1', text)
00474         text = text.strip()
00475 
00476         # return the text
00477         return text

Here is the call graph for this function:

Here is the caller graph for this function:

def argparse.HelpFormatter._format_args (   self,
  action,
  default_metavar 
) [private]

Definition at line 571 of file argparse.py.

00571 
00572     def _format_args(self, action, default_metavar):
00573         get_metavar = self._metavar_formatter(action, default_metavar)
00574         if action.nargs is None:
00575             result = '%s' % get_metavar(1)
00576         elif action.nargs == OPTIONAL:
00577             result = '[%s]' % get_metavar(1)
00578         elif action.nargs == ZERO_OR_MORE:
00579             result = '[%s [%s ...]]' % get_metavar(2)
00580         elif action.nargs == ONE_OR_MORE:
00581             result = '%s [%s ...]' % get_metavar(2)
00582         elif action.nargs == REMAINDER:
00583             result = '...'
00584         elif action.nargs == PARSER:
00585             result = '%s ...' % get_metavar(1)
00586         else:
00587             formats = ['%s' for _ in range(action.nargs)]
00588             result = ' '.join(formats) % get_metavar(action.nargs)
00589         return result

Here is the call graph for this function:

Here is the caller graph for this function:

def argparse.HelpFormatter._format_text (   self,
  text 
) [private]

Definition at line 478 of file argparse.py.

00478 
00479     def _format_text(self, text):
00480         if '%(prog)' in text:
00481             text = text % dict(prog=self._prog)
00482         text_width = self._width - self._current_indent
00483         indent = ' ' * self._current_indent
00484         return self._fill_text(text, text_width, indent) + '\n\n'

Here is the call graph for this function:

Here is the caller graph for this function:

def argparse.HelpFormatter._format_usage (   self,
  usage,
  actions,
  groups,
  prefix 
) [private]

Definition at line 290 of file argparse.py.

00290 
00291     def _format_usage(self, usage, actions, groups, prefix):
00292         if prefix is None:
00293             prefix = _('usage: ')
00294 
00295         # if usage is specified, use that
00296         if usage is not None:
00297             usage = usage % dict(prog=self._prog)
00298 
00299         # if no optionals or positionals are available, usage is just prog
00300         elif usage is None and not actions:
00301             usage = '%(prog)s' % dict(prog=self._prog)
00302 
00303         # if optionals and positionals are available, calculate usage
00304         elif usage is None:
00305             prog = '%(prog)s' % dict(prog=self._prog)
00306 
00307             # split optionals from positionals
00308             optionals = []
00309             positionals = []
00310             for action in actions:
00311                 if action.option_strings:
00312                     optionals.append(action)
00313                 else:
00314                     positionals.append(action)
00315 
00316             # build full usage string
00317             format = self._format_actions_usage
00318             action_usage = format(optionals + positionals, groups)
00319             usage = ' '.join([s for s in [prog, action_usage] if s])
00320 
00321             # wrap the usage parts if it's too long
00322             text_width = self._width - self._current_indent
00323             if len(prefix) + len(usage) > text_width:
00324 
00325                 # break usage into wrappable parts
00326                 part_regexp = r'\(.*?\)+|\[.*?\]+|\S+'
00327                 opt_usage = format(optionals, groups)
00328                 pos_usage = format(positionals, groups)
00329                 opt_parts = _re.findall(part_regexp, opt_usage)
00330                 pos_parts = _re.findall(part_regexp, pos_usage)
00331                 assert ' '.join(opt_parts) == opt_usage
00332                 assert ' '.join(pos_parts) == pos_usage
00333 
00334                 # helper for wrapping lines
00335                 def get_lines(parts, indent, prefix=None):
00336                     lines = []
00337                     line = []
00338                     if prefix is not None:
00339                         line_len = len(prefix) - 1
00340                     else:
00341                         line_len = len(indent) - 1
00342                     for part in parts:
00343                         if line_len + 1 + len(part) > text_width:
00344                             lines.append(indent + ' '.join(line))
00345                             line = []
00346                             line_len = len(indent) - 1
00347                         line.append(part)
00348                         line_len += len(part) + 1
00349                     if line:
00350                         lines.append(indent + ' '.join(line))
00351                     if prefix is not None:
00352                         lines[0] = lines[0][len(indent):]
00353                     return lines
00354 
00355                 # if prog is short, follow it with optionals or positionals
00356                 if len(prefix) + len(prog) <= 0.75 * text_width:
00357                     indent = ' ' * (len(prefix) + len(prog) + 1)
00358                     if opt_parts:
00359                         lines = get_lines([prog] + opt_parts, indent, prefix)
00360                         lines.extend(get_lines(pos_parts, indent))
00361                     elif pos_parts:
00362                         lines = get_lines([prog] + pos_parts, indent, prefix)
00363                     else:
00364                         lines = [prog]
00365 
00366                 # if prog is long, put it on its own line
00367                 else:
00368                     indent = ' ' * len(prefix)
00369                     parts = opt_parts + pos_parts
00370                     lines = get_lines(parts, indent)
00371                     if len(lines) > 1:
00372                         lines = []
00373                         lines.extend(get_lines(opt_parts, indent))
00374                         lines.extend(get_lines(pos_parts, indent))
00375                     lines = [prog] + lines
00376 
00377                 # join lines into usage
00378                 usage = '\n'.join(lines)
00379 
00380         # prefix with 'usage:'
00381         return '%s%s\n\n' % (prefix, usage)

Here is the call graph for this function:

Here is the caller graph for this function:

def argparse.HelpFormatter._get_help_string (   self,
  action 
) [private]

Reimplemented in argparse.ArgumentDefaultsHelpFormatter.

Definition at line 623 of file argparse.py.

00623 
00624     def _get_help_string(self, action):
00625         return action.help
00626 

Here is the caller graph for this function:

def argparse.HelpFormatter._indent (   self) [private]

Definition at line 186 of file argparse.py.

00186 
00187     def _indent(self):
00188         self._current_indent += self._indent_increment
00189         self._level += 1

Here is the caller graph for this function:

def argparse.HelpFormatter._iter_indented_subactions (   self,
  action 
) [private]

Definition at line 603 of file argparse.py.

00603 
00604     def _iter_indented_subactions(self, action):
00605         try:
00606             get_subactions = action._get_subactions
00607         except AttributeError:
00608             pass
00609         else:
00610             self._indent()
00611             for subaction in get_subactions():
00612                 yield subaction
00613             self._dedent()

Here is the call graph for this function:

Here is the caller graph for this function:

def argparse.HelpFormatter._join_parts (   self,
  part_strings 
) [private]

Definition at line 285 of file argparse.py.

00285 
00286     def _join_parts(self, part_strings):
00287         return ''.join([part
00288                         for part in part_strings
00289                         if part and part is not SUPPRESS])

Here is the caller graph for this function:

def argparse.HelpFormatter._metavar_formatter (   self,
  action,
  default_metavar 
) [private]

Definition at line 555 of file argparse.py.

00555 
00556     def _metavar_formatter(self, action, default_metavar):
00557         if action.metavar is not None:
00558             result = action.metavar
00559         elif action.choices is not None:
00560             choice_strs = [str(choice) for choice in action.choices]
00561             result = '{%s}' % ','.join(choice_strs)
00562         else:
00563             result = default_metavar
00564 
00565         def format(tuple_size):
00566             if isinstance(result, tuple):
00567                 return result
00568             else:
00569                 return (result, ) * tuple_size
00570         return format

Here is the caller graph for this function:

def argparse.HelpFormatter._split_lines (   self,
  text,
  width 
) [private]

Reimplemented in argparse.RawTextHelpFormatter.

Definition at line 614 of file argparse.py.

00614 
00615     def _split_lines(self, text, width):
00616         text = self._whitespace_matcher.sub(' ', text).strip()
00617         return _textwrap.wrap(text, width)

Here is the caller graph for this function:

def argparse.HelpFormatter.add_argument (   self,
  action 
)

Definition at line 253 of file argparse.py.

00253 
00254     def add_argument(self, action):
00255         if action.help is not SUPPRESS:
00256 
00257             # find all invocations
00258             get_invocation = self._format_action_invocation
00259             invocations = [get_invocation(action)]
00260             for subaction in self._iter_indented_subactions(action):
00261                 invocations.append(get_invocation(subaction))
00262 
00263             # update the maximum item length
00264             invocation_length = max([len(s) for s in invocations])
00265             action_length = invocation_length + self._current_indent
00266             self._action_max_length = max(self._action_max_length,
00267                                           action_length)
00268 
00269             # add the item to the list
00270             self._add_item(self._format_action, [action])

Here is the call graph for this function:

Here is the caller graph for this function:

def argparse.HelpFormatter.add_arguments (   self,
  actions 
)

Definition at line 271 of file argparse.py.

00271 
00272     def add_arguments(self, actions):
00273         for action in actions:
00274             self.add_argument(action)

Here is the call graph for this function:

def argparse.HelpFormatter.add_text (   self,
  text 
)

Definition at line 244 of file argparse.py.

00244 
00245     def add_text(self, text):
00246         if text is not SUPPRESS and text is not None:
00247             self._add_item(self._format_text, [text])

Here is the call graph for this function:

def argparse.HelpFormatter.add_usage (   self,
  usage,
  actions,
  groups,
  prefix = None 
)

Definition at line 248 of file argparse.py.

00248 
00249     def add_usage(self, usage, actions, groups, prefix=None):
00250         if usage is not SUPPRESS:
00251             args = usage, actions, groups, prefix
00252             self._add_item(self._format_usage, args)

Here is the call graph for this function:

Definition at line 240 of file argparse.py.

00240 
00241     def end_section(self):
00242         self._current_section = self._current_section.parent
00243         self._dedent()

Here is the call graph for this function:

Definition at line 278 of file argparse.py.

00278 
00279     def format_help(self):
00280         help = self._root_section.format_help()
00281         if help:
00282             help = self._long_break_matcher.sub('\n\n', help)
00283             help = help.strip('\n') + '\n'
00284         return help

Here is the caller graph for this function:

def argparse.HelpFormatter.start_section (   self,
  heading 
)

Definition at line 234 of file argparse.py.

00234 
00235     def start_section(self, heading):
00236         self._indent()
00237         section = self._Section(self, self._current_section, heading)
00238         self._add_item(section.format_help, [])
00239         self._current_section = section

Here is the call graph for this function:


Member Data Documentation

Definition at line 175 of file argparse.py.

Definition at line 173 of file argparse.py.

Definition at line 178 of file argparse.py.

Definition at line 169 of file argparse.py.

Definition at line 174 of file argparse.py.

Definition at line 181 of file argparse.py.

Definition at line 170 of file argparse.py.

Definition at line 168 of file argparse.py.

Definition at line 177 of file argparse.py.

Definition at line 180 of file argparse.py.

Definition at line 171 of file argparse.py.

Definition at line 107 of file object.h.

struct _typeobject* _object::ob_type [inherited]

Definition at line 108 of file object.h.


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