PageRenderTime 54ms CodeModel.GetById 10ms RepoModel.GetById 1ms app.codeStats 0ms

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

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

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