PageRenderTime 55ms CodeModel.GetById 15ms RepoModel.GetById 1ms app.codeStats 0ms

/External.LCA_RESTRICTED/Languages/CPython/27/Lib/argparse.py

http://github.com/IronLanguages/main
Python | 2347 lines | 1948 code | 168 blank | 231 comment | 244 complexity | cf662eb0ae9e5a0f53e15fd50cc9d19d MD5 | raw file
Possible License(s): CPL-1.0, BSD-3-Clause, ISC, GPL-2.0, MPL-2.0-no-copyleft-exception

Large files files are truncated, but you can click here to view the full file

  1. # Author: Steven J. Bethard <steven.bethard@gmail.com>.
  2. """Command-line parsing library
  3. This module is an optparse-inspired command-line parsing library that:
  4. - handles both optional and positional arguments
  5. - produces highly informative usage messages
  6. - supports parsers that dispatch to sub-parsers
  7. The following is a simple usage example that sums integers from the
  8. command-line and writes the result to a file::
  9. parser = argparse.ArgumentParser(
  10. description='sum the integers at the command line')
  11. parser.add_argument(
  12. 'integers', metavar='int', nargs='+', type=int,
  13. help='an integer to be summed')
  14. parser.add_argument(
  15. '--log', default=sys.stdout, type=argparse.FileType('w'),
  16. help='the file where the sum should be written')
  17. args = parser.parse_args()
  18. args.log.write('%s' % sum(args.integers))
  19. args.log.close()
  20. The module contains the following public classes:
  21. - ArgumentParser -- The main entry point for command-line parsing. As the
  22. example above shows, the add_argument() method is used to populate
  23. the parser with actions for optional and positional arguments. Then
  24. the parse_args() method is invoked to convert the args at the
  25. command-line into an object with attributes.
  26. - ArgumentError -- The exception raised by ArgumentParser objects when
  27. there are errors with the parser's actions. Errors raised while
  28. parsing the command-line are caught by ArgumentParser and emitted
  29. as command-line messages.
  30. - FileType -- A factory for defining types of files to be created. As the
  31. example above shows, instances of FileType are typically passed as
  32. the type= argument of add_argument() calls.
  33. - Action -- The base class for parser actions. Typically actions are
  34. selected by passing strings like 'store_true' or 'append_const' to
  35. the action= argument of add_argument(). However, for greater
  36. customization of ArgumentParser actions, subclasses of Action may
  37. be defined and passed as the action= argument.
  38. - HelpFormatter, RawDescriptionHelpFormatter, RawTextHelpFormatter,
  39. ArgumentDefaultsHelpFormatter -- Formatter classes which
  40. may be passed as the formatter_class= argument to the
  41. ArgumentParser constructor. HelpFormatter is the default,
  42. RawDescriptionHelpFormatter and RawTextHelpFormatter tell the parser
  43. not to change the formatting for help text, and
  44. ArgumentDefaultsHelpFormatter adds information about argument defaults
  45. to the help.
  46. All other classes in this module are considered implementation details.
  47. (Also note that HelpFormatter and RawDescriptionHelpFormatter are only
  48. considered public as object names -- the API of the formatter objects is
  49. still considered an implementation detail.)
  50. """
  51. __version__ = '1.1'
  52. __all__ = [
  53. 'ArgumentParser',
  54. 'ArgumentError',
  55. 'ArgumentTypeError',
  56. 'FileType',
  57. 'HelpFormatter',
  58. 'ArgumentDefaultsHelpFormatter',
  59. 'RawDescriptionHelpFormatter',
  60. 'RawTextHelpFormatter',
  61. 'Namespace',
  62. 'Action',
  63. 'ONE_OR_MORE',
  64. 'OPTIONAL',
  65. 'PARSER',
  66. 'REMAINDER',
  67. 'SUPPRESS',
  68. 'ZERO_OR_MORE',
  69. ]
  70. import collections as _collections
  71. import copy as _copy
  72. import os as _os
  73. import re as _re
  74. import sys as _sys
  75. import textwrap as _textwrap
  76. from gettext import gettext as _
  77. def _callable(obj):
  78. return hasattr(obj, '__call__') or hasattr(obj, '__bases__')
  79. SUPPRESS = '==SUPPRESS=='
  80. OPTIONAL = '?'
  81. ZERO_OR_MORE = '*'
  82. ONE_OR_MORE = '+'
  83. PARSER = 'A...'
  84. REMAINDER = '...'
  85. _UNRECOGNIZED_ARGS_ATTR = '_unrecognized_args'
  86. # =============================
  87. # Utility functions and classes
  88. # =============================
  89. class _AttributeHolder(object):
  90. """Abstract base class that provides __repr__.
  91. The __repr__ method returns a string in the format::
  92. ClassName(attr=name, attr=name, ...)
  93. The attributes are determined either by a class-level attribute,
  94. '_kwarg_names', or by inspecting the instance __dict__.
  95. """
  96. def __repr__(self):
  97. type_name = type(self).__name__
  98. arg_strings = []
  99. for arg in self._get_args():
  100. arg_strings.append(repr(arg))
  101. for name, value in self._get_kwargs():
  102. arg_strings.append('%s=%r' % (name, value))
  103. return '%s(%s)' % (type_name, ', '.join(arg_strings))
  104. def _get_kwargs(self):
  105. return sorted(self.__dict__.items())
  106. def _get_args(self):
  107. return []
  108. def _ensure_value(namespace, name, value):
  109. if getattr(namespace, name, None) is None:
  110. setattr(namespace, name, value)
  111. return getattr(namespace, name)
  112. # ===============
  113. # Formatting Help
  114. # ===============
  115. class HelpFormatter(object):
  116. """Formatter for generating usage messages and argument help strings.
  117. Only the name of this class is considered a public API. All the methods
  118. provided by the class are considered an implementation detail.
  119. """
  120. def __init__(self,
  121. prog,
  122. indent_increment=2,
  123. max_help_position=24,
  124. width=None):
  125. # default setting for width
  126. if width is None:
  127. try:
  128. width = int(_os.environ['COLUMNS'])
  129. except (KeyError, ValueError):
  130. width = 80
  131. width -= 2
  132. self._prog = prog
  133. self._indent_increment = indent_increment
  134. self._max_help_position = max_help_position
  135. self._width = width
  136. self._current_indent = 0
  137. self._level = 0
  138. self._action_max_length = 0
  139. self._root_section = self._Section(self, None)
  140. self._current_section = self._root_section
  141. self._whitespace_matcher = _re.compile(r'\s+')
  142. self._long_break_matcher = _re.compile(r'\n\n\n+')
  143. # ===============================
  144. # Section and indentation methods
  145. # ===============================
  146. def _indent(self):
  147. self._current_indent += self._indent_increment
  148. self._level += 1
  149. def _dedent(self):
  150. self._current_indent -= self._indent_increment
  151. assert self._current_indent >= 0, 'Indent decreased below 0.'
  152. self._level -= 1
  153. class _Section(object):
  154. def __init__(self, formatter, parent, heading=None):
  155. self.formatter = formatter
  156. self.parent = parent
  157. self.heading = heading
  158. self.items = []
  159. def format_help(self):
  160. # format the indented section
  161. if self.parent is not None:
  162. self.formatter._indent()
  163. join = self.formatter._join_parts
  164. for func, args in self.items:
  165. func(*args)
  166. item_help = join([func(*args) for func, args in self.items])
  167. if self.parent is not None:
  168. self.formatter._dedent()
  169. # return nothing if the section was empty
  170. if not item_help:
  171. return ''
  172. # add the heading if the section was non-empty
  173. if self.heading is not SUPPRESS and self.heading is not None:
  174. current_indent = self.formatter._current_indent
  175. heading = '%*s%s:\n' % (current_indent, '', self.heading)
  176. else:
  177. heading = ''
  178. # join the section-initial newline, the heading and the help
  179. return join(['\n', heading, item_help, '\n'])
  180. def _add_item(self, func, args):
  181. self._current_section.items.append((func, args))
  182. # ========================
  183. # Message building methods
  184. # ========================
  185. def start_section(self, heading):
  186. self._indent()
  187. section = self._Section(self, self._current_section, heading)
  188. self._add_item(section.format_help, [])
  189. self._current_section = section
  190. def end_section(self):
  191. self._current_section = self._current_section.parent
  192. self._dedent()
  193. def add_text(self, text):
  194. if text is not SUPPRESS and text is not None:
  195. self._add_item(self._format_text, [text])
  196. def add_usage(self, usage, actions, groups, prefix=None):
  197. if usage is not SUPPRESS:
  198. args = usage, actions, groups, prefix
  199. self._add_item(self._format_usage, args)
  200. def add_argument(self, action):
  201. if action.help is not SUPPRESS:
  202. # find all invocations
  203. get_invocation = self._format_action_invocation
  204. invocations = [get_invocation(action)]
  205. for subaction in self._iter_indented_subactions(action):
  206. invocations.append(get_invocation(subaction))
  207. # update the maximum item length
  208. invocation_length = max([len(s) for s in invocations])
  209. action_length = invocation_length + self._current_indent
  210. self._action_max_length = max(self._action_max_length,
  211. action_length)
  212. # add the item to the list
  213. self._add_item(self._format_action, [action])
  214. def add_arguments(self, actions):
  215. for action in actions:
  216. self.add_argument(action)
  217. # =======================
  218. # Help-formatting methods
  219. # =======================
  220. def format_help(self):
  221. help = self._root_section.format_help()
  222. if help:
  223. help = self._long_break_matcher.sub('\n\n', help)
  224. help = help.strip('\n') + '\n'
  225. return help
  226. def _join_parts(self, part_strings):
  227. return ''.join([part
  228. for part in part_strings
  229. if part and part is not SUPPRESS])
  230. def _format_usage(self, usage, actions, groups, prefix):
  231. if prefix is None:
  232. prefix = _('usage: ')
  233. # if usage is specified, use that
  234. if usage is not None:
  235. usage = usage % dict(prog=self._prog)
  236. # if no optionals or positionals are available, usage is just prog
  237. elif usage is None and not actions:
  238. usage = '%(prog)s' % dict(prog=self._prog)
  239. # if optionals and positionals are available, calculate usage
  240. elif usage is None:
  241. prog = '%(prog)s' % dict(prog=self._prog)
  242. # split optionals from positionals
  243. optionals = []
  244. positionals = []
  245. for action in actions:
  246. if action.option_strings:
  247. optionals.append(action)
  248. else:
  249. positionals.append(action)
  250. # build full usage string
  251. format = self._format_actions_usage
  252. action_usage = format(optionals + positionals, groups)
  253. usage = ' '.join([s for s in [prog, action_usage] if s])
  254. # wrap the usage parts if it's too long
  255. text_width = self._width - self._current_indent
  256. if len(prefix) + len(usage) > text_width:
  257. # break usage into wrappable parts
  258. part_regexp = r'\(.*?\)+|\[.*?\]+|\S+'
  259. opt_usage = format(optionals, groups)
  260. pos_usage = format(positionals, groups)
  261. opt_parts = _re.findall(part_regexp, opt_usage)
  262. pos_parts = _re.findall(part_regexp, pos_usage)
  263. assert ' '.join(opt_parts) == opt_usage
  264. assert ' '.join(pos_parts) == pos_usage
  265. # helper for wrapping lines
  266. def get_lines(parts, indent, prefix=None):
  267. lines = []
  268. line = []
  269. if prefix is not None:
  270. line_len = len(prefix) - 1
  271. else:
  272. line_len = len(indent) - 1
  273. for part in parts:
  274. if line_len + 1 + len(part) > text_width:
  275. lines.append(indent + ' '.join(line))
  276. line = []
  277. line_len = len(indent) - 1
  278. line.append(part)
  279. line_len += len(part) + 1
  280. if line:
  281. lines.append(indent + ' '.join(line))
  282. if prefix is not None:
  283. lines[0] = lines[0][len(indent):]
  284. return lines
  285. # if prog is short, follow it with optionals or positionals
  286. if len(prefix) + len(prog) <= 0.75 * text_width:
  287. indent = ' ' * (len(prefix) + len(prog) + 1)
  288. if opt_parts:
  289. lines = get_lines([prog] + opt_parts, indent, prefix)
  290. lines.extend(get_lines(pos_parts, indent))
  291. elif pos_parts:
  292. lines = get_lines([prog] + pos_parts, indent, prefix)
  293. else:
  294. lines = [prog]
  295. # if prog is long, put it on its own line
  296. else:
  297. indent = ' ' * len(prefix)
  298. parts = opt_parts + pos_parts
  299. lines = get_lines(parts, indent)
  300. if len(lines) > 1:
  301. lines = []
  302. lines.extend(get_lines(opt_parts, indent))
  303. lines.extend(get_lines(pos_parts, indent))
  304. lines = [prog] + lines
  305. # join lines into usage
  306. usage = '\n'.join(lines)
  307. # prefix with 'usage:'
  308. return '%s%s\n\n' % (prefix, usage)
  309. def _format_actions_usage(self, actions, groups):
  310. # find group indices and identify actions in groups
  311. group_actions = set()
  312. inserts = {}
  313. for group in groups:
  314. try:
  315. start = actions.index(group._group_actions[0])
  316. except ValueError:
  317. continue
  318. else:
  319. end = start + len(group._group_actions)
  320. if actions[start:end] == group._group_actions:
  321. for action in group._group_actions:
  322. group_actions.add(action)
  323. if not group.required:
  324. if start in inserts:
  325. inserts[start] += ' ['
  326. else:
  327. inserts[start] = '['
  328. inserts[end] = ']'
  329. else:
  330. if start in inserts:
  331. inserts[start] += ' ('
  332. else:
  333. inserts[start] = '('
  334. inserts[end] = ')'
  335. for i in range(start + 1, end):
  336. inserts[i] = '|'
  337. # collect all actions format strings
  338. parts = []
  339. for i, action in enumerate(actions):
  340. # suppressed arguments are marked with None
  341. # remove | separators for suppressed arguments
  342. if action.help is SUPPRESS:
  343. parts.append(None)
  344. if inserts.get(i) == '|':
  345. inserts.pop(i)
  346. elif inserts.get(i + 1) == '|':
  347. inserts.pop(i + 1)
  348. # produce all arg strings
  349. elif not action.option_strings:
  350. part = self._format_args(action, action.dest)
  351. # if it's in a group, strip the outer []
  352. if action in group_actions:
  353. if part[0] == '[' and part[-1] == ']':
  354. part = part[1:-1]
  355. # add the action string to the list
  356. parts.append(part)
  357. # produce the first way to invoke the option in brackets
  358. else:
  359. option_string = action.option_strings[0]
  360. # if the Optional doesn't take a value, format is:
  361. # -s or --long
  362. if action.nargs == 0:
  363. part = '%s' % option_string
  364. # if the Optional takes a value, format is:
  365. # -s ARGS or --long ARGS
  366. else:
  367. default = action.dest.upper()
  368. args_string = self._format_args(action, default)
  369. part = '%s %s' % (option_string, args_string)
  370. # make it look optional if it's not required or in a group
  371. if not action.required and action not in group_actions:
  372. part = '[%s]' % part
  373. # add the action string to the list
  374. parts.append(part)
  375. # insert things at the necessary indices
  376. for i in sorted(inserts, reverse=True):
  377. parts[i:i] = [inserts[i]]
  378. # join all the action items with spaces
  379. text = ' '.join([item for item in parts if item is not None])
  380. # clean up separators for mutually exclusive groups
  381. open = r'[\[(]'
  382. close = r'[\])]'
  383. text = _re.sub(r'(%s) ' % open, r'\1', text)
  384. text = _re.sub(r' (%s)' % close, r'\1', text)
  385. text = _re.sub(r'%s *%s' % (open, close), r'', text)
  386. text = _re.sub(r'\(([^|]*)\)', r'\1', text)
  387. text = text.strip()
  388. # return the text
  389. return text
  390. def _format_text(self, text):
  391. if '%(prog)' in text:
  392. text = text % dict(prog=self._prog)
  393. text_width = self._width - self._current_indent
  394. indent = ' ' * self._current_indent
  395. return self._fill_text(text, text_width, indent) + '\n\n'
  396. def _format_action(self, action):
  397. # determine the required width and the entry label
  398. help_position = min(self._action_max_length + 2,
  399. self._max_help_position)
  400. help_width = self._width - help_position
  401. action_width = help_position - self._current_indent - 2
  402. action_header = self._format_action_invocation(action)
  403. # ho nelp; start on same line and add a final newline
  404. if not action.help:
  405. tup = self._current_indent, '', action_header
  406. action_header = '%*s%s\n' % tup
  407. # short action name; start on the same line and pad two spaces
  408. elif len(action_header) <= action_width:
  409. tup = self._current_indent, '', action_width, action_header
  410. action_header = '%*s%-*s ' % tup
  411. indent_first = 0
  412. # long action name; start on the next line
  413. else:
  414. tup = self._current_indent, '', action_header
  415. action_header = '%*s%s\n' % tup
  416. indent_first = help_position
  417. # collect the pieces of the action help
  418. parts = [action_header]
  419. # if there was help for the action, add lines of help text
  420. if action.help:
  421. help_text = self._expand_help(action)
  422. help_lines = self._split_lines(help_text, help_width)
  423. parts.append('%*s%s\n' % (indent_first, '', help_lines[0]))
  424. for line in help_lines[1:]:
  425. parts.append('%*s%s\n' % (help_position, '', line))
  426. # or add a newline if the description doesn't end with one
  427. elif not action_header.endswith('\n'):
  428. parts.append('\n')
  429. # if there are any sub-actions, add their help as well
  430. for subaction in self._iter_indented_subactions(action):
  431. parts.append(self._format_action(subaction))
  432. # return a single string
  433. return self._join_parts(parts)
  434. def _format_action_invocation(self, action):
  435. if not action.option_strings:
  436. metavar, = self._metavar_formatter(action, action.dest)(1)
  437. return metavar
  438. else:
  439. parts = []
  440. # if the Optional doesn't take a value, format is:
  441. # -s, --long
  442. if action.nargs == 0:
  443. parts.extend(action.option_strings)
  444. # if the Optional takes a value, format is:
  445. # -s ARGS, --long ARGS
  446. else:
  447. default = action.dest.upper()
  448. args_string = self._format_args(action, default)
  449. for option_string in action.option_strings:
  450. parts.append('%s %s' % (option_string, args_string))
  451. return ', '.join(parts)
  452. def _metavar_formatter(self, action, default_metavar):
  453. if action.metavar is not None:
  454. result = action.metavar
  455. elif action.choices is not None:
  456. choice_strs = [str(choice) for choice in action.choices]
  457. result = '{%s}' % ','.join(choice_strs)
  458. else:
  459. result = default_metavar
  460. def format(tuple_size):
  461. if isinstance(result, tuple):
  462. return result
  463. else:
  464. return (result, ) * tuple_size
  465. return format
  466. def _format_args(self, action, default_metavar):
  467. get_metavar = self._metavar_formatter(action, default_metavar)
  468. if action.nargs is None:
  469. result = '%s' % get_metavar(1)
  470. elif action.nargs == OPTIONAL:
  471. result = '[%s]' % get_metavar(1)
  472. elif action.nargs == ZERO_OR_MORE:
  473. result = '[%s [%s ...]]' % get_metavar(2)
  474. elif action.nargs == ONE_OR_MORE:
  475. result = '%s [%s ...]' % get_metavar(2)
  476. elif action.nargs == REMAINDER:
  477. result = '...'
  478. elif action.nargs == PARSER:
  479. result = '%s ...' % get_metavar(1)
  480. else:
  481. formats = ['%s' for _ in range(action.nargs)]
  482. result = ' '.join(formats) % get_metavar(action.nargs)
  483. return result
  484. def _expand_help(self, action):
  485. params = dict(vars(action), prog=self._prog)
  486. for name in list(params):
  487. if params[name] is SUPPRESS:
  488. del params[name]
  489. for name in list(params):
  490. if hasattr(params[name], '__name__'):
  491. params[name] = params[name].__name__
  492. if params.get('choices') is not None:
  493. choices_str = ', '.join([str(c) for c in params['choices']])
  494. params['choices'] = choices_str
  495. return self._get_help_string(action) % params
  496. def _iter_indented_subactions(self, action):
  497. try:
  498. get_subactions = action._get_subactions
  499. except AttributeError:
  500. pass
  501. else:
  502. self._indent()
  503. for subaction in get_subactions():
  504. yield subaction
  505. self._dedent()
  506. def _split_lines(self, text, width):
  507. text = self._whitespace_matcher.sub(' ', text).strip()
  508. return _textwrap.wrap(text, width)
  509. def _fill_text(self, text, width, indent):
  510. text = self._whitespace_matcher.sub(' ', text).strip()
  511. return _textwrap.fill(text, width, initial_indent=indent,
  512. subsequent_indent=indent)
  513. def _get_help_string(self, action):
  514. return action.help
  515. class RawDescriptionHelpFormatter(HelpFormatter):
  516. """Help message formatter which retains any formatting in descriptions.
  517. Only the name of this class is considered a public API. All the methods
  518. provided by the class are considered an implementation detail.
  519. """
  520. def _fill_text(self, text, width, indent):
  521. return ''.join([indent + line for line in text.splitlines(True)])
  522. class RawTextHelpFormatter(RawDescriptionHelpFormatter):
  523. """Help message formatter which retains formatting of all help text.
  524. Only the name of this class is considered a public API. All the methods
  525. provided by the class are considered an implementation detail.
  526. """
  527. def _split_lines(self, text, width):
  528. return text.splitlines()
  529. class ArgumentDefaultsHelpFormatter(HelpFormatter):
  530. """Help message formatter which adds default values to argument help.
  531. Only the name of this class is considered a public API. All the methods
  532. provided by the class are considered an implementation detail.
  533. """
  534. def _get_help_string(self, action):
  535. help = action.help
  536. if '%(default)' not in action.help:
  537. if action.default is not SUPPRESS:
  538. defaulting_nargs = [OPTIONAL, ZERO_OR_MORE]
  539. if action.option_strings or action.nargs in defaulting_nargs:
  540. help += ' (default: %(default)s)'
  541. return help
  542. # =====================
  543. # Options and Arguments
  544. # =====================
  545. def _get_action_name(argument):
  546. if argument is None:
  547. return None
  548. elif argument.option_strings:
  549. return '/'.join(argument.option_strings)
  550. elif argument.metavar not in (None, SUPPRESS):
  551. return argument.metavar
  552. elif argument.dest not in (None, SUPPRESS):
  553. return argument.dest
  554. else:
  555. return None
  556. class ArgumentError(Exception):
  557. """An error from creating or using an argument (optional or positional).
  558. The string value of this exception is the message, augmented with
  559. information about the argument that caused it.
  560. """
  561. def __init__(self, argument, message):
  562. self.argument_name = _get_action_name(argument)
  563. self.message = message
  564. def __str__(self):
  565. if self.argument_name is None:
  566. format = '%(message)s'
  567. else:
  568. format = 'argument %(argument_name)s: %(message)s'
  569. return format % dict(message=self.message,
  570. argument_name=self.argument_name)
  571. class ArgumentTypeError(Exception):
  572. """An error from trying to convert a command line string to a type."""
  573. pass
  574. # ==============
  575. # Action classes
  576. # ==============
  577. class Action(_AttributeHolder):
  578. """Information about how to convert command line strings to Python objects.
  579. Action objects are used by an ArgumentParser to represent the information
  580. needed to parse a single argument from one or more strings from the
  581. command line. The keyword arguments to the Action constructor are also
  582. all attributes of Action instances.
  583. Keyword Arguments:
  584. - option_strings -- A list of command-line option strings which
  585. should be associated with this action.
  586. - dest -- The name of the attribute to hold the created object(s)
  587. - nargs -- The number of command-line arguments that should be
  588. consumed. By default, one argument will be consumed and a single
  589. value will be produced. Other values include:
  590. - N (an integer) consumes N arguments (and produces a list)
  591. - '?' consumes zero or one arguments
  592. - '*' consumes zero or more arguments (and produces a list)
  593. - '+' consumes one or more arguments (and produces a list)
  594. Note that the difference between the default and nargs=1 is that
  595. with the default, a single value will be produced, while with
  596. nargs=1, a list containing a single value will be produced.
  597. - const -- The value to be produced if the option is specified and the
  598. option uses an action that takes no values.
  599. - default -- The value to be produced if the option is not specified.
  600. - type -- The type which the command-line arguments should be converted
  601. to, should be one of 'string', 'int', 'float', 'complex' or a
  602. callable object that accepts a single string argument. If None,
  603. 'string' is assumed.
  604. - choices -- A container of values that should be allowed. If not None,
  605. after a command-line argument has been converted to the appropriate
  606. type, an exception will be raised if it is not a member of this
  607. collection.
  608. - required -- True if the action must always be specified at the
  609. command line. This is only meaningful for optional command-line
  610. arguments.
  611. - help -- The help string describing the argument.
  612. - metavar -- The name to be used for the option's argument with the
  613. help string. If None, the 'dest' value will be used as the name.
  614. """
  615. def __init__(self,
  616. option_strings,
  617. dest,
  618. nargs=None,
  619. const=None,
  620. default=None,
  621. type=None,
  622. choices=None,
  623. required=False,
  624. help=None,
  625. metavar=None):
  626. self.option_strings = option_strings
  627. self.dest = dest
  628. self.nargs = nargs
  629. self.const = const
  630. self.default = default
  631. self.type = type
  632. self.choices = choices
  633. self.required = required
  634. self.help = help
  635. self.metavar = metavar
  636. def _get_kwargs(self):
  637. names = [
  638. 'option_strings',
  639. 'dest',
  640. 'nargs',
  641. 'const',
  642. 'default',
  643. 'type',
  644. 'choices',
  645. 'help',
  646. 'metavar',
  647. ]
  648. return [(name, getattr(self, name)) for name in names]
  649. def __call__(self, parser, namespace, values, option_string=None):
  650. raise NotImplementedError(_('.__call__() not defined'))
  651. class _StoreAction(Action):
  652. def __init__(self,
  653. option_strings,
  654. dest,
  655. nargs=None,
  656. const=None,
  657. default=None,
  658. type=None,
  659. choices=None,
  660. required=False,
  661. help=None,
  662. metavar=None):
  663. if nargs == 0:
  664. raise ValueError('nargs for store actions must be > 0; if you '
  665. 'have nothing to store, actions such as store '
  666. 'true or store const may be more appropriate')
  667. if const is not None and nargs != OPTIONAL:
  668. raise ValueError('nargs must be %r to supply const' % OPTIONAL)
  669. super(_StoreAction, self).__init__(
  670. option_strings=option_strings,
  671. dest=dest,
  672. nargs=nargs,
  673. const=const,
  674. default=default,
  675. type=type,
  676. choices=choices,
  677. required=required,
  678. help=help,
  679. metavar=metavar)
  680. def __call__(self, parser, namespace, values, option_string=None):
  681. setattr(namespace, self.dest, values)
  682. class _StoreConstAction(Action):
  683. def __init__(self,
  684. option_strings,
  685. dest,
  686. const,
  687. default=None,
  688. required=False,
  689. help=None,
  690. metavar=None):
  691. super(_StoreConstAction, self).__init__(
  692. option_strings=option_strings,
  693. dest=dest,
  694. nargs=0,
  695. const=const,
  696. default=default,
  697. required=required,
  698. help=help)
  699. def __call__(self, parser, namespace, values, option_string=None):
  700. setattr(namespace, self.dest, self.const)
  701. class _StoreTrueAction(_StoreConstAction):
  702. def __init__(self,
  703. option_strings,
  704. dest,
  705. default=False,
  706. required=False,
  707. help=None):
  708. super(_StoreTrueAction, self).__init__(
  709. option_strings=option_strings,
  710. dest=dest,
  711. const=True,
  712. default=default,
  713. required=required,
  714. help=help)
  715. class _StoreFalseAction(_StoreConstAction):
  716. def __init__(self,
  717. option_strings,
  718. dest,
  719. default=True,
  720. required=False,
  721. help=None):
  722. super(_StoreFalseAction, self).__init__(
  723. option_strings=option_strings,
  724. dest=dest,
  725. const=False,
  726. default=default,
  727. required=required,
  728. help=help)
  729. class _AppendAction(Action):
  730. def __init__(self,
  731. option_strings,
  732. dest,
  733. nargs=None,
  734. const=None,
  735. default=None,
  736. type=None,
  737. choices=None,
  738. required=False,
  739. help=None,
  740. metavar=None):
  741. if nargs == 0:
  742. raise ValueError('nargs for append actions must be > 0; if arg '
  743. 'strings are not supplying the value to append, '
  744. 'the append const action may be more appropriate')
  745. if const is not None and nargs != OPTIONAL:
  746. raise ValueError('nargs must be %r to supply const' % OPTIONAL)
  747. super(_AppendAction, self).__init__(
  748. option_strings=option_strings,
  749. dest=dest,
  750. nargs=nargs,
  751. const=const,
  752. default=default,
  753. type=type,
  754. choices=choices,
  755. required=required,
  756. help=help,
  757. metavar=metavar)
  758. def __call__(self, parser, namespace, values, option_string=None):
  759. items = _copy.copy(_ensure_value(namespace, self.dest, []))
  760. items.append(values)
  761. setattr(namespace, self.dest, items)
  762. class _AppendConstAction(Action):
  763. def __init__(self,
  764. option_strings,
  765. dest,
  766. const,
  767. default=None,
  768. required=False,
  769. help=None,
  770. metavar=None):
  771. super(_AppendConstAction, self).__init__(
  772. option_strings=option_strings,
  773. dest=dest,
  774. nargs=0,
  775. const=const,
  776. default=default,
  777. required=required,
  778. help=help,
  779. metavar=metavar)
  780. def __call__(self, parser, namespace, values, option_string=None):
  781. items = _copy.copy(_ensure_value(namespace, self.dest, []))
  782. items.append(self.const)
  783. setattr(namespace, self.dest, items)
  784. class _CountAction(Action):
  785. def __init__(self,
  786. option_strings,
  787. dest,
  788. default=None,
  789. required=False,
  790. help=None):
  791. super(_CountAction, self).__init__(
  792. option_strings=option_strings,
  793. dest=dest,
  794. nargs=0,
  795. default=default,
  796. required=required,
  797. help=help)
  798. def __call__(self, parser, namespace, values, option_string=None):
  799. new_count = _ensure_value(namespace, self.dest, 0) + 1
  800. setattr(namespace, self.dest, new_count)
  801. class _HelpAction(Action):
  802. def __init__(self,
  803. option_strings,
  804. dest=SUPPRESS,
  805. default=SUPPRESS,
  806. help=None):
  807. super(_HelpAction, self).__init__(
  808. option_strings=option_strings,
  809. dest=dest,
  810. default=default,
  811. nargs=0,
  812. help=help)
  813. def __call__(self, parser, namespace, values, option_string=None):
  814. parser.print_help()
  815. parser.exit()
  816. class _VersionAction(Action):
  817. def __init__(self,
  818. option_strings,
  819. version=None,
  820. dest=SUPPRESS,
  821. default=SUPPRESS,
  822. help="show program's version number and exit"):
  823. super(_VersionAction, self).__init__(
  824. option_strings=option_strings,
  825. dest=dest,
  826. default=default,
  827. nargs=0,
  828. help=help)
  829. self.version = version
  830. def __call__(self, parser, namespace, values, option_string=None):
  831. version = self.version
  832. if version is None:
  833. version = parser.version
  834. formatter = parser._get_formatter()
  835. formatter.add_text(version)
  836. parser.exit(message=formatter.format_help())
  837. class _SubParsersAction(Action):
  838. class _ChoicesPseudoAction(Action):
  839. def __init__(self, name, help):
  840. sup = super(_SubParsersAction._ChoicesPseudoAction, self)
  841. sup.__init__(option_strings=[], dest=name, help=help)
  842. def __init__(self,
  843. option_strings,
  844. prog,
  845. parser_class,
  846. dest=SUPPRESS,
  847. help=None,
  848. metavar=None):
  849. self._prog_prefix = prog
  850. self._parser_class = parser_class
  851. self._name_parser_map = _collections.OrderedDict()
  852. self._choices_actions = []
  853. super(_SubParsersAction, self).__init__(
  854. option_strings=option_strings,
  855. dest=dest,
  856. nargs=PARSER,
  857. choices=self._name_parser_map,
  858. help=help,
  859. metavar=metavar)
  860. def add_parser(self, name, **kwargs):
  861. # set prog from the existing prefix
  862. if kwargs.get('prog') is None:
  863. kwargs['prog'] = '%s %s' % (self._prog_prefix, name)
  864. # create a pseudo-action to hold the choice help
  865. if 'help' in kwargs:
  866. help = kwargs.pop('help')
  867. choice_action = self._ChoicesPseudoAction(name, help)
  868. self._choices_actions.append(choice_action)
  869. # create the parser and add it to the map
  870. parser = self._parser_class(**kwargs)
  871. self._name_parser_map[name] = parser
  872. return parser
  873. def _get_subactions(self):
  874. return self._choices_actions
  875. def __call__(self, parser, namespace, values, option_string=None):
  876. parser_name = values[0]
  877. arg_strings = values[1:]
  878. # set the parser name if requested
  879. if self.dest is not SUPPRESS:
  880. setattr(namespace, self.dest, parser_name)
  881. # select the parser
  882. try:
  883. parser = self._name_parser_map[parser_name]
  884. except KeyError:
  885. tup = parser_name, ', '.join(self._name_parser_map)
  886. msg = _('unknown parser %r (choices: %s)') % tup
  887. raise ArgumentError(self, msg)
  888. # parse all the remaining options into the namespace
  889. # store any unrecognized options on the object, so that the top
  890. # level parser can decide what to do with them
  891. namespace, arg_strings = parser.parse_known_args(arg_strings, namespace)
  892. if arg_strings:
  893. vars(namespace).setdefault(_UNRECOGNIZED_ARGS_ATTR, [])
  894. getattr(namespace, _UNRECOGNIZED_ARGS_ATTR).extend(arg_strings)
  895. # ==============
  896. # Type classes
  897. # ==============
  898. class FileType(object):
  899. """Factory for creating file object types
  900. Instances of FileType are typically passed as type= arguments to the
  901. ArgumentParser add_argument() method.
  902. Keyword Arguments:
  903. - mode -- A string indicating how the file is to be opened. Accepts the
  904. same values as the builtin open() function.
  905. - bufsize -- The file's desired buffer size. Accepts the same values as
  906. the builtin open() function.
  907. """
  908. def __init__(self, mode='r', bufsize=-1):
  909. self._mode = mode
  910. self._bufsize = bufsize
  911. def __call__(self, string):
  912. # the special argument "-" means sys.std{in,out}
  913. if string == '-':
  914. if 'r' in self._mode:
  915. return _sys.stdin
  916. elif 'w' in self._mode:
  917. return _sys.stdout
  918. else:
  919. msg = _('argument "-" with mode %r') % self._mode
  920. raise ValueError(msg)
  921. # all other arguments are used as file names
  922. try:
  923. return open(string, self._mode, self._bufsize)
  924. except IOError as e:
  925. message = _("can't open '%s': %s")
  926. raise ArgumentTypeError(message % (string, e))
  927. def __repr__(self):
  928. args = self._mode, self._bufsize
  929. args_str = ', '.join(repr(arg) for arg in args if arg != -1)
  930. return '%s(%s)' % (type(self).__name__, args_str)
  931. # ===========================
  932. # Optional and Positional Parsing
  933. # ===========================
  934. class Namespace(_AttributeHolder):
  935. """Simple object for storing attributes.
  936. Implements equality by attribute names and values, and provides a simple
  937. string representation.
  938. """
  939. def __init__(self, **kwargs):
  940. for name in kwargs:
  941. setattr(self, name, kwargs[name])
  942. __hash__ = None
  943. def __eq__(self, other):
  944. return vars(self) == vars(other)
  945. def __ne__(self, other):
  946. return not (self == other)
  947. def __contains__(self, key):
  948. return key in self.__dict__
  949. class _ActionsContainer(object):
  950. def __init__(self,
  951. description,
  952. prefix_chars,
  953. argument_default,
  954. conflict_handler):
  955. super(_ActionsContainer, self).__init__()
  956. self.description = description
  957. self.argument_default = argument_default
  958. self.prefix_chars = prefix_chars
  959. self.conflict_handler = conflict_handler
  960. # set up registries
  961. self._registries = {}
  962. # register actions
  963. self.register('action', None, _StoreAction)
  964. self.register('action', 'store', _StoreAction)
  965. self.register('action', 'store_const', _StoreConstAction)
  966. self.register('action', 'store_true', _StoreTrueAction)
  967. self.register('action', 'store_false', _StoreFalseAction)
  968. self.register('action', 'append', _AppendAction)
  969. self.register('action', 'append_const', _AppendConstAction)
  970. self.register('action', 'count', _CountAction)
  971. self.register('action', 'help', _HelpAction)
  972. self.register('action', 'version', _VersionAction)
  973. self.register('action', 'parsers', _SubParsersAction)
  974. # raise an exception if the conflict handler is invalid
  975. self._get_handler()
  976. # action storage
  977. self._actions = []
  978. self._option_string_actions = {}
  979. # groups
  980. self._action_groups = []
  981. self._mutually_exclusive_groups = []
  982. # defaults storage
  983. self._defaults = {}
  984. # determines whether an "option" looks like a negative number
  985. self._negative_number_matcher = _re.compile(r'^-\d+$|^-\d*\.\d+$')
  986. # whether or not there are any optionals that look like negative
  987. # numbers -- uses a list so it can be shared and edited
  988. self._has_negative_number_optionals = []
  989. # ====================
  990. # Registration methods
  991. # ====================
  992. def register(self, registry_name, value, object):
  993. registry = self._registries.setdefault(registry_name, {})
  994. registry[value] = object
  995. def _registry_get(self, registry_name, value, default=None):
  996. return self._registries[registry_name].get(value, default)
  997. # ==================================
  998. # Namespace default accessor methods
  999. # ==================================
  1000. def set_defaults(self, **kwargs):
  1001. self._defaults.update(kwargs)
  1002. # if these defaults match any existing arguments, replace
  1003. # the previous default on the object with the new one
  1004. for action in self._actions:
  1005. if action.dest in kwargs:
  1006. action.default = kwargs[action.dest]
  1007. def get_default(self, dest):
  1008. for action in self._actions:
  1009. if action.dest == dest and action.default is not None:
  1010. return action.default
  1011. return self._defaults.get(dest, None)
  1012. # =======================
  1013. # Adding argument actions
  1014. # =======================
  1015. def add_argument(self, *args, **kwargs):
  1016. """
  1017. add_argument(dest, ..., name=value, ...)
  1018. add_argument(option_string, option_string, ..., name=value, ...)
  1019. """
  1020. # if no positional args are supplied or only one is supplied and
  1021. # it doesn't look like an option string, parse a positional
  1022. # argument
  1023. chars = self.prefix_chars
  1024. if not args or len(args) == 1 and args[0][0] not in chars:
  1025. if args and 'dest' in kwargs:
  1026. raise ValueError('dest supplied twice for positional argument')
  1027. kwargs = self._get_positional_kwargs(*args, **kwargs)
  1028. # otherwise, we're adding an optional argument
  1029. else:
  1030. kwargs = self._get_optional_kwargs(*args, **kwargs)
  1031. # if no default was supplied, use the parser-level default
  1032. if 'default' not in kwargs:
  1033. dest = kwargs['dest']
  1034. if dest in self._defaults:
  1035. kwargs['default'] = self._defaults[dest]
  1036. elif self.argument_default is not None:
  1037. kwargs['default'] = self.argument_default
  1038. # create the action object, and add it to the parser
  1039. action_class = self._pop_action_class(kwargs)
  1040. if not _callable(action_class):
  1041. raise ValueError('unknown action "%s"' % (action_class,))
  1042. action = action_class(**kwargs)
  1043. # raise an error if the action type is not callable
  1044. type_func = self._registry_get('type', action.type, action.type)
  1045. if not _callable(type_func):
  1046. raise ValueError('%r is not callable' % (type_func,))
  1047. # raise an error if the metavar does not match the type
  1048. if hasattr(self, "_get_formatter"):
  1049. try:
  1050. self._get_formatter()._format_args(action, None)
  1051. except TypeError:
  1052. raise ValueError("length of metavar tuple does not match nargs")
  1053. return self._add_action(action)
  1054. def add_argument_group(self, *args, **kwargs):
  1055. group = _ArgumentGroup(self, *args, **kwargs)
  1056. self._action_groups.append(group)
  1057. return group
  1058. def add_mutually_exclusive_group(self, **kwargs):
  1059. group = _MutuallyExclusiveGroup(self, **kwargs)
  1060. self._mutually_exclusive_groups.append(group)
  1061. return group
  1062. def _add_action(self, action):
  1063. # resolve any conflicts
  1064. self._check_conflict(action)
  1065. # add to actions list
  1066. self._actions.append(action)
  1067. action.container = self
  1068. # index the action by any option strings it has
  1069. for option_string in action.option_strings:
  1070. self._option_string_actions[option_string] = action
  1071. # set the flag if any option strings look like negative numbers
  1072. for option_string in action.option_strings:
  1073. if self._negative_number_matcher.match(option_string):
  1074. if not self._has_negative_number_optionals:
  1075. self._has_negative_number_optionals.append(True)
  1076. # return the created action
  1077. return action
  1078. def _remove_action(self, action):
  1079. self._actions.remove(action)
  1080. def _add_container_actions(self, container):
  1081. # collect groups by titles
  1082. title_group_map = {}
  1083. for group in self._action_groups:
  1084. if group.title in title_group_map:
  1085. msg = _('cannot merge actions - two groups are named %r')
  1086. raise ValueError(msg % (group.title))
  1087. title_group_map[group.title] = group
  1088. # map each action to its group
  1089. group_map = {}
  1090. for group in container._action_groups:
  1091. # if a group with the title exists, use that, otherwise
  1092. # create a new group matching the container's group
  1093. if group.title not in title_group_map:
  1094. title_group_map[group.title] = self.add_argument_group(
  1095. title=group.title,
  1096. description=group.description,
  1097. conflict_handler=group.conflict_handler)
  1098. # map the actions to their new group
  1099. for action in group._group_actions:
  1100. group_map[action] = title_group_map[group.title]
  1101. # add container's mutually exclusive groups
  1102. # NOTE: if add_mutually_exclusive_group ever gains title= and
  1103. # description= then this code will need to be expanded as above
  1104. for group in container._mutually_exclusive_groups:
  1105. mutex_group = self.add_mutually_exclusive_group(
  1106. required=group.required)
  1107. # map the actions to their new mutex group
  1108. for action in group._group_actions:
  1109. group_map[action] = mutex_group
  1110. # add all actions to this container or their group
  1111. for action in container._actions:
  1112. group_map.get(action, self)._add_action(action)
  1113. def _get_positional_kwargs(self, dest, **kwargs):
  1114. # make sure required is not specified
  1115. if 'required' in kwargs:
  1116. msg = _("'required' is an invalid argument for positionals")
  1117. raise TypeError(msg)
  1118. # mark positional arguments as required if at least one is
  1119. # always required
  1120. if kwargs.get('nargs') not in [OPTIONAL, ZERO_OR_MORE]:
  1121. kwargs['required'] = True
  1122. if kwargs.get('nargs') == ZERO_OR_MORE and 'default' not in kwargs:
  1123. kwargs['required'] = True
  1124. # return the keyword arguments with no option strings
  1125. return dict(kwargs, dest=dest, option_strings=[])
  1126. def _get_optional_kwargs(self, *args, **kwargs):
  1127. # determine short and long option strings
  1128. option_strings = []
  1129. long_option_strings = []
  1130. for option_string in args:
  1131. # error on strings that don't start with an appropriate prefix
  1132. if not option_string[0] in self.prefix_chars:
  1133. msg = _('invalid option string %r: '
  1134. 'must start with a character %r')
  1135. tup = option_string, self.prefix_chars
  1136. raise ValueError(msg % tup)
  1137. # strings starting with two prefix characters are long options
  1138. option_strings.append(option_string)
  1139. if option_string[0] in self.prefix_chars:
  1140. if len(option_string) > 1:
  1141. if option_string[1] in self.prefix_chars:
  1142. long_option_strings.append(option_string)
  1143. # infer destination, '--foo-bar' -> 'foo_bar' and '-x' -> 'x'
  1144. dest = kwargs.pop('dest', None)
  1145. if dest is None:
  1146. if long_option_strings:
  1147. dest_option_string = long_option_strings[0]
  1148. else:
  1149. dest_option_string = option_strings[0]
  1150. dest = dest_option_str

Large files files are truncated, but you can click here to view the full file