PageRenderTime 60ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 0ms

/lib-python/2/argparse.py

https://bitbucket.org/kcr/pypy
Python | 2347 lines | 1948 code | 168 blank | 231 comment | 244 complexity | cf662eb0ae9e5a0f53e15fd50cc9d19d MD5 | raw file
Possible License(s): Apache-2.0
  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_string.lstrip(self.prefix_chars)
  1151. if not dest:
  1152. msg = _('dest= is required for options like %r')
  1153. raise ValueError(msg % option_string)
  1154. dest = dest.replace('-', '_')
  1155. # return the updated keyword arguments
  1156. return dict(kwargs, dest=dest, option_strings=option_strings)
  1157. def _pop_action_class(self, kwargs, default=None):
  1158. action = kwargs.pop('action', default)
  1159. return self._registry_get('action', action, action)
  1160. def _get_handler(self):
  1161. # determine function from conflict handler string
  1162. handler_func_name = '_handle_conflict_%s' % self.conflict_handler
  1163. try:
  1164. return getattr(self, handler_func_name)
  1165. except AttributeError:
  1166. msg = _('invalid conflict_resolution value: %r')
  1167. raise ValueError(msg % self.conflict_handler)
  1168. def _check_conflict(self, action):
  1169. # find all options that conflict with this option
  1170. confl_optionals = []
  1171. for option_string in action.option_strings:
  1172. if option_string in self._option_string_actions:
  1173. confl_optional = self._option_string_actions[option_string]
  1174. confl_optionals.append((option_string, confl_optional))
  1175. # resolve any conflicts
  1176. if confl_optionals:
  1177. conflict_handler = self._get_handler()
  1178. conflict_handler(action, confl_optionals)
  1179. def _handle_conflict_error(self, action, conflicting_actions):
  1180. message = _('conflicting option string(s): %s')
  1181. conflict_string = ', '.join([option_string
  1182. for option_string, action
  1183. in conflicting_actions])
  1184. raise ArgumentError(action, message % conflict_string)
  1185. def _handle_conflict_resolve(self, action, conflicting_actions):
  1186. # remove all conflicting options
  1187. for option_string, action in conflicting_actions:
  1188. # remove the conflicting option
  1189. action.option_strings.remove(option_string)
  1190. self._option_string_actions.pop(option_string, None)
  1191. # if the option now has no option string, remove it from the
  1192. # container holding it
  1193. if not action.option_strings:
  1194. action.container._remove_action(action)
  1195. class _ArgumentGroup(_ActionsContainer):
  1196. def __init__(self, container, title=None, description=None, **kwargs):
  1197. # add any missing keyword arguments by checking the container
  1198. update = kwargs.setdefault
  1199. update('conflict_handler', container.conflict_handler)
  1200. update('prefix_chars', container.prefix_chars)
  1201. update('argument_default', container.argument_default)
  1202. super_init = super(_ArgumentGroup, self).__init__
  1203. super_init(description=description, **kwargs)
  1204. # group attributes
  1205. self.title = title
  1206. self._group_actions = []
  1207. # share most attributes with the container
  1208. self._registries = container._registries
  1209. self._actions = container._actions
  1210. self._option_string_actions = container._option_string_actions
  1211. self._defaults = container._defaults
  1212. self._has_negative_number_optionals = \
  1213. container._has_negative_number_optionals
  1214. self._mutually_exclusive_groups = container._mutually_exclusive_groups
  1215. def _add_action(self, action):
  1216. action = super(_ArgumentGroup, self)._add_action(action)
  1217. self._group_actions.append(action)
  1218. return action
  1219. def _remove_action(self, action):
  1220. super(_ArgumentGroup, self)._remove_action(action)
  1221. self._group_actions.remove(action)
  1222. class _MutuallyExclusiveGroup(_ArgumentGroup):
  1223. def __init__(self, container, required=False):
  1224. super(_MutuallyExclusiveGroup, self).__init__(container)
  1225. self.required = required
  1226. self._container = container
  1227. def _add_action(self, action):
  1228. if action.required:
  1229. msg = _('mutually exclusive arguments must be optional')
  1230. raise ValueError(msg)
  1231. action = self._container._add_action(action)
  1232. self._group_actions.append(action)
  1233. return action
  1234. def _remove_action(self, action):
  1235. self._container._remove_action(action)
  1236. self._group_actions.remove(action)
  1237. class ArgumentParser(_AttributeHolder, _ActionsContainer):
  1238. """Object for parsing command line strings into Python objects.
  1239. Keyword Arguments:
  1240. - prog -- The name of the program (default: sys.argv[0])
  1241. - usage -- A usage message (default: auto-generated from arguments)
  1242. - description -- A description of what the program does
  1243. - epilog -- Text following the argument descriptions
  1244. - parents -- Parsers whose arguments should be copied into this one
  1245. - formatter_class -- HelpFormatter class for printing help messages
  1246. - prefix_chars -- Characters that prefix optional arguments
  1247. - fromfile_prefix_chars -- Characters that prefix files containing
  1248. additional arguments
  1249. - argument_default -- The default value for all arguments
  1250. - conflict_handler -- String indicating how to handle conflicts
  1251. - add_help -- Add a -h/-help option
  1252. """
  1253. def __init__(self,
  1254. prog=None,
  1255. usage=None,
  1256. description=None,
  1257. epilog=None,
  1258. version=None,
  1259. parents=[],
  1260. formatter_class=HelpFormatter,
  1261. prefix_chars='-',
  1262. fromfile_prefix_chars=None,
  1263. argument_default=None,
  1264. conflict_handler='error',
  1265. add_help=True):
  1266. if version is not None:
  1267. import warnings
  1268. warnings.warn(
  1269. """The "version" argument to ArgumentParser is deprecated. """
  1270. """Please use """
  1271. """"add_argument(..., action='version', version="N", ...)" """
  1272. """instead""", DeprecationWarning)
  1273. superinit = super(ArgumentParser, self).__init__
  1274. superinit(description=description,
  1275. prefix_chars=prefix_chars,
  1276. argument_default=argument_default,
  1277. conflict_handler=conflict_handler)
  1278. # default setting for prog
  1279. if prog is None:
  1280. prog = _os.path.basename(_sys.argv[0])
  1281. self.prog = prog
  1282. self.usage = usage
  1283. self.epilog = epilog
  1284. self.version = version
  1285. self.formatter_class = formatter_class
  1286. self.fromfile_prefix_chars = fromfile_prefix_chars
  1287. self.add_help = add_help
  1288. add_group = self.add_argument_group
  1289. self._positionals = add_group(_('positional arguments'))
  1290. self._optionals = add_group(_('optional arguments'))
  1291. self._subparsers = None
  1292. # register types
  1293. def identity(string):
  1294. return string
  1295. self.register('type', None, identity)
  1296. # add help and version arguments if necessary
  1297. # (using explicit default to override global argument_default)
  1298. default_prefix = '-' if '-' in prefix_chars else prefix_chars[0]
  1299. if self.add_help:
  1300. self.add_argument(
  1301. default_prefix+'h', default_prefix*2+'help',
  1302. action='help', default=SUPPRESS,
  1303. help=_('show this help message and exit'))
  1304. if self.version:
  1305. self.add_argument(
  1306. default_prefix+'v', default_prefix*2+'version',
  1307. action='version', default=SUPPRESS,
  1308. version=self.version,
  1309. help=_("show program's version number and exit"))
  1310. # add parent arguments and defaults
  1311. for parent in parents:
  1312. self._add_container_actions(parent)
  1313. try:
  1314. defaults = parent._defaults
  1315. except AttributeError:
  1316. pass
  1317. else:
  1318. self._defaults.update(defaults)
  1319. # =======================
  1320. # Pretty __repr__ methods
  1321. # =======================
  1322. def _get_kwargs(self):
  1323. names = [
  1324. 'prog',
  1325. 'usage',
  1326. 'description',
  1327. 'version',
  1328. 'formatter_class',
  1329. 'conflict_handler',
  1330. 'add_help',
  1331. ]
  1332. return [(name, getattr(self, name)) for name in names]
  1333. # ==================================
  1334. # Optional/Positional adding methods
  1335. # ==================================
  1336. def add_subparsers(self, **kwargs):
  1337. if self._subparsers is not None:
  1338. self.error(_('cannot have multiple subparser arguments'))
  1339. # add the parser class to the arguments if it's not present
  1340. kwargs.setdefault('parser_class', type(self))
  1341. if 'title' in kwargs or 'description' in kwargs:
  1342. title = _(kwargs.pop('title', 'subcommands'))
  1343. description = _(kwargs.pop('description', None))
  1344. self._subparsers = self.add_argument_group(title, description)
  1345. else:
  1346. self._subparsers = self._positionals
  1347. # prog defaults to the usage message of this parser, skipping
  1348. # optional arguments and with no "usage:" prefix
  1349. if kwargs.get('prog') is None:
  1350. formatter = self._get_formatter()
  1351. positionals = self._get_positional_actions()
  1352. groups = self._mutually_exclusive_groups
  1353. formatter.add_usage(self.usage, positionals, groups, '')
  1354. kwargs['prog'] = formatter.format_help().strip()
  1355. # create the parsers action and add it to the positionals list
  1356. parsers_class = self._pop_action_class(kwargs, 'parsers')
  1357. action = parsers_class(option_strings=[], **kwargs)
  1358. self._subparsers._add_action(action)
  1359. # return the created parsers action
  1360. return action
  1361. def _add_action(self, action):
  1362. if action.option_strings:
  1363. self._optionals._add_action(action)
  1364. else:
  1365. self._positionals._add_action(action)
  1366. return action
  1367. def _get_optional_actions(self):
  1368. return [action
  1369. for action in self._actions
  1370. if action.option_strings]
  1371. def _get_positional_actions(self):
  1372. return [action
  1373. for action in self._actions
  1374. if not action.option_strings]
  1375. # =====================================
  1376. # Command line argument parsing methods
  1377. # =====================================
  1378. def parse_args(self, args=None, namespace=None):
  1379. args, argv = self.parse_known_args(args, namespace)
  1380. if argv:
  1381. msg = _('unrecognized arguments: %s')
  1382. self.error(msg % ' '.join(argv))
  1383. return args
  1384. def parse_known_args(self, args=None, namespace=None):
  1385. # args default to the system args
  1386. if args is None:
  1387. args = _sys.argv[1:]
  1388. # default Namespace built from parser defaults
  1389. if namespace is None:
  1390. namespace = Namespace()
  1391. # add any action defaults that aren't present
  1392. for action in self._actions:
  1393. if action.dest is not SUPPRESS:
  1394. if not hasattr(namespace, action.dest):
  1395. if action.default is not SUPPRESS:
  1396. default = action.default
  1397. if isinstance(action.default, basestring):
  1398. default = self._get_value(action, default)
  1399. setattr(namespace, action.dest, default)
  1400. # add any parser defaults that aren't present
  1401. for dest in self._defaults:
  1402. if not hasattr(namespace, dest):
  1403. setattr(namespace, dest, self._defaults[dest])
  1404. # parse the arguments and exit if there are any errors
  1405. try:
  1406. namespace, args = self._parse_known_args(args, namespace)
  1407. if hasattr(namespace, _UNRECOGNIZED_ARGS_ATTR):
  1408. args.extend(getattr(namespace, _UNRECOGNIZED_ARGS_ATTR))
  1409. delattr(namespace, _UNRECOGNIZED_ARGS_ATTR)
  1410. return namespace, args
  1411. except ArgumentError:
  1412. err = _sys.exc_info()[1]
  1413. self.error(str(err))
  1414. def _parse_known_args(self, arg_strings, namespace):
  1415. # replace arg strings that are file references
  1416. if self.fromfile_prefix_chars is not None:
  1417. arg_strings = self._read_args_from_files(arg_strings)
  1418. # map all mutually exclusive arguments to the other arguments
  1419. # they can't occur with
  1420. action_conflicts = {}
  1421. for mutex_group in self._mutually_exclusive_groups:
  1422. group_actions = mutex_group._group_actions
  1423. for i, mutex_action in enumerate(mutex_group._group_actions):
  1424. conflicts = action_conflicts.setdefault(mutex_action, [])
  1425. conflicts.extend(group_actions[:i])
  1426. conflicts.extend(group_actions[i + 1:])
  1427. # find all option indices, and determine the arg_string_pattern
  1428. # which has an 'O' if there is an option at an index,
  1429. # an 'A' if there is an argument, or a '-' if there is a '--'
  1430. option_string_indices = {}
  1431. arg_string_pattern_parts = []
  1432. arg_strings_iter = iter(arg_strings)
  1433. for i, arg_string in enumerate(arg_strings_iter):
  1434. # all args after -- are non-options
  1435. if arg_string == '--':
  1436. arg_string_pattern_parts.append('-')
  1437. for arg_string in arg_strings_iter:
  1438. arg_string_pattern_parts.append('A')
  1439. # otherwise, add the arg to the arg strings
  1440. # and note the index if it was an option
  1441. else:
  1442. option_tuple = self._parse_optional(arg_string)
  1443. if option_tuple is None:
  1444. pattern = 'A'
  1445. else:
  1446. option_string_indices[i] = option_tuple
  1447. pattern = 'O'
  1448. arg_string_pattern_parts.append(pattern)
  1449. # join the pieces together to form the pattern
  1450. arg_strings_pattern = ''.join(arg_string_pattern_parts)
  1451. # converts arg strings to the appropriate and then takes the action
  1452. seen_actions = set()
  1453. seen_non_default_actions = set()
  1454. def take_action(action, argument_strings, option_string=None):
  1455. seen_actions.add(action)
  1456. argument_values = self._get_values(action, argument_strings)
  1457. # error if this argument is not allowed with other previously
  1458. # seen arguments, assuming that actions that use the default
  1459. # value don't really count as "present"
  1460. if argument_values is not action.default:
  1461. seen_non_default_actions.add(action)
  1462. for conflict_action in action_conflicts.get(action, []):
  1463. if conflict_action in seen_non_default_actions:
  1464. msg = _('not allowed with argument %s')
  1465. action_name = _get_action_name(conflict_action)
  1466. raise ArgumentError(action, msg % action_name)
  1467. # take the action if we didn't receive a SUPPRESS value
  1468. # (e.g. from a default)
  1469. if argument_values is not SUPPRESS:
  1470. action(self, namespace, argument_values, option_string)
  1471. # function to convert arg_strings into an optional action
  1472. def consume_optional(start_index):
  1473. # get the optional identified at this index
  1474. option_tuple = option_string_indices[start_index]
  1475. action, option_string, explicit_arg = option_tuple
  1476. # identify additional optionals in the same arg string
  1477. # (e.g. -xyz is the same as -x -y -z if no args are required)
  1478. match_argument = self._match_argument
  1479. action_tuples = []
  1480. while True:
  1481. # if we found no optional action, skip it
  1482. if action is None:
  1483. extras.append(arg_strings[start_index])
  1484. return start_index + 1
  1485. # if there is an explicit argument, try to match the
  1486. # optional's string arguments to only this
  1487. if explicit_arg is not None:
  1488. arg_count = match_argument(action, 'A')
  1489. # if the action is a single-dash option and takes no
  1490. # arguments, try to parse more single-dash options out
  1491. # of the tail of the option string
  1492. chars = self.prefix_chars
  1493. if arg_count == 0 and option_string[1] not in chars:
  1494. action_tuples.append((action, [], option_string))
  1495. char = option_string[0]
  1496. option_string = char + explicit_arg[0]
  1497. new_explicit_arg = explicit_arg[1:] or None
  1498. optionals_map = self._option_string_actions
  1499. if option_string in optionals_map:
  1500. action = optionals_map[option_string]
  1501. explicit_arg = new_explicit_arg
  1502. else:
  1503. msg = _('ignored explicit argument %r')
  1504. raise ArgumentError(action, msg % explicit_arg)
  1505. # if the action expect exactly one argument, we've
  1506. # successfully matched the option; exit the loop
  1507. elif arg_count == 1:
  1508. stop = start_index + 1
  1509. args = [explicit_arg]
  1510. action_tuples.append((action, args, option_string))
  1511. break
  1512. # error if a double-dash option did not use the
  1513. # explicit argument
  1514. else:
  1515. msg = _('ignored explicit argument %r')
  1516. raise ArgumentError(action, msg % explicit_arg)
  1517. # if there is no explicit argument, try to match the
  1518. # optional's string arguments with the following strings
  1519. # if successful, exit the loop
  1520. else:
  1521. start = start_index + 1
  1522. selected_patterns = arg_strings_pattern[start:]
  1523. arg_count = match_argument(action, selected_patterns)
  1524. stop = start + arg_count
  1525. args = arg_strings[start:stop]
  1526. action_tuples.append((action, args, option_string))
  1527. break
  1528. # add the Optional to the list and return the index at which
  1529. # the Optional's string args stopped
  1530. assert action_tuples
  1531. for action, args, option_string in action_tuples:
  1532. take_action(action, args, option_string)
  1533. return stop
  1534. # the list of Positionals left to be parsed; this is modified
  1535. # by consume_positionals()
  1536. positionals = self._get_positional_actions()
  1537. # function to convert arg_strings into positional actions
  1538. def consume_positionals(start_index):
  1539. # match as many Positionals as possible
  1540. match_partial = self._match_arguments_partial
  1541. selected_pattern = arg_strings_pattern[start_index:]
  1542. arg_counts = match_partial(positionals, selected_pattern)
  1543. # slice off the appropriate arg strings for each Positional
  1544. # and add the Positional and its args to the list
  1545. for action, arg_count in zip(positionals, arg_counts):
  1546. args = arg_strings[start_index: start_index + arg_count]
  1547. start_index += arg_count
  1548. take_action(action, args)
  1549. # slice off the Positionals that we just parsed and return the
  1550. # index at which the Positionals' string args stopped
  1551. positionals[:] = positionals[len(arg_counts):]
  1552. return start_index
  1553. # consume Positionals and Optionals alternately, until we have
  1554. # passed the last option string
  1555. extras = []
  1556. start_index = 0
  1557. if option_string_indices:
  1558. max_option_string_index = max(option_string_indices)
  1559. else:
  1560. max_option_string_index = -1
  1561. while start_index <= max_option_string_index:
  1562. # consume any Positionals preceding the next option
  1563. next_option_string_index = min([
  1564. index
  1565. for index in option_string_indices
  1566. if index >= start_index])
  1567. if start_index != next_option_string_index:
  1568. positionals_end_index = consume_positionals(start_index)
  1569. # only try to parse the next optional if we didn't consume
  1570. # the option string during the positionals parsing
  1571. if positionals_end_index > start_index:
  1572. start_index = positionals_end_index
  1573. continue
  1574. else:
  1575. start_index = positionals_end_index
  1576. # if we consumed all the positionals we could and we're not
  1577. # at the index of an option string, there were extra arguments
  1578. if start_index not in option_string_indices:
  1579. strings = arg_strings[start_index:next_option_string_index]
  1580. extras.extend(strings)
  1581. start_index = next_option_string_index
  1582. # consume the next optional and any arguments for it
  1583. start_index = consume_optional(start_index)
  1584. # consume any positionals following the last Optional
  1585. stop_index = consume_positionals(start_index)
  1586. # if we didn't consume all the argument strings, there were extras
  1587. extras.extend(arg_strings[stop_index:])
  1588. # if we didn't use all the Positional objects, there were too few
  1589. # arg strings supplied.
  1590. if positionals:
  1591. self.error(_('too few arguments'))
  1592. # make sure all required actions were present
  1593. for action in self._actions:
  1594. if action.required:
  1595. if action not in seen_actions:
  1596. name = _get_action_name(action)
  1597. self.error(_('argument %s is required') % name)
  1598. # make sure all required groups had one option present
  1599. for group in self._mutually_exclusive_groups:
  1600. if group.required:
  1601. for action in group._group_actions:
  1602. if action in seen_non_default_actions:
  1603. break
  1604. # if no actions were used, report the error
  1605. else:
  1606. names = [_get_action_name(action)
  1607. for action in group._group_actions
  1608. if action.help is not SUPPRESS]
  1609. msg = _('one of the arguments %s is required')
  1610. self.error(msg % ' '.join(names))
  1611. # return the updated namespace and the extra arguments
  1612. return namespace, extras
  1613. def _read_args_from_files(self, arg_strings):
  1614. # expand arguments referencing files
  1615. new_arg_strings = []
  1616. for arg_string in arg_strings:
  1617. # for regular arguments, just add them back into the list
  1618. if arg_string[0] not in self.fromfile_prefix_chars:
  1619. new_arg_strings.append(arg_string)
  1620. # replace arguments referencing files with the file content
  1621. else:
  1622. try:
  1623. args_file = open(arg_string[1:])
  1624. try:
  1625. arg_strings = []
  1626. for arg_line in args_file.read().splitlines():
  1627. for arg in self.convert_arg_line_to_args(arg_line):
  1628. arg_strings.append(arg)
  1629. arg_strings = self._read_args_from_files(arg_strings)
  1630. new_arg_strings.extend(arg_strings)
  1631. finally:
  1632. args_file.close()
  1633. except IOError:
  1634. err = _sys.exc_info()[1]
  1635. self.error(str(err))
  1636. # return the modified argument list
  1637. return new_arg_strings
  1638. def convert_arg_line_to_args(self, arg_line):
  1639. return [arg_line]
  1640. def _match_argument(self, action, arg_strings_pattern):
  1641. # match the pattern for this action to the arg strings
  1642. nargs_pattern = self._get_nargs_pattern(action)
  1643. match = _re.match(nargs_pattern, arg_strings_pattern)
  1644. # raise an exception if we weren't able to find a match
  1645. if match is None:
  1646. nargs_errors = {
  1647. None: _('expected one argument'),
  1648. OPTIONAL: _('expected at most one argument'),
  1649. ONE_OR_MORE: _('expected at least one argument'),
  1650. }
  1651. default = _('expected %s argument(s)') % action.nargs
  1652. msg = nargs_errors.get(action.nargs, default)
  1653. raise ArgumentError(action, msg)
  1654. # return the number of arguments matched
  1655. return len(match.group(1))
  1656. def _match_arguments_partial(self, actions, arg_strings_pattern):
  1657. # progressively shorten the actions list by slicing off the
  1658. # final actions until we find a match
  1659. result = []
  1660. for i in range(len(actions), 0, -1):
  1661. actions_slice = actions[:i]
  1662. pattern = ''.join([self._get_nargs_pattern(action)
  1663. for action in actions_slice])
  1664. match = _re.match(pattern, arg_strings_pattern)
  1665. if match is not None:
  1666. result.extend([len(string) for string in match.groups()])
  1667. break
  1668. # return the list of arg string counts
  1669. return result
  1670. def _parse_optional(self, arg_string):
  1671. # if it's an empty string, it was meant to be a positional
  1672. if not arg_string:
  1673. return None
  1674. # if it doesn't start with a prefix, it was meant to be positional
  1675. if not arg_string[0] in self.prefix_chars:
  1676. return None
  1677. # if the option string is present in the parser, return the action
  1678. if arg_string in self._option_string_actions:
  1679. action = self._option_string_actions[arg_string]
  1680. return action, arg_string, None
  1681. # if it's just a single character, it was meant to be positional
  1682. if len(arg_string) == 1:
  1683. return None
  1684. # if the option string before the "=" is present, return the action
  1685. if '=' in arg_string:
  1686. option_string, explicit_arg = arg_string.split('=', 1)
  1687. if option_string in self._option_string_actions:
  1688. action = self._option_string_actions[option_string]
  1689. return action, option_string, explicit_arg
  1690. # search through all possible prefixes of the option string
  1691. # and all actions in the parser for possible interpretations
  1692. option_tuples = self._get_option_tuples(arg_string)
  1693. # if multiple actions match, the option string was ambiguous
  1694. if len(option_tuples) > 1:
  1695. options = ', '.join([option_string
  1696. for action, option_string, explicit_arg in option_tuples])
  1697. tup = arg_string, options
  1698. self.error(_('ambiguous option: %s could match %s') % tup)
  1699. # if exactly one action matched, this segmentation is good,
  1700. # so return the parsed action
  1701. elif len(option_tuples) == 1:
  1702. option_tuple, = option_tuples
  1703. return option_tuple
  1704. # if it was not found as an option, but it looks like a negative
  1705. # number, it was meant to be positional
  1706. # unless there are negative-number-like options
  1707. if self._negative_number_matcher.match(arg_string):
  1708. if not self._has_negative_number_optionals:
  1709. return None
  1710. # if it contains a space, it was meant to be a positional
  1711. if ' ' in arg_string:
  1712. return None
  1713. # it was meant to be an optional but there is no such option
  1714. # in this parser (though it might be a valid option in a subparser)
  1715. return None, arg_string, None
  1716. def _get_option_tuples(self, option_string):
  1717. result = []
  1718. # option strings starting with two prefix characters are only
  1719. # split at the '='
  1720. chars = self.prefix_chars
  1721. if option_string[0] in chars and option_string[1] in chars:
  1722. if '=' in option_string:
  1723. option_prefix, explicit_arg = option_string.split('=', 1)
  1724. else:
  1725. option_prefix = option_string
  1726. explicit_arg = None
  1727. for option_string in self._option_string_actions:
  1728. if option_string.startswith(option_prefix):
  1729. action = self._option_string_actions[option_string]
  1730. tup = action, option_string, explicit_arg
  1731. result.append(tup)
  1732. # single character options can be concatenated with their arguments
  1733. # but multiple character options always have to have their argument
  1734. # separate
  1735. elif option_string[0] in chars and option_string[1] not in chars:
  1736. option_prefix = option_string
  1737. explicit_arg = None
  1738. short_option_prefix = option_string[:2]
  1739. short_explicit_arg = option_string[2:]
  1740. for option_string in self._option_string_actions:
  1741. if option_string == short_option_prefix:
  1742. action = self._option_string_actions[option_string]
  1743. tup = action, option_string, short_explicit_arg
  1744. result.append(tup)
  1745. elif option_string.startswith(option_prefix):
  1746. action = self._option_string_actions[option_string]
  1747. tup = action, option_string, explicit_arg
  1748. result.append(tup)
  1749. # shouldn't ever get here
  1750. else:
  1751. self.error(_('unexpected option string: %s') % option_string)
  1752. # return the collected option tuples
  1753. return result
  1754. def _get_nargs_pattern(self, action):
  1755. # in all examples below, we have to allow for '--' args
  1756. # which are represented as '-' in the pattern
  1757. nargs = action.nargs
  1758. # the default (None) is assumed to be a single argument
  1759. if nargs is None:
  1760. nargs_pattern = '(-*A-*)'
  1761. # allow zero or one arguments
  1762. elif nargs == OPTIONAL:
  1763. nargs_pattern = '(-*A?-*)'
  1764. # allow zero or more arguments
  1765. elif nargs == ZERO_OR_MORE:
  1766. nargs_pattern = '(-*[A-]*)'
  1767. # allow one or more arguments
  1768. elif nargs == ONE_OR_MORE:
  1769. nargs_pattern = '(-*A[A-]*)'
  1770. # allow any number of options or arguments
  1771. elif nargs == REMAINDER:
  1772. nargs_pattern = '([-AO]*)'
  1773. # allow one argument followed by any number of options or arguments
  1774. elif nargs == PARSER:
  1775. nargs_pattern = '(-*A[-AO]*)'
  1776. # all others should be integers
  1777. else:
  1778. nargs_pattern = '(-*%s-*)' % '-*'.join('A' * nargs)
  1779. # if this is an optional action, -- is not allowed
  1780. if action.option_strings:
  1781. nargs_pattern = nargs_pattern.replace('-*', '')
  1782. nargs_pattern = nargs_pattern.replace('-', '')
  1783. # return the pattern
  1784. return nargs_pattern
  1785. # ========================
  1786. # Value conversion methods
  1787. # ========================
  1788. def _get_values(self, action, arg_strings):
  1789. # for everything but PARSER args, strip out '--'
  1790. if action.nargs not in [PARSER, REMAINDER]:
  1791. arg_strings = [s for s in arg_strings if s != '--']
  1792. # optional argument produces a default when not present
  1793. if not arg_strings and action.nargs == OPTIONAL:
  1794. if action.option_strings:
  1795. value = action.const
  1796. else:
  1797. value = action.default
  1798. if isinstance(value, basestring):
  1799. value = self._get_value(action, value)
  1800. self._check_value(action, value)
  1801. # when nargs='*' on a positional, if there were no command-line
  1802. # args, use the default if it is anything other than None
  1803. elif (not arg_strings and action.nargs == ZERO_OR_MORE and
  1804. not action.option_strings):
  1805. if action.default is not None:
  1806. value = action.default
  1807. else:
  1808. value = arg_strings
  1809. self._check_value(action, value)
  1810. # single argument or optional argument produces a single value
  1811. elif len(arg_strings) == 1 and action.nargs in [None, OPTIONAL]:
  1812. arg_string, = arg_strings
  1813. value = self._get_value(action, arg_string)
  1814. self._check_value(action, value)
  1815. # REMAINDER arguments convert all values, checking none
  1816. elif action.nargs == REMAINDER:
  1817. value = [self._get_value(action, v) for v in arg_strings]
  1818. # PARSER arguments convert all values, but check only the first
  1819. elif action.nargs == PARSER:
  1820. value = [self._get_value(action, v) for v in arg_strings]
  1821. self._check_value(action, value[0])
  1822. # all other types of nargs produce a list
  1823. else:
  1824. value = [self._get_value(action, v) for v in arg_strings]
  1825. for v in value:
  1826. self._check_value(action, v)
  1827. # return the converted value
  1828. return value
  1829. def _get_value(self, action, arg_string):
  1830. type_func = self._registry_get('type', action.type, action.type)
  1831. if not _callable(type_func):
  1832. msg = _('%r is not callable')
  1833. raise ArgumentError(action, msg % type_func)
  1834. # convert the value to the appropriate type
  1835. try:
  1836. result = type_func(arg_string)
  1837. # ArgumentTypeErrors indicate errors
  1838. except ArgumentTypeError:
  1839. name = getattr(action.type, '__name__', repr(action.type))
  1840. msg = str(_sys.exc_info()[1])
  1841. raise ArgumentError(action, msg)
  1842. # TypeErrors or ValueErrors also indicate errors
  1843. except (TypeError, ValueError):
  1844. name = getattr(action.type, '__name__', repr(action.type))
  1845. msg = _('invalid %s value: %r')
  1846. raise ArgumentError(action, msg % (name, arg_string))
  1847. # return the converted value
  1848. return result
  1849. def _check_value(self, action, value):
  1850. # converted value must be one of the choices (if specified)
  1851. if action.choices is not None and value not in action.choices:
  1852. tup = value, ', '.join(map(repr, action.choices))
  1853. msg = _('invalid choice: %r (choose from %s)') % tup
  1854. raise ArgumentError(action, msg)
  1855. # =======================
  1856. # Help-formatting methods
  1857. # =======================
  1858. def format_usage(self):
  1859. formatter = self._get_formatter()
  1860. formatter.add_usage(self.usage, self._actions,
  1861. self._mutually_exclusive_groups)
  1862. return formatter.format_help()
  1863. def format_help(self):
  1864. formatter = self._get_formatter()
  1865. # usage
  1866. formatter.add_usage(self.usage, self._actions,
  1867. self._mutually_exclusive_groups)
  1868. # description
  1869. formatter.add_text(self.description)
  1870. # positionals, optionals and user-defined groups
  1871. for action_group in self._action_groups:
  1872. formatter.start_section(action_group.title)
  1873. formatter.add_text(action_group.description)
  1874. formatter.add_arguments(action_group._group_actions)
  1875. formatter.end_section()
  1876. # epilog
  1877. formatter.add_text(self.epilog)
  1878. # determine help from format above
  1879. return formatter.format_help()
  1880. def format_version(self):
  1881. import warnings
  1882. warnings.warn(
  1883. 'The format_version method is deprecated -- the "version" '
  1884. 'argument to ArgumentParser is no longer supported.',
  1885. DeprecationWarning)
  1886. formatter = self._get_formatter()
  1887. formatter.add_text(self.version)
  1888. return formatter.format_help()
  1889. def _get_formatter(self):
  1890. return self.formatter_class(prog=self.prog)
  1891. # =====================
  1892. # Help-printing methods
  1893. # =====================
  1894. def print_usage(self, file=None):
  1895. if file is None:
  1896. file = _sys.stdout
  1897. self._print_message(self.format_usage(), file)
  1898. def print_help(self, file=None):
  1899. if file is None:
  1900. file = _sys.stdout
  1901. self._print_message(self.format_help(), file)
  1902. def print_version(self, file=None):
  1903. import warnings
  1904. warnings.warn(
  1905. 'The print_version method is deprecated -- the "version" '
  1906. 'argument to ArgumentParser is no longer supported.',
  1907. DeprecationWarning)
  1908. self._print_message(self.format_version(), file)
  1909. def _print_message(self, message, file=None):
  1910. if message:
  1911. if file is None:
  1912. file = _sys.stderr
  1913. file.write(message)
  1914. # ===============
  1915. # Exiting methods
  1916. # ===============
  1917. def exit(self, status=0, message=None):
  1918. if message:
  1919. self._print_message(message, _sys.stderr)
  1920. _sys.exit(status)
  1921. def error(self, message):
  1922. """error(message: string)
  1923. Prints a usage message incorporating the message to stderr and
  1924. exits.
  1925. If you override this in a subclass, it should not return -- it
  1926. should either exit or raise an exception.
  1927. """
  1928. self.print_usage(_sys.stderr)
  1929. self.exit(2, _('%s: error: %s\n') % (self.prog, message))