You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2376 lines
87 KiB

  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 _, ngettext
  77. SUPPRESS = '==SUPPRESS=='
  78. OPTIONAL = '?'
  79. ZERO_OR_MORE = '*'
  80. ONE_OR_MORE = '+'
  81. PARSER = 'A...'
  82. REMAINDER = '...'
  83. _UNRECOGNIZED_ARGS_ATTR = '_unrecognized_args'
  84. # =============================
  85. # Utility functions and classes
  86. # =============================
  87. class _AttributeHolder(object):
  88. """Abstract base class that provides __repr__.
  89. The __repr__ method returns a string in the format::
  90. ClassName(attr=name, attr=name, ...)
  91. The attributes are determined either by a class-level attribute,
  92. '_kwarg_names', or by inspecting the instance __dict__.
  93. """
  94. def __repr__(self):
  95. type_name = type(self).__name__
  96. arg_strings = []
  97. for arg in self._get_args():
  98. arg_strings.append(repr(arg))
  99. for name, value in self._get_kwargs():
  100. arg_strings.append('%s=%r' % (name, value))
  101. return '%s(%s)' % (type_name, ', '.join(arg_strings))
  102. def _get_kwargs(self):
  103. return sorted(self.__dict__.items())
  104. def _get_args(self):
  105. return []
  106. def _ensure_value(namespace, name, value):
  107. if getattr(namespace, name, None) is None:
  108. setattr(namespace, name, value)
  109. return getattr(namespace, name)
  110. # ===============
  111. # Formatting Help
  112. # ===============
  113. class HelpFormatter(object):
  114. """Formatter for generating usage messages and argument help strings.
  115. Only the name of this class is considered a public API. All the methods
  116. provided by the class are considered an implementation detail.
  117. """
  118. def __init__(self,
  119. prog,
  120. indent_increment=2,
  121. max_help_position=24,
  122. width=None):
  123. # default setting for width
  124. if width is None:
  125. try:
  126. width = int(_os.environ['COLUMNS'])
  127. except (KeyError, ValueError):
  128. width = 80
  129. width -= 2
  130. self._prog = prog
  131. self._indent_increment = indent_increment
  132. self._max_help_position = max_help_position
  133. self._width = width
  134. self._current_indent = 0
  135. self._level = 0
  136. self._action_max_length = 0
  137. self._root_section = self._Section(self, None)
  138. self._current_section = self._root_section
  139. self._whitespace_matcher = _re.compile(r'\s+')
  140. self._long_break_matcher = _re.compile(r'\n\n\n+')
  141. # ===============================
  142. # Section and indentation methods
  143. # ===============================
  144. def _indent(self):
  145. self._current_indent += self._indent_increment
  146. self._level += 1
  147. def _dedent(self):
  148. self._current_indent -= self._indent_increment
  149. assert self._current_indent >= 0, 'Indent decreased below 0.'
  150. self._level -= 1
  151. class _Section(object):
  152. def __init__(self, formatter, parent, heading=None):
  153. self.formatter = formatter
  154. self.parent = parent
  155. self.heading = heading
  156. self.items = []
  157. def format_help(self):
  158. # format the indented section
  159. if self.parent is not None:
  160. self.formatter._indent()
  161. join = self.formatter._join_parts
  162. for func, args in self.items:
  163. func(*args)
  164. item_help = join([func(*args) for func, args in self.items])
  165. if self.parent is not None:
  166. self.formatter._dedent()
  167. # return nothing if the section was empty
  168. if not item_help:
  169. return ''
  170. # add the heading if the section was non-empty
  171. if self.heading is not SUPPRESS and self.heading is not None:
  172. current_indent = self.formatter._current_indent
  173. heading = '%*s%s:\n' % (current_indent, '', self.heading)
  174. else:
  175. heading = ''
  176. # join the section-initial newline, the heading and the help
  177. return join(['\n', heading, item_help, '\n'])
  178. def _add_item(self, func, args):
  179. self._current_section.items.append((func, args))
  180. # ========================
  181. # Message building methods
  182. # ========================
  183. def start_section(self, heading):
  184. self._indent()
  185. section = self._Section(self, self._current_section, heading)
  186. self._add_item(section.format_help, [])
  187. self._current_section = section
  188. def end_section(self):
  189. self._current_section = self._current_section.parent
  190. self._dedent()
  191. def add_text(self, text):
  192. if text is not SUPPRESS and text is not None:
  193. self._add_item(self._format_text, [text])
  194. def add_usage(self, usage, actions, groups, prefix=None):
  195. if usage is not SUPPRESS:
  196. args = usage, actions, groups, prefix
  197. self._add_item(self._format_usage, args)
  198. def add_argument(self, action):
  199. if action.help is not SUPPRESS:
  200. # find all invocations
  201. get_invocation = self._format_action_invocation
  202. invocations = [get_invocation(action)]
  203. for subaction in self._iter_indented_subactions(action):
  204. invocations.append(get_invocation(subaction))
  205. # update the maximum item length
  206. invocation_length = max([len(s) for s in invocations])
  207. action_length = invocation_length + self._current_indent
  208. self._action_max_length = max(self._action_max_length,
  209. action_length)
  210. # add the item to the list
  211. self._add_item(self._format_action, [action])
  212. def add_arguments(self, actions):
  213. for action in actions:
  214. self.add_argument(action)
  215. # =======================
  216. # Help-formatting methods
  217. # =======================
  218. def format_help(self):
  219. help = self._root_section.format_help()
  220. if help:
  221. help = self._long_break_matcher.sub('\n\n', help)
  222. help = help.strip('\n') + '\n'
  223. return help
  224. def _join_parts(self, part_strings):
  225. return ''.join([part
  226. for part in part_strings
  227. if part and part is not SUPPRESS])
  228. def _format_usage(self, usage, actions, groups, prefix):
  229. if prefix is None:
  230. prefix = _('usage: ')
  231. # if usage is specified, use that
  232. if usage is not None:
  233. usage = usage % dict(prog=self._prog)
  234. # if no optionals or positionals are available, usage is just prog
  235. elif usage is None and not actions:
  236. usage = '%(prog)s' % dict(prog=self._prog)
  237. # if optionals and positionals are available, calculate usage
  238. elif usage is None:
  239. prog = '%(prog)s' % dict(prog=self._prog)
  240. # split optionals from positionals
  241. optionals = []
  242. positionals = []
  243. for action in actions:
  244. if action.option_strings:
  245. optionals.append(action)
  246. else:
  247. positionals.append(action)
  248. # build full usage string
  249. format = self._format_actions_usage
  250. action_usage = format(optionals + positionals, groups)
  251. usage = ' '.join([s for s in [prog, action_usage] if s])
  252. # wrap the usage parts if it's too long
  253. text_width = self._width - self._current_indent
  254. if len(prefix) + len(usage) > text_width:
  255. # break usage into wrappable parts
  256. part_regexp = r'\(.*?\)+|\[.*?\]+|\S+'
  257. opt_usage = format(optionals, groups)
  258. pos_usage = format(positionals, groups)
  259. opt_parts = _re.findall(part_regexp, opt_usage)
  260. pos_parts = _re.findall(part_regexp, pos_usage)
  261. assert ' '.join(opt_parts) == opt_usage
  262. assert ' '.join(pos_parts) == pos_usage
  263. # helper for wrapping lines
  264. def get_lines(parts, indent, prefix=None):
  265. lines = []
  266. line = []
  267. if prefix is not None:
  268. line_len = len(prefix) - 1
  269. else:
  270. line_len = len(indent) - 1
  271. for part in parts:
  272. if line_len + 1 + len(part) > text_width:
  273. lines.append(indent + ' '.join(line))
  274. line = []
  275. line_len = len(indent) - 1
  276. line.append(part)
  277. line_len += len(part) + 1
  278. if line:
  279. lines.append(indent + ' '.join(line))
  280. if prefix is not None:
  281. lines[0] = lines[0][len(indent):]
  282. return lines
  283. # if prog is short, follow it with optionals or positionals
  284. if len(prefix) + len(prog) <= 0.75 * text_width:
  285. indent = ' ' * (len(prefix) + len(prog) + 1)
  286. if opt_parts:
  287. lines = get_lines([prog] + opt_parts, indent, prefix)
  288. lines.extend(get_lines(pos_parts, indent))
  289. elif pos_parts:
  290. lines = get_lines([prog] + pos_parts, indent, prefix)
  291. else:
  292. lines = [prog]
  293. # if prog is long, put it on its own line
  294. else:
  295. indent = ' ' * len(prefix)
  296. parts = opt_parts + pos_parts
  297. lines = get_lines(parts, indent)
  298. if len(lines) > 1:
  299. lines = []
  300. lines.extend(get_lines(opt_parts, indent))
  301. lines.extend(get_lines(pos_parts, indent))
  302. lines = [prog] + lines
  303. # join lines into usage
  304. usage = '\n'.join(lines)
  305. # prefix with 'usage:'
  306. return '%s%s\n\n' % (prefix, usage)
  307. def _format_actions_usage(self, actions, groups):
  308. # find group indices and identify actions in groups
  309. group_actions = set()
  310. inserts = {}
  311. for group in groups:
  312. try:
  313. start = actions.index(group._group_actions[0])
  314. except ValueError:
  315. continue
  316. else:
  317. end = start + len(group._group_actions)
  318. if actions[start:end] == group._group_actions:
  319. for action in group._group_actions:
  320. group_actions.add(action)
  321. if not group.required:
  322. if start in inserts:
  323. inserts[start] += ' ['
  324. else:
  325. inserts[start] = '['
  326. inserts[end] = ']'
  327. else:
  328. if start in inserts:
  329. inserts[start] += ' ('
  330. else:
  331. inserts[start] = '('
  332. inserts[end] = ')'
  333. for i in range(start + 1, end):
  334. inserts[i] = '|'
  335. # collect all actions format strings
  336. parts = []
  337. for i, action in enumerate(actions):
  338. # suppressed arguments are marked with None
  339. # remove | separators for suppressed arguments
  340. if action.help is SUPPRESS:
  341. parts.append(None)
  342. if inserts.get(i) == '|':
  343. inserts.pop(i)
  344. elif inserts.get(i + 1) == '|':
  345. inserts.pop(i + 1)
  346. # produce all arg strings
  347. elif not action.option_strings:
  348. part = self._format_args(action, action.dest)
  349. # if it's in a group, strip the outer []
  350. if action in group_actions:
  351. if part[0] == '[' and part[-1] == ']':
  352. part = part[1:-1]
  353. # add the action string to the list
  354. parts.append(part)
  355. # produce the first way to invoke the option in brackets
  356. else:
  357. option_string = action.option_strings[0]
  358. # if the Optional doesn't take a value, format is:
  359. # -s or --long
  360. if action.nargs == 0:
  361. part = '%s' % option_string
  362. # if the Optional takes a value, format is:
  363. # -s ARGS or --long ARGS
  364. else:
  365. default = action.dest.upper()
  366. args_string = self._format_args(action, default)
  367. part = '%s %s' % (option_string, args_string)
  368. # make it look optional if it's not required or in a group
  369. if not action.required and action not in group_actions:
  370. part = '[%s]' % part
  371. # add the action string to the list
  372. parts.append(part)
  373. # insert things at the necessary indices
  374. for i in sorted(inserts, reverse=True):
  375. parts[i:i] = [inserts[i]]
  376. # join all the action items with spaces
  377. text = ' '.join([item for item in parts if item is not None])
  378. # clean up separators for mutually exclusive groups
  379. open = r'[\[(]'
  380. close = r'[\])]'
  381. text = _re.sub(r'(%s) ' % open, r'\1', text)
  382. text = _re.sub(r' (%s)' % close, r'\1', text)
  383. text = _re.sub(r'%s *%s' % (open, close), r'', text)
  384. text = _re.sub(r'\(([^|]*)\)', r'\1', text)
  385. text = text.strip()
  386. # return the text
  387. return text
  388. def _format_text(self, text):
  389. if '%(prog)' in text:
  390. text = text % dict(prog=self._prog)
  391. text_width = self._width - self._current_indent
  392. indent = ' ' * self._current_indent
  393. return self._fill_text(text, text_width, indent) + '\n\n'
  394. def _format_action(self, action):
  395. # determine the required width and the entry label
  396. help_position = min(self._action_max_length + 2,
  397. self._max_help_position)
  398. help_width = self._width - help_position
  399. action_width = help_position - self._current_indent - 2
  400. action_header = self._format_action_invocation(action)
  401. # ho nelp; start on same line and add a final newline
  402. if not action.help:
  403. tup = self._current_indent, '', action_header
  404. action_header = '%*s%s\n' % tup
  405. # short action name; start on the same line and pad two spaces
  406. elif len(action_header) <= action_width:
  407. tup = self._current_indent, '', action_width, action_header
  408. action_header = '%*s%-*s ' % tup
  409. indent_first = 0
  410. # long action name; start on the next line
  411. else:
  412. tup = self._current_indent, '', action_header
  413. action_header = '%*s%s\n' % tup
  414. indent_first = help_position
  415. # collect the pieces of the action help
  416. parts = [action_header]
  417. # if there was help for the action, add lines of help text
  418. if action.help:
  419. help_text = self._expand_help(action)
  420. help_lines = self._split_lines(help_text, help_width)
  421. parts.append('%*s%s\n' % (indent_first, '', help_lines[0]))
  422. for line in help_lines[1:]:
  423. parts.append('%*s%s\n' % (help_position, '', line))
  424. # or add a newline if the description doesn't end with one
  425. elif not action_header.endswith('\n'):
  426. parts.append('\n')
  427. # if there are any sub-actions, add their help as well
  428. for subaction in self._iter_indented_subactions(action):
  429. parts.append(self._format_action(subaction))
  430. # return a single string
  431. return self._join_parts(parts)
  432. def _format_action_invocation(self, action):
  433. if not action.option_strings:
  434. metavar, = self._metavar_formatter(action, action.dest)(1)
  435. return metavar
  436. else:
  437. parts = []
  438. # if the Optional doesn't take a value, format is:
  439. # -s, --long
  440. if action.nargs == 0:
  441. parts.extend(action.option_strings)
  442. # if the Optional takes a value, format is:
  443. # -s ARGS, --long ARGS
  444. else:
  445. default = action.dest.upper()
  446. args_string = self._format_args(action, default)
  447. for option_string in action.option_strings:
  448. parts.append('%s %s' % (option_string, args_string))
  449. return ', '.join(parts)
  450. def _metavar_formatter(self, action, default_metavar):
  451. if action.metavar is not None:
  452. result = action.metavar
  453. elif action.choices is not None:
  454. choice_strs = [str(choice) for choice in action.choices]
  455. result = '{%s}' % ','.join(choice_strs)
  456. else:
  457. result = default_metavar
  458. def format(tuple_size):
  459. if isinstance(result, tuple):
  460. return result
  461. else:
  462. return (result, ) * tuple_size
  463. return format
  464. def _format_args(self, action, default_metavar):
  465. get_metavar = self._metavar_formatter(action, default_metavar)
  466. if action.nargs is None:
  467. result = '%s' % get_metavar(1)
  468. elif action.nargs == OPTIONAL:
  469. result = '[%s]' % get_metavar(1)
  470. elif action.nargs == ZERO_OR_MORE:
  471. result = '[%s [%s ...]]' % get_metavar(2)
  472. elif action.nargs == ONE_OR_MORE:
  473. result = '%s [%s ...]' % get_metavar(2)
  474. elif action.nargs == REMAINDER:
  475. result = '...'
  476. elif action.nargs == PARSER:
  477. result = '%s ...' % get_metavar(1)
  478. else:
  479. formats = ['%s' for _ in range(action.nargs)]
  480. result = ' '.join(formats) % get_metavar(action.nargs)
  481. return result
  482. def _expand_help(self, action):
  483. params = dict(vars(action), prog=self._prog)
  484. for name in list(params):
  485. if params[name] is SUPPRESS:
  486. del params[name]
  487. for name in list(params):
  488. if hasattr(params[name], '__name__'):
  489. params[name] = params[name].__name__
  490. if params.get('choices') is not None:
  491. choices_str = ', '.join([str(c) for c in params['choices']])
  492. params['choices'] = choices_str
  493. return self._get_help_string(action) % params
  494. def _iter_indented_subactions(self, action):
  495. try:
  496. get_subactions = action._get_subactions
  497. except AttributeError:
  498. pass
  499. else:
  500. self._indent()
  501. for subaction in get_subactions():
  502. yield subaction
  503. self._dedent()
  504. def _split_lines(self, text, width):
  505. text = self._whitespace_matcher.sub(' ', text).strip()
  506. return _textwrap.wrap(text, width)
  507. def _fill_text(self, text, width, indent):
  508. text = self._whitespace_matcher.sub(' ', text).strip()
  509. return _textwrap.fill(text, width, initial_indent=indent,
  510. subsequent_indent=indent)
  511. def _get_help_string(self, action):
  512. return action.help
  513. class RawDescriptionHelpFormatter(HelpFormatter):
  514. """Help message formatter which retains any formatting in descriptions.
  515. Only the name of this class is considered a public API. All the methods
  516. provided by the class are considered an implementation detail.
  517. """
  518. def _fill_text(self, text, width, indent):
  519. return ''.join([indent + line for line in text.splitlines(True)])
  520. class RawTextHelpFormatter(RawDescriptionHelpFormatter):
  521. """Help message formatter which retains formatting of all help text.
  522. Only the name of this class is considered a public API. All the methods
  523. provided by the class are considered an implementation detail.
  524. """
  525. def _split_lines(self, text, width):
  526. return text.splitlines()
  527. class ArgumentDefaultsHelpFormatter(HelpFormatter):
  528. """Help message formatter which adds default values to argument help.
  529. Only the name of this class is considered a public API. All the methods
  530. provided by the class are considered an implementation detail.
  531. """
  532. def _get_help_string(self, action):
  533. help = action.help
  534. if '%(default)' not in action.help:
  535. if action.default is not SUPPRESS:
  536. defaulting_nargs = [OPTIONAL, ZERO_OR_MORE]
  537. if action.option_strings or action.nargs in defaulting_nargs:
  538. help += ' (default: %(default)s)'
  539. return help
  540. # =====================
  541. # Options and Arguments
  542. # =====================
  543. def _get_action_name(argument):
  544. if argument is None:
  545. return None
  546. elif argument.option_strings:
  547. return '/'.join(argument.option_strings)
  548. elif argument.metavar not in (None, SUPPRESS):
  549. return argument.metavar
  550. elif argument.dest not in (None, SUPPRESS):
  551. return argument.dest
  552. else:
  553. return None
  554. class ArgumentError(Exception):
  555. """An error from creating or using an argument (optional or positional).
  556. The string value of this exception is the message, augmented with
  557. information about the argument that caused it.
  558. """
  559. def __init__(self, argument, message):
  560. self.argument_name = _get_action_name(argument)
  561. self.message = message
  562. def __str__(self):
  563. if self.argument_name is None:
  564. format = '%(message)s'
  565. else:
  566. format = 'argument %(argument_name)s: %(message)s'
  567. return format % dict(message=self.message,
  568. argument_name=self.argument_name)
  569. class ArgumentTypeError(Exception):
  570. """An error from trying to convert a command line string to a type."""
  571. pass
  572. # ==============
  573. # Action classes
  574. # ==============
  575. class Action(_AttributeHolder):
  576. """Information about how to convert command line strings to Python objects.
  577. Action objects are used by an ArgumentParser to represent the information
  578. needed to parse a single argument from one or more strings from the
  579. command line. The keyword arguments to the Action constructor are also
  580. all attributes of Action instances.
  581. Keyword Arguments:
  582. - option_strings -- A list of command-line option strings which
  583. should be associated with this action.
  584. - dest -- The name of the attribute to hold the created object(s)
  585. - nargs -- The number of command-line arguments that should be
  586. consumed. By default, one argument will be consumed and a single
  587. value will be produced. Other values include:
  588. - N (an integer) consumes N arguments (and produces a list)
  589. - '?' consumes zero or one arguments
  590. - '*' consumes zero or more arguments (and produces a list)
  591. - '+' consumes one or more arguments (and produces a list)
  592. Note that the difference between the default and nargs=1 is that
  593. with the default, a single value will be produced, while with
  594. nargs=1, a list containing a single value will be produced.
  595. - const -- The value to be produced if the option is specified and the
  596. option uses an action that takes no values.
  597. - default -- The value to be produced if the option is not specified.
  598. - type -- A callable that accepts a single string argument, and
  599. returns the converted value. The standard Python types str, int,
  600. float, and complex are useful examples of such callables. If None,
  601. str is used.
  602. - choices -- A container of values that should be allowed. If not None,
  603. after a command-line argument has been converted to the appropriate
  604. type, an exception will be raised if it is not a member of this
  605. collection.
  606. - required -- True if the action must always be specified at the
  607. command line. This is only meaningful for optional command-line
  608. arguments.
  609. - help -- The help string describing the argument.
  610. - metavar -- The name to be used for the option's argument with the
  611. help string. If None, the 'dest' value will be used as the name.
  612. """
  613. def __init__(self,
  614. option_strings,
  615. dest,
  616. nargs=None,
  617. const=None,
  618. default=None,
  619. type=None,
  620. choices=None,
  621. required=False,
  622. help=None,
  623. metavar=None):
  624. self.option_strings = option_strings
  625. self.dest = dest
  626. self.nargs = nargs
  627. self.const = const
  628. self.default = default
  629. self.type = type
  630. self.choices = choices
  631. self.required = required
  632. self.help = help
  633. self.metavar = metavar
  634. def _get_kwargs(self):
  635. names = [
  636. 'option_strings',
  637. 'dest',
  638. 'nargs',
  639. 'const',
  640. 'default',
  641. 'type',
  642. 'choices',
  643. 'help',
  644. 'metavar',
  645. ]
  646. return [(name, getattr(self, name)) for name in names]
  647. def __call__(self, parser, namespace, values, option_string=None):
  648. raise NotImplementedError(_('.__call__() not defined'))
  649. class _StoreAction(Action):
  650. def __init__(self,
  651. option_strings,
  652. dest,
  653. nargs=None,
  654. const=None,
  655. default=None,
  656. type=None,
  657. choices=None,
  658. required=False,
  659. help=None,
  660. metavar=None):
  661. if nargs == 0:
  662. raise ValueError('nargs for store actions must be > 0; if you '
  663. 'have nothing to store, actions such as store '
  664. 'true or store const may be more appropriate')
  665. if const is not None and nargs != OPTIONAL:
  666. raise ValueError('nargs must be %r to supply const' % OPTIONAL)
  667. super(_StoreAction, self).__init__(
  668. option_strings=option_strings,
  669. dest=dest,
  670. nargs=nargs,
  671. const=const,
  672. default=default,
  673. type=type,
  674. choices=choices,
  675. required=required,
  676. help=help,
  677. metavar=metavar)
  678. def __call__(self, parser, namespace, values, option_string=None):
  679. setattr(namespace, self.dest, values)
  680. class _StoreConstAction(Action):
  681. def __init__(self,
  682. option_strings,
  683. dest,
  684. const,
  685. default=None,
  686. required=False,
  687. help=None,
  688. metavar=None):
  689. super(_StoreConstAction, self).__init__(
  690. option_strings=option_strings,
  691. dest=dest,
  692. nargs=0,
  693. const=const,
  694. default=default,
  695. required=required,
  696. help=help)
  697. def __call__(self, parser, namespace, values, option_string=None):
  698. setattr(namespace, self.dest, self.const)
  699. class _StoreTrueAction(_StoreConstAction):
  700. def __init__(self,
  701. option_strings,
  702. dest,
  703. default=False,
  704. required=False,
  705. help=None):
  706. super(_StoreTrueAction, self).__init__(
  707. option_strings=option_strings,
  708. dest=dest,
  709. const=True,
  710. default=default,
  711. required=required,
  712. help=help)
  713. class _StoreFalseAction(_StoreConstAction):
  714. def __init__(self,
  715. option_strings,
  716. dest,
  717. default=True,
  718. required=False,
  719. help=None):
  720. super(_StoreFalseAction, self).__init__(
  721. option_strings=option_strings,
  722. dest=dest,
  723. const=False,
  724. default=default,
  725. required=required,
  726. help=help)
  727. class _AppendAction(Action):
  728. def __init__(self,
  729. option_strings,
  730. dest,
  731. nargs=None,
  732. const=None,
  733. default=None,
  734. type=None,
  735. choices=None,
  736. required=False,
  737. help=None,
  738. metavar=None):
  739. if nargs == 0:
  740. raise ValueError('nargs for append actions must be > 0; if arg '
  741. 'strings are not supplying the value to append, '
  742. 'the append const action may be more appropriate')
  743. if const is not None and nargs != OPTIONAL:
  744. raise ValueError('nargs must be %r to supply const' % OPTIONAL)
  745. super(_AppendAction, self).__init__(
  746. option_strings=option_strings,
  747. dest=dest,
  748. nargs=nargs,
  749. const=const,
  750. default=default,
  751. type=type,
  752. choices=choices,
  753. required=required,
  754. help=help,
  755. metavar=metavar)
  756. def __call__(self, parser, namespace, values, option_string=None):
  757. items = _copy.copy(_ensure_value(namespace, self.dest, []))
  758. items.append(values)
  759. setattr(namespace, self.dest, items)
  760. class _AppendConstAction(Action):
  761. def __init__(self,
  762. option_strings,
  763. dest,
  764. const,
  765. default=None,
  766. required=False,
  767. help=None,
  768. metavar=None):
  769. super(_AppendConstAction, self).__init__(
  770. option_strings=option_strings,
  771. dest=dest,
  772. nargs=0,
  773. const=const,
  774. default=default,
  775. required=required,
  776. help=help,
  777. metavar=metavar)
  778. def __call__(self, parser, namespace, values, option_string=None):
  779. items = _copy.copy(_ensure_value(namespace, self.dest, []))
  780. items.append(self.const)
  781. setattr(namespace, self.dest, items)
  782. class _CountAction(Action):
  783. def __init__(self,
  784. option_strings,
  785. dest,
  786. default=None,
  787. required=False,
  788. help=None):
  789. super(_CountAction, self).__init__(
  790. option_strings=option_strings,
  791. dest=dest,
  792. nargs=0,
  793. default=default,
  794. required=required,
  795. help=help)
  796. def __call__(self, parser, namespace, values, option_string=None):
  797. new_count = _ensure_value(namespace, self.dest, 0) + 1
  798. setattr(namespace, self.dest, new_count)
  799. class _HelpAction(Action):
  800. def __init__(self,
  801. option_strings,
  802. dest=SUPPRESS,
  803. default=SUPPRESS,
  804. help=None):
  805. super(_HelpAction, self).__init__(
  806. option_strings=option_strings,
  807. dest=dest,
  808. default=default,
  809. nargs=0,
  810. help=help)
  811. def __call__(self, parser, namespace, values, option_string=None):
  812. parser.print_help()
  813. parser.exit()
  814. class _VersionAction(Action):
  815. def __init__(self,
  816. option_strings,
  817. version=None,
  818. dest=SUPPRESS,
  819. default=SUPPRESS,
  820. help="show program's version number and exit"):
  821. super(_VersionAction, self).__init__(
  822. option_strings=option_strings,
  823. dest=dest,
  824. default=default,
  825. nargs=0,
  826. help=help)
  827. self.version = version
  828. def __call__(self, parser, namespace, values, option_string=None):
  829. version = self.version
  830. if version is None:
  831. version = parser.version
  832. formatter = parser._get_formatter()
  833. formatter.add_text(version)
  834. parser.exit(message=formatter.format_help())
  835. class _SubParsersAction(Action):
  836. class _ChoicesPseudoAction(Action):
  837. def __init__(self, name, aliases, help):
  838. metavar = dest = name
  839. if aliases:
  840. metavar += ' (%s)' % ', '.join(aliases)
  841. sup = super(_SubParsersAction._ChoicesPseudoAction, self)
  842. sup.__init__(option_strings=[], dest=dest, help=help,
  843. metavar=metavar)
  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. aliases = kwargs.pop('aliases', ())
  867. # create a pseudo-action to hold the choice help
  868. if 'help' in kwargs:
  869. help = kwargs.pop('help')
  870. choice_action = self._ChoicesPseudoAction(name, aliases, help)
  871. self._choices_actions.append(choice_action)
  872. # create the parser and add it to the map
  873. parser = self._parser_class(**kwargs)
  874. self._name_parser_map[name] = parser
  875. # make parser available under aliases also
  876. for alias in aliases:
  877. self._name_parser_map[alias] = parser
  878. return parser
  879. def _get_subactions(self):
  880. return self._choices_actions
  881. def __call__(self, parser, namespace, values, option_string=None):
  882. parser_name = values[0]
  883. arg_strings = values[1:]
  884. # set the parser name if requested
  885. if self.dest is not SUPPRESS:
  886. setattr(namespace, self.dest, parser_name)
  887. # select the parser
  888. try:
  889. parser = self._name_parser_map[parser_name]
  890. except KeyError:
  891. args = {'parser_name': parser_name,
  892. 'choices': ', '.join(self._name_parser_map)}
  893. msg = _('unknown parser %(parser_name)r (choices: %(choices)s)') % args
  894. raise ArgumentError(self, msg)
  895. # parse all the remaining options into the namespace
  896. # store any unrecognized options on the object, so that the top
  897. # level parser can decide what to do with them
  898. namespace, arg_strings = parser.parse_known_args(arg_strings, namespace)
  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. def __eq__(self, other):
  950. return vars(self) == vars(other)
  951. def __ne__(self, other):
  952. return not (self == other)
  953. def __contains__(self, key):
  954. return key in self.__dict__
  955. class _ActionsContainer(object):
  956. def __init__(self,
  957. description,
  958. prefix_chars,
  959. argument_default,
  960. conflict_handler):
  961. super(_ActionsContainer, self).__init__()
  962. self.description = description
  963. self.argument_default = argument_default
  964. self.prefix_chars = prefix_chars
  965. self.conflict_handler = conflict_handler
  966. # set up registries
  967. self._registries = {}
  968. # register actions
  969. self.register('action', None, _StoreAction)
  970. self.register('action', 'store', _StoreAction)
  971. self.register('action', 'store_const', _StoreConstAction)
  972. self.register('action', 'store_true', _StoreTrueAction)
  973. self.register('action', 'store_false', _StoreFalseAction)
  974. self.register('action', 'append', _AppendAction)
  975. self.register('action', 'append_const', _AppendConstAction)
  976. self.register('action', 'count', _CountAction)
  977. self.register('action', 'help', _HelpAction)
  978. self.register('action', 'version', _VersionAction)
  979. self.register('action', 'parsers', _SubParsersAction)
  980. # raise an exception if the conflict handler is invalid
  981. self._get_handler()
  982. # action storage
  983. self._actions = []
  984. self._option_string_actions = {}
  985. # groups
  986. self._action_groups = []
  987. self._mutually_exclusive_groups = []
  988. # defaults storage
  989. self._defaults = {}
  990. # determines whether an "option" looks like a negative number
  991. self._negative_number_matcher = _re.compile(r'^-\d+$|^-\d*\.\d+$')
  992. # whether or not there are any optionals that look like negative
  993. # numbers -- uses a list so it can be shared and edited
  994. self._has_negative_number_optionals = []
  995. # ====================
  996. # Registration methods
  997. # ====================
  998. def register(self, registry_name, value, object):
  999. registry = self._registries.setdefault(registry_name, {})
  1000. registry[value] = object
  1001. def _registry_get(self, registry_name, value, default=None):
  1002. return self._registries[registry_name].get(value, default)
  1003. # ==================================
  1004. # Namespace default accessor methods
  1005. # ==================================
  1006. def set_defaults(self, **kwargs):
  1007. self._defaults.update(kwargs)
  1008. # if these defaults match any existing arguments, replace
  1009. # the previous default on the object with the new one
  1010. for action in self._actions:
  1011. if action.dest in kwargs:
  1012. action.default = kwargs[action.dest]
  1013. def get_default(self, dest):
  1014. for action in self._actions:
  1015. if action.dest == dest and action.default is not None:
  1016. return action.default
  1017. return self._defaults.get(dest, None)
  1018. # =======================
  1019. # Adding argument actions
  1020. # =======================
  1021. def add_argument(self, *args, **kwargs):
  1022. """
  1023. add_argument(dest, ..., name=value, ...)
  1024. add_argument(option_string, option_string, ..., name=value, ...)
  1025. """
  1026. # if no positional args are supplied or only one is supplied and
  1027. # it doesn't look like an option string, parse a positional
  1028. # argument
  1029. chars = self.prefix_chars
  1030. if not args or len(args) == 1 and args[0][0] not in chars:
  1031. if args and 'dest' in kwargs:
  1032. raise ValueError('dest supplied twice for positional argument')
  1033. kwargs = self._get_positional_kwargs(*args, **kwargs)
  1034. # otherwise, we're adding an optional argument
  1035. else:
  1036. kwargs = self._get_optional_kwargs(*args, **kwargs)
  1037. # if no default was supplied, use the parser-level default
  1038. if 'default' not in kwargs:
  1039. dest = kwargs['dest']
  1040. if dest in self._defaults:
  1041. kwargs['default'] = self._defaults[dest]
  1042. elif self.argument_default is not None:
  1043. kwargs['default'] = self.argument_default
  1044. # create the action object, and add it to the parser
  1045. action_class = self._pop_action_class(kwargs)
  1046. if not callable(action_class):
  1047. raise ValueError('unknown action "%s"' % (action_class,))
  1048. action = action_class(**kwargs)
  1049. # raise an error if the action type is not callable
  1050. type_func = self._registry_get('type', action.type, action.type)
  1051. if not callable(type_func):
  1052. raise ValueError('%r is not callable' % (type_func,))
  1053. # raise an error if the metavar does not match the type
  1054. if hasattr(self, "_get_formatter"):
  1055. try:
  1056. self._get_formatter()._format_args(action, None)
  1057. except TypeError:
  1058. raise ValueError("length of metavar tuple does not match nargs")
  1059. return self._add_action(action)
  1060. def add_argument_group(self, *args, **kwargs):
  1061. group = _ArgumentGroup(self, *args, **kwargs)
  1062. self._action_groups.append(group)
  1063. return group
  1064. def add_mutually_exclusive_group(self, **kwargs):
  1065. group = _MutuallyExclusiveGroup(self, **kwargs)
  1066. self._mutually_exclusive_groups.append(group)
  1067. return group
  1068. def _add_action(self, action):
  1069. # resolve any conflicts
  1070. self._check_conflict(action)
  1071. # add to actions list
  1072. self._actions.append(action)
  1073. action.container = self
  1074. # index the action by any option strings it has
  1075. for option_string in action.option_strings:
  1076. self._option_string_actions[option_string] = action
  1077. # set the flag if any option strings look like negative numbers
  1078. for option_string in action.option_strings:
  1079. if self._negative_number_matcher.match(option_string):
  1080. if not self._has_negative_number_optionals:
  1081. self._has_negative_number_optionals.append(True)
  1082. # return the created action
  1083. return action
  1084. def _remove_action(self, action):
  1085. self._actions.remove(action)
  1086. def _add_container_actions(self, container):
  1087. # collect groups by titles
  1088. title_group_map = {}
  1089. for group in self._action_groups:
  1090. if group.title in title_group_map:
  1091. msg = _('cannot merge actions - two groups are named %r')
  1092. raise ValueError(msg % (group.title))
  1093. title_group_map[group.title] = group
  1094. # map each action to its group
  1095. group_map = {}
  1096. for group in container._action_groups:
  1097. # if a group with the title exists, use that, otherwise
  1098. # create a new group matching the container's group
  1099. if group.title not in title_group_map:
  1100. title_group_map[group.title] = self.add_argument_group(
  1101. title=group.title,
  1102. description=group.description,
  1103. conflict_handler=group.conflict_handler)
  1104. # map the actions to their new group
  1105. for action in group._group_actions:
  1106. group_map[action] = title_group_map[group.title]
  1107. # add container's mutually exclusive groups
  1108. # NOTE: if add_mutually_exclusive_group ever gains title= and
  1109. # description= then this code will need to be expanded as above
  1110. for group in container._mutually_exclusive_groups:
  1111. mutex_group = self.add_mutually_exclusive_group(
  1112. required=group.required)
  1113. # map the actions to their new mutex group
  1114. for action in group._group_actions:
  1115. group_map[action] = mutex_group
  1116. # add all actions to this container or their group
  1117. for action in container._actions:
  1118. group_map.get(action, self)._add_action(action)
  1119. def _get_positional_kwargs(self, dest, **kwargs):
  1120. # make sure required is not specified
  1121. if 'required' in kwargs:
  1122. msg = _("'required' is an invalid argument for positionals")
  1123. raise TypeError(msg)
  1124. # mark positional arguments as required if at least one is
  1125. # always required
  1126. if kwargs.get('nargs') not in [OPTIONAL, ZERO_OR_MORE]:
  1127. kwargs['required'] = True
  1128. if kwargs.get('nargs') == ZERO_OR_MORE and 'default' not in kwargs:
  1129. kwargs['required'] = True
  1130. # return the keyword arguments with no option strings
  1131. return dict(kwargs, dest=dest, option_strings=[])
  1132. def _get_optional_kwargs(self, *args, **kwargs):
  1133. # determine short and long option strings
  1134. option_strings = []
  1135. long_option_strings = []
  1136. for option_string in args:
  1137. # error on strings that don't start with an appropriate prefix
  1138. if not option_string[0] in self.prefix_chars:
  1139. args = {'option': option_string,
  1140. 'prefix_chars': self.prefix_chars}
  1141. msg = _('invalid option string %(option)r: '
  1142. 'must start with a character %(prefix_chars)r')
  1143. raise ValueError(msg % args)
  1144. # strings starting with two prefix characters are long options
  1145. option_strings.append(option_string)
  1146. if option_string[0] in self.prefix_chars:
  1147. if len(option_string) > 1:
  1148. if option_string[1] in self.prefix_chars:
  1149. long_option_strings.append(option_string)
  1150. # infer destination, '--foo-bar' -> 'foo_bar' and '-x' -> 'x'
  1151. dest = kwargs.pop('dest', None)
  1152. if dest is None:
  1153. if long_option_strings:
  1154. dest_option_string = long_option_strings[0]
  1155. else:
  1156. dest_option_string = option_strings[0]
  1157. dest = dest_option_string.lstrip(self.prefix_chars)
  1158. if not dest:
  1159. msg = _('dest= is required for options like %r')
  1160. raise ValueError(msg % option_string)
  1161. dest = dest.replace('-', '_')
  1162. # return the updated keyword arguments
  1163. return dict(kwargs, dest=dest, option_strings=option_strings)
  1164. def _pop_action_class(self, kwargs, default=None):
  1165. action = kwargs.pop('action', default)
  1166. return self._registry_get('action', action, action)
  1167. def _get_handler(self):
  1168. # determine function from conflict handler string
  1169. handler_func_name = '_handle_conflict_%s' % self.conflict_handler
  1170. try:
  1171. return getattr(self, handler_func_name)
  1172. except AttributeError:
  1173. msg = _('invalid conflict_resolution value: %r')
  1174. raise ValueError(msg % self.conflict_handler)
  1175. def _check_conflict(self, action):
  1176. # find all options that conflict with this option
  1177. confl_optionals = []
  1178. for option_string in action.option_strings:
  1179. if option_string in self._option_string_actions:
  1180. confl_optional = self._option_string_actions[option_string]
  1181. confl_optionals.append((option_string, confl_optional))
  1182. # resolve any conflicts
  1183. if confl_optionals:
  1184. conflict_handler = self._get_handler()
  1185. conflict_handler(action, confl_optionals)
  1186. def _handle_conflict_error(self, action, conflicting_actions):
  1187. message = ngettext('conflicting option string: %s',
  1188. 'conflicting option strings: %s',
  1189. len(conflicting_actions))
  1190. conflict_string = ', '.join([option_string
  1191. for option_string, action
  1192. in conflicting_actions])
  1193. raise ArgumentError(action, message % conflict_string)
  1194. def _handle_conflict_resolve(self, action, conflicting_actions):
  1195. # remove all conflicting options
  1196. for option_string, action in conflicting_actions:
  1197. # remove the conflicting option
  1198. action.option_strings.remove(option_string)
  1199. self._option_string_actions.pop(option_string, None)
  1200. # if the option now has no option string, remove it from the
  1201. # container holding it
  1202. if not action.option_strings:
  1203. action.container._remove_action(action)
  1204. class _ArgumentGroup(_ActionsContainer):
  1205. def __init__(self, container, title=None, description=None, **kwargs):
  1206. # add any missing keyword arguments by checking the container
  1207. update = kwargs.setdefault
  1208. update('conflict_handler', container.conflict_handler)
  1209. update('prefix_chars', container.prefix_chars)
  1210. update('argument_default', container.argument_default)
  1211. super_init = super(_ArgumentGroup, self).__init__
  1212. super_init(description=description, **kwargs)
  1213. # group attributes
  1214. self.title = title
  1215. self._group_actions = []
  1216. # share most attributes with the container
  1217. self._registries = container._registries
  1218. self._actions = container._actions
  1219. self._option_string_actions = container._option_string_actions
  1220. self._defaults = container._defaults
  1221. self._has_negative_number_optionals = \
  1222. container._has_negative_number_optionals
  1223. self._mutually_exclusive_groups = container._mutually_exclusive_groups
  1224. def _add_action(self, action):
  1225. action = super(_ArgumentGroup, self)._add_action(action)
  1226. self._group_actions.append(action)
  1227. return action
  1228. def _remove_action(self, action):
  1229. super(_ArgumentGroup, self)._remove_action(action)
  1230. self._group_actions.remove(action)
  1231. class _MutuallyExclusiveGroup(_ArgumentGroup):
  1232. def __init__(self, container, required=False):
  1233. super(_MutuallyExclusiveGroup, self).__init__(container)
  1234. self.required = required
  1235. self._container = container
  1236. def _add_action(self, action):
  1237. if action.required:
  1238. msg = _('mutually exclusive arguments must be optional')
  1239. raise ValueError(msg)
  1240. action = self._container._add_action(action)
  1241. self._group_actions.append(action)
  1242. return action
  1243. def _remove_action(self, action):
  1244. self._container._remove_action(action)
  1245. self._group_actions.remove(action)
  1246. class ArgumentParser(_AttributeHolder, _ActionsContainer):
  1247. """Object for parsing command line strings into Python objects.
  1248. Keyword Arguments:
  1249. - prog -- The name of the program (default: sys.argv[0])
  1250. - usage -- A usage message (default: auto-generated from arguments)
  1251. - description -- A description of what the program does
  1252. - epilog -- Text following the argument descriptions
  1253. - parents -- Parsers whose arguments should be copied into this one
  1254. - formatter_class -- HelpFormatter class for printing help messages
  1255. - prefix_chars -- Characters that prefix optional arguments
  1256. - fromfile_prefix_chars -- Characters that prefix files containing
  1257. additional arguments
  1258. - argument_default -- The default value for all arguments
  1259. - conflict_handler -- String indicating how to handle conflicts
  1260. - add_help -- Add a -h/-help option
  1261. """
  1262. def __init__(self,
  1263. prog=None,
  1264. usage=None,
  1265. description=None,
  1266. epilog=None,
  1267. version=None,
  1268. parents=[],
  1269. formatter_class=HelpFormatter,
  1270. prefix_chars='-',
  1271. fromfile_prefix_chars=None,
  1272. argument_default=None,
  1273. conflict_handler='error',
  1274. add_help=True):
  1275. if version is not None:
  1276. import warnings
  1277. warnings.warn(
  1278. """The "version" argument to ArgumentParser is deprecated. """
  1279. """Please use """
  1280. """"add_argument(..., action='version', version="N", ...)" """
  1281. """instead""", DeprecationWarning)
  1282. superinit = super(ArgumentParser, self).__init__
  1283. superinit(description=description,
  1284. prefix_chars=prefix_chars,
  1285. argument_default=argument_default,
  1286. conflict_handler=conflict_handler)
  1287. # default setting for prog
  1288. if prog is None:
  1289. prog = _os.path.basename(_sys.argv[0])
  1290. self.prog = prog
  1291. self.usage = usage
  1292. self.epilog = epilog
  1293. self.version = version
  1294. self.formatter_class = formatter_class
  1295. self.fromfile_prefix_chars = fromfile_prefix_chars
  1296. self.add_help = add_help
  1297. add_group = self.add_argument_group
  1298. self._positionals = add_group(_('positional arguments'))
  1299. self._optionals = add_group(_('optional arguments'))
  1300. self._subparsers = None
  1301. # register types
  1302. def identity(string):
  1303. return string
  1304. self.register('type', None, identity)
  1305. # add help and version arguments if necessary
  1306. # (using explicit default to override global argument_default)
  1307. default_prefix = '-' if '-' in prefix_chars else prefix_chars[0]
  1308. if self.add_help:
  1309. self.add_argument(
  1310. default_prefix+'h', default_prefix*2+'help',
  1311. action='help', default=SUPPRESS,
  1312. help=_('show this help message and exit'))
  1313. if self.version:
  1314. self.add_argument(
  1315. default_prefix+'v', default_prefix*2+'version',
  1316. action='version', default=SUPPRESS,
  1317. version=self.version,
  1318. help=_("show program's version number and exit"))
  1319. # add parent arguments and defaults
  1320. for parent in parents:
  1321. self._add_container_actions(parent)
  1322. try:
  1323. defaults = parent._defaults
  1324. except AttributeError:
  1325. pass
  1326. else:
  1327. self._defaults.update(defaults)
  1328. # =======================
  1329. # Pretty __repr__ methods
  1330. # =======================
  1331. def _get_kwargs(self):
  1332. names = [
  1333. 'prog',
  1334. 'usage',
  1335. 'description',
  1336. 'version',
  1337. 'formatter_class',
  1338. 'conflict_handler',
  1339. 'add_help',
  1340. ]
  1341. return [(name, getattr(self, name)) for name in names]
  1342. # ==================================
  1343. # Optional/Positional adding methods
  1344. # ==================================
  1345. def add_subparsers(self, **kwargs):
  1346. if self._subparsers is not None:
  1347. self.error(_('cannot have multiple subparser arguments'))
  1348. # add the parser class to the arguments if it's not present
  1349. kwargs.setdefault('parser_class', type(self))
  1350. if 'title' in kwargs or 'description' in kwargs:
  1351. title = _(kwargs.pop('title', 'subcommands'))
  1352. description = _(kwargs.pop('description', None))
  1353. self._subparsers = self.add_argument_group(title, description)
  1354. else:
  1355. self._subparsers = self._positionals
  1356. # prog defaults to the usage message of this parser, skipping
  1357. # optional arguments and with no "usage:" prefix
  1358. if kwargs.get('prog') is None:
  1359. formatter = self._get_formatter()
  1360. positionals = self._get_positional_actions()
  1361. groups = self._mutually_exclusive_groups
  1362. formatter.add_usage(self.usage, positionals, groups, '')
  1363. kwargs['prog'] = formatter.format_help().strip()
  1364. # create the parsers action and add it to the positionals list
  1365. parsers_class = self._pop_action_class(kwargs, 'parsers')
  1366. action = parsers_class(option_strings=[], **kwargs)
  1367. self._subparsers._add_action(action)
  1368. # return the created parsers action
  1369. return action
  1370. def _add_action(self, action):
  1371. if action.option_strings:
  1372. self._optionals._add_action(action)
  1373. else:
  1374. self._positionals._add_action(action)
  1375. return action
  1376. def _get_optional_actions(self):
  1377. return [action
  1378. for action in self._actions
  1379. if action.option_strings]
  1380. def _get_positional_actions(self):
  1381. return [action
  1382. for action in self._actions
  1383. if not action.option_strings]
  1384. # =====================================
  1385. # Command line argument parsing methods
  1386. # =====================================
  1387. def parse_args(self, args=None, namespace=None):
  1388. args, argv = self.parse_known_args(args, namespace)
  1389. if argv:
  1390. msg = _('unrecognized arguments: %s')
  1391. self.error(msg % ' '.join(argv))
  1392. return args
  1393. def parse_known_args(self, args=None, namespace=None):
  1394. if args is None:
  1395. # args default to the system args
  1396. args = _sys.argv[1:]
  1397. else:
  1398. # make sure that args are mutable
  1399. args = list(args)
  1400. # default Namespace built from parser defaults
  1401. if namespace is None:
  1402. namespace = Namespace()
  1403. # add any action defaults that aren't present
  1404. for action in self._actions:
  1405. if action.dest is not SUPPRESS:
  1406. if not hasattr(namespace, action.dest):
  1407. if action.default is not SUPPRESS:
  1408. setattr(namespace, action.dest, action.default)
  1409. # add any parser defaults that aren't present
  1410. for dest in self._defaults:
  1411. if not hasattr(namespace, dest):
  1412. setattr(namespace, dest, self._defaults[dest])
  1413. # parse the arguments and exit if there are any errors
  1414. try:
  1415. namespace, args = self._parse_known_args(args, namespace)
  1416. if hasattr(namespace, _UNRECOGNIZED_ARGS_ATTR):
  1417. args.extend(getattr(namespace, _UNRECOGNIZED_ARGS_ATTR))
  1418. delattr(namespace, _UNRECOGNIZED_ARGS_ATTR)
  1419. return namespace, args
  1420. except ArgumentError:
  1421. err = _sys.exc_info()[1]
  1422. self.error(str(err))
  1423. def _parse_known_args(self, arg_strings, namespace):
  1424. # replace arg strings that are file references
  1425. if self.fromfile_prefix_chars is not None:
  1426. arg_strings = self._read_args_from_files(arg_strings)
  1427. # map all mutually exclusive arguments to the other arguments
  1428. # they can't occur with
  1429. action_conflicts = {}
  1430. for mutex_group in self._mutually_exclusive_groups:
  1431. group_actions = mutex_group._group_actions
  1432. for i, mutex_action in enumerate(mutex_group._group_actions):
  1433. conflicts = action_conflicts.setdefault(mutex_action, [])
  1434. conflicts.extend(group_actions[:i])
  1435. conflicts.extend(group_actions[i + 1:])
  1436. # find all option indices, and determine the arg_string_pattern
  1437. # which has an 'O' if there is an option at an index,
  1438. # an 'A' if there is an argument, or a '-' if there is a '--'
  1439. option_string_indices = {}
  1440. arg_string_pattern_parts = []
  1441. arg_strings_iter = iter(arg_strings)
  1442. for i, arg_string in enumerate(arg_strings_iter):
  1443. # all args after -- are non-options
  1444. if arg_string == '--':
  1445. arg_string_pattern_parts.append('-')
  1446. for arg_string in arg_strings_iter:
  1447. arg_string_pattern_parts.append('A')
  1448. # otherwise, add the arg to the arg strings
  1449. # and note the index if it was an option
  1450. else:
  1451. option_tuple = self._parse_optional(arg_string)
  1452. if option_tuple is None:
  1453. pattern = 'A'
  1454. else:
  1455. option_string_indices[i] = option_tuple
  1456. pattern = 'O'
  1457. arg_string_pattern_parts.append(pattern)
  1458. # join the pieces together to form the pattern
  1459. arg_strings_pattern = ''.join(arg_string_pattern_parts)
  1460. # converts arg strings to the appropriate and then takes the action
  1461. seen_actions = set()
  1462. seen_non_default_actions = set()
  1463. def take_action(action, argument_strings, option_string=None):
  1464. seen_actions.add(action)
  1465. argument_values = self._get_values(action, argument_strings)
  1466. # error if this argument is not allowed with other previously
  1467. # seen arguments, assuming that actions that use the default
  1468. # value don't really count as "present"
  1469. if argument_values is not action.default:
  1470. seen_non_default_actions.add(action)
  1471. for conflict_action in action_conflicts.get(action, []):
  1472. if conflict_action in seen_non_default_actions:
  1473. msg = _('not allowed with argument %s')
  1474. action_name = _get_action_name(conflict_action)
  1475. raise ArgumentError(action, msg % action_name)
  1476. # take the action if we didn't receive a SUPPRESS value
  1477. # (e.g. from a default)
  1478. if argument_values is not SUPPRESS:
  1479. action(self, namespace, argument_values, option_string)
  1480. # function to convert arg_strings into an optional action
  1481. def consume_optional(start_index):
  1482. # get the optional identified at this index
  1483. option_tuple = option_string_indices[start_index]
  1484. action, option_string, explicit_arg = option_tuple
  1485. # identify additional optionals in the same arg string
  1486. # (e.g. -xyz is the same as -x -y -z if no args are required)
  1487. match_argument = self._match_argument
  1488. action_tuples = []
  1489. while True:
  1490. # if we found no optional action, skip it
  1491. if action is None:
  1492. extras.append(arg_strings[start_index])
  1493. return start_index + 1
  1494. # if there is an explicit argument, try to match the
  1495. # optional's string arguments to only this
  1496. if explicit_arg is not None:
  1497. arg_count = match_argument(action, 'A')
  1498. # if the action is a single-dash option and takes no
  1499. # arguments, try to parse more single-dash options out
  1500. # of the tail of the option string
  1501. chars = self.prefix_chars
  1502. if arg_count == 0 and option_string[1] not in chars:
  1503. action_tuples.append((action, [], option_string))
  1504. char = option_string[0]
  1505. option_string = char + explicit_arg[0]
  1506. new_explicit_arg = explicit_arg[1:] or None
  1507. optionals_map = self._option_string_actions
  1508. if option_string in optionals_map:
  1509. action = optionals_map[option_string]
  1510. explicit_arg = new_explicit_arg
  1511. else:
  1512. msg = _('ignored explicit argument %r')
  1513. raise ArgumentError(action, msg % explicit_arg)
  1514. # if the action expect exactly one argument, we've
  1515. # successfully matched the option; exit the loop
  1516. elif arg_count == 1:
  1517. stop = start_index + 1
  1518. args = [explicit_arg]
  1519. action_tuples.append((action, args, option_string))
  1520. break
  1521. # error if a double-dash option did not use the
  1522. # explicit argument
  1523. else:
  1524. msg = _('ignored explicit argument %r')
  1525. raise ArgumentError(action, msg % explicit_arg)
  1526. # if there is no explicit argument, try to match the
  1527. # optional's string arguments with the following strings
  1528. # if successful, exit the loop
  1529. else:
  1530. start = start_index + 1
  1531. selected_patterns = arg_strings_pattern[start:]
  1532. arg_count = match_argument(action, selected_patterns)
  1533. stop = start + arg_count
  1534. args = arg_strings[start:stop]
  1535. action_tuples.append((action, args, option_string))
  1536. break
  1537. # add the Optional to the list and return the index at which
  1538. # the Optional's string args stopped
  1539. assert action_tuples
  1540. for action, args, option_string in action_tuples:
  1541. take_action(action, args, option_string)
  1542. return stop
  1543. # the list of Positionals left to be parsed; this is modified
  1544. # by consume_positionals()
  1545. positionals = self._get_positional_actions()
  1546. # function to convert arg_strings into positional actions
  1547. def consume_positionals(start_index):
  1548. # match as many Positionals as possible
  1549. match_partial = self._match_arguments_partial
  1550. selected_pattern = arg_strings_pattern[start_index:]
  1551. arg_counts = match_partial(positionals, selected_pattern)
  1552. # slice off the appropriate arg strings for each Positional
  1553. # and add the Positional and its args to the list
  1554. for action, arg_count in zip(positionals, arg_counts):
  1555. args = arg_strings[start_index: start_index + arg_count]
  1556. start_index += arg_count
  1557. take_action(action, args)
  1558. # slice off the Positionals that we just parsed and return the
  1559. # index at which the Positionals' string args stopped
  1560. positionals[:] = positionals[len(arg_counts):]
  1561. return start_index
  1562. # consume Positionals and Optionals alternately, until we have
  1563. # passed the last option string
  1564. extras = []
  1565. start_index = 0
  1566. if option_string_indices:
  1567. max_option_string_index = max(option_string_indices)
  1568. else:
  1569. max_option_string_index = -1
  1570. while start_index <= max_option_string_index:
  1571. # consume any Positionals preceding the next option
  1572. next_option_string_index = min([
  1573. index
  1574. for index in option_string_indices
  1575. if index >= start_index])
  1576. if start_index != next_option_string_index:
  1577. positionals_end_index = consume_positionals(start_index)
  1578. # only try to parse the next optional if we didn't consume
  1579. # the option string during the positionals parsing
  1580. if positionals_end_index > start_index:
  1581. start_index = positionals_end_index
  1582. continue
  1583. else:
  1584. start_index = positionals_end_index
  1585. # if we consumed all the positionals we could and we're not
  1586. # at the index of an option string, there were extra arguments
  1587. if start_index not in option_string_indices:
  1588. strings = arg_strings[start_index:next_option_string_index]
  1589. extras.extend(strings)
  1590. start_index = next_option_string_index
  1591. # consume the next optional and any arguments for it
  1592. start_index = consume_optional(start_index)
  1593. # consume any positionals following the last Optional
  1594. stop_index = consume_positionals(start_index)
  1595. # if we didn't consume all the argument strings, there were extras
  1596. extras.extend(arg_strings[stop_index:])
  1597. # if we didn't use all the Positional objects, there were too few
  1598. # arg strings supplied.
  1599. if positionals:
  1600. self.error(_('too few arguments'))
  1601. # make sure all required actions were present, and convert defaults.
  1602. for action in self._actions:
  1603. if action not in seen_actions:
  1604. if action.required:
  1605. name = _get_action_name(action)
  1606. self.error(_('argument %s is required') % name)
  1607. else:
  1608. # Convert action default now instead of doing it before
  1609. # parsing arguments to avoid calling convert functions
  1610. # twice (which may fail) if the argument was given, but
  1611. # only if it was defined already in the namespace
  1612. if (action.default is not None and
  1613. isinstance(action.default, str) and
  1614. hasattr(namespace, action.dest) and
  1615. action.default is getattr(namespace, action.dest)):
  1616. setattr(namespace, action.dest,
  1617. self._get_value(action, action.default))
  1618. # make sure all required groups had one option present
  1619. for group in self._mutually_exclusive_groups:
  1620. if group.required:
  1621. for action in group._group_actions:
  1622. if action in seen_non_default_actions:
  1623. break
  1624. # if no actions were used, report the error
  1625. else:
  1626. names = [_get_action_name(action)
  1627. for action in group._group_actions
  1628. if action.help is not SUPPRESS]
  1629. msg = _('one of the arguments %s is required')
  1630. self.error(msg % ' '.join(names))
  1631. # return the updated namespace and the extra arguments
  1632. return namespace, extras
  1633. def _read_args_from_files(self, arg_strings):
  1634. # expand arguments referencing files
  1635. new_arg_strings = []
  1636. for arg_string in arg_strings:
  1637. # for regular arguments, just add them back into the list
  1638. if not arg_string or arg_string[0] not in self.fromfile_prefix_chars:
  1639. new_arg_strings.append(arg_string)
  1640. # replace arguments referencing files with the file content
  1641. else:
  1642. try:
  1643. args_file = open(arg_string[1:])
  1644. try:
  1645. arg_strings = []
  1646. for arg_line in args_file.read().splitlines():
  1647. for arg in self.convert_arg_line_to_args(arg_line):
  1648. arg_strings.append(arg)
  1649. arg_strings = self._read_args_from_files(arg_strings)
  1650. new_arg_strings.extend(arg_strings)
  1651. finally:
  1652. args_file.close()
  1653. except IOError:
  1654. err = _sys.exc_info()[1]
  1655. self.error(str(err))
  1656. # return the modified argument list
  1657. return new_arg_strings
  1658. def convert_arg_line_to_args(self, arg_line):
  1659. return [arg_line]
  1660. def _match_argument(self, action, arg_strings_pattern):
  1661. # match the pattern for this action to the arg strings
  1662. nargs_pattern = self._get_nargs_pattern(action)
  1663. match = _re.match(nargs_pattern, arg_strings_pattern)
  1664. # raise an exception if we weren't able to find a match
  1665. if match is None:
  1666. nargs_errors = {
  1667. None: _('expected one argument'),
  1668. OPTIONAL: _('expected at most one argument'),
  1669. ONE_OR_MORE: _('expected at least one argument'),
  1670. }
  1671. default = ngettext('expected %s argument',
  1672. 'expected %s arguments',
  1673. action.nargs) % action.nargs
  1674. msg = nargs_errors.get(action.nargs, default)
  1675. raise ArgumentError(action, msg)
  1676. # return the number of arguments matched
  1677. return len(match.group(1))
  1678. def _match_arguments_partial(self, actions, arg_strings_pattern):
  1679. # progressively shorten the actions list by slicing off the
  1680. # final actions until we find a match
  1681. result = []
  1682. for i in range(len(actions), 0, -1):
  1683. actions_slice = actions[:i]
  1684. pattern = ''.join([self._get_nargs_pattern(action)
  1685. for action in actions_slice])
  1686. match = _re.match(pattern, arg_strings_pattern)
  1687. if match is not None:
  1688. result.extend([len(string) for string in match.groups()])
  1689. break
  1690. # return the list of arg string counts
  1691. return result
  1692. def _parse_optional(self, arg_string):
  1693. # if it's an empty string, it was meant to be a positional
  1694. if not arg_string:
  1695. return None
  1696. # if it doesn't start with a prefix, it was meant to be positional
  1697. if not arg_string[0] in self.prefix_chars:
  1698. return None
  1699. # if the option string is present in the parser, return the action
  1700. if arg_string in self._option_string_actions:
  1701. action = self._option_string_actions[arg_string]
  1702. return action, arg_string, None
  1703. # if it's just a single character, it was meant to be positional
  1704. if len(arg_string) == 1:
  1705. return None
  1706. # if the option string before the "=" is present, return the action
  1707. if '=' in arg_string:
  1708. option_string, explicit_arg = arg_string.split('=', 1)
  1709. if option_string in self._option_string_actions:
  1710. action = self._option_string_actions[option_string]
  1711. return action, option_string, explicit_arg
  1712. # search through all possible prefixes of the option string
  1713. # and all actions in the parser for possible interpretations
  1714. option_tuples = self._get_option_tuples(arg_string)
  1715. # if multiple actions match, the option string was ambiguous
  1716. if len(option_tuples) > 1:
  1717. options = ', '.join([option_string
  1718. for action, option_string, explicit_arg in option_tuples])
  1719. args = {'option': arg_string, 'matches': options}
  1720. msg = _('ambiguous option: %(option)s could match %(matches)s')
  1721. self.error(msg % args)
  1722. # if exactly one action matched, this segmentation is good,
  1723. # so return the parsed action
  1724. elif len(option_tuples) == 1:
  1725. option_tuple, = option_tuples
  1726. return option_tuple
  1727. # if it was not found as an option, but it looks like a negative
  1728. # number, it was meant to be positional
  1729. # unless there are negative-number-like options
  1730. if self._negative_number_matcher.match(arg_string):
  1731. if not self._has_negative_number_optionals:
  1732. return None
  1733. # if it contains a space, it was meant to be a positional
  1734. if ' ' in arg_string:
  1735. return None
  1736. # it was meant to be an optional but there is no such option
  1737. # in this parser (though it might be a valid option in a subparser)
  1738. return None, arg_string, None
  1739. def _get_option_tuples(self, option_string):
  1740. result = []
  1741. # option strings starting with two prefix characters are only
  1742. # split at the '='
  1743. chars = self.prefix_chars
  1744. if option_string[0] in chars and option_string[1] in chars:
  1745. if '=' in option_string:
  1746. option_prefix, explicit_arg = option_string.split('=', 1)
  1747. else:
  1748. option_prefix = option_string
  1749. explicit_arg = None
  1750. for option_string in self._option_string_actions:
  1751. if option_string.startswith(option_prefix):
  1752. action = self._option_string_actions[option_string]
  1753. tup = action, option_string, explicit_arg
  1754. result.append(tup)
  1755. # single character options can be concatenated with their arguments
  1756. # but multiple character options always have to have their argument
  1757. # separate
  1758. elif option_string[0] in chars and option_string[1] not in chars:
  1759. option_prefix = option_string
  1760. explicit_arg = None
  1761. short_option_prefix = option_string[:2]
  1762. short_explicit_arg = option_string[2:]
  1763. for option_string in self._option_string_actions:
  1764. if option_string == short_option_prefix:
  1765. action = self._option_string_actions[option_string]
  1766. tup = action, option_string, short_explicit_arg
  1767. result.append(tup)
  1768. elif option_string.startswith(option_prefix):
  1769. action = self._option_string_actions[option_string]
  1770. tup = action, option_string, explicit_arg
  1771. result.append(tup)
  1772. # shouldn't ever get here
  1773. else:
  1774. self.error(_('unexpected option string: %s') % option_string)
  1775. # return the collected option tuples
  1776. return result
  1777. def _get_nargs_pattern(self, action):
  1778. # in all examples below, we have to allow for '--' args
  1779. # which are represented as '-' in the pattern
  1780. nargs = action.nargs
  1781. # the default (None) is assumed to be a single argument
  1782. if nargs is None:
  1783. nargs_pattern = '(-*A-*)'
  1784. # allow zero or one arguments
  1785. elif nargs == OPTIONAL:
  1786. nargs_pattern = '(-*A?-*)'
  1787. # allow zero or more arguments
  1788. elif nargs == ZERO_OR_MORE:
  1789. nargs_pattern = '(-*[A-]*)'
  1790. # allow one or more arguments
  1791. elif nargs == ONE_OR_MORE:
  1792. nargs_pattern = '(-*A[A-]*)'
  1793. # allow any number of options or arguments
  1794. elif nargs == REMAINDER:
  1795. nargs_pattern = '([-AO]*)'
  1796. # allow one argument followed by any number of options or arguments
  1797. elif nargs == PARSER:
  1798. nargs_pattern = '(-*A[-AO]*)'
  1799. # all others should be integers
  1800. else:
  1801. nargs_pattern = '(-*%s-*)' % '-*'.join('A' * nargs)
  1802. # if this is an optional action, -- is not allowed
  1803. if action.option_strings:
  1804. nargs_pattern = nargs_pattern.replace('-*', '')
  1805. nargs_pattern = nargs_pattern.replace('-', '')
  1806. # return the pattern
  1807. return nargs_pattern
  1808. # ========================
  1809. # Value conversion methods
  1810. # ========================
  1811. def _get_values(self, action, arg_strings):
  1812. # for everything but PARSER, REMAINDER args, strip out first '--'
  1813. if action.nargs not in [PARSER, REMAINDER]:
  1814. try:
  1815. arg_strings.remove('--')
  1816. except ValueError:
  1817. pass
  1818. # optional argument produces a default when not present
  1819. if not arg_strings and action.nargs == OPTIONAL:
  1820. if action.option_strings:
  1821. value = action.const
  1822. else:
  1823. value = action.default
  1824. if isinstance(value, str):
  1825. value = self._get_value(action, value)
  1826. self._check_value(action, value)
  1827. # when nargs='*' on a positional, if there were no command-line
  1828. # args, use the default if it is anything other than None
  1829. elif (not arg_strings and action.nargs == ZERO_OR_MORE and
  1830. not action.option_strings):
  1831. if action.default is not None:
  1832. value = action.default
  1833. else:
  1834. value = arg_strings
  1835. self._check_value(action, value)
  1836. # single argument or optional argument produces a single value
  1837. elif len(arg_strings) == 1 and action.nargs in [None, OPTIONAL]:
  1838. arg_string, = arg_strings
  1839. value = self._get_value(action, arg_string)
  1840. self._check_value(action, value)
  1841. # REMAINDER arguments convert all values, checking none
  1842. elif action.nargs == REMAINDER:
  1843. value = [self._get_value(action, v) for v in arg_strings]
  1844. # PARSER arguments convert all values, but check only the first
  1845. elif action.nargs == PARSER:
  1846. value = [self._get_value(action, v) for v in arg_strings]
  1847. self._check_value(action, value[0])
  1848. # all other types of nargs produce a list
  1849. else:
  1850. value = [self._get_value(action, v) for v in arg_strings]
  1851. for v in value:
  1852. self._check_value(action, v)
  1853. # return the converted value
  1854. return value
  1855. def _get_value(self, action, arg_string):
  1856. type_func = self._registry_get('type', action.type, action.type)
  1857. if not callable(type_func):
  1858. msg = _('%r is not callable')
  1859. raise ArgumentError(action, msg % type_func)
  1860. # convert the value to the appropriate type
  1861. try:
  1862. result = type_func(arg_string)
  1863. # ArgumentTypeErrors indicate errors
  1864. except ArgumentTypeError:
  1865. name = getattr(action.type, '__name__', repr(action.type))
  1866. msg = str(_sys.exc_info()[1])
  1867. raise ArgumentError(action, msg)
  1868. # TypeErrors or ValueErrors also indicate errors
  1869. except (TypeError, ValueError):
  1870. name = getattr(action.type, '__name__', repr(action.type))
  1871. args = {'type': name, 'value': arg_string}
  1872. msg = _('invalid %(type)s value: %(value)r')
  1873. raise ArgumentError(action, msg % args)
  1874. # return the converted value
  1875. return result
  1876. def _check_value(self, action, value):
  1877. # converted value must be one of the choices (if specified)
  1878. if action.choices is not None and value not in action.choices:
  1879. args = {'value': value,
  1880. 'choices': ', '.join(map(repr, action.choices))}
  1881. msg = _('invalid choice: %(value)r (choose from %(choices)s)')
  1882. raise ArgumentError(action, msg % args)
  1883. # =======================
  1884. # Help-formatting methods
  1885. # =======================
  1886. def format_usage(self):
  1887. formatter = self._get_formatter()
  1888. formatter.add_usage(self.usage, self._actions,
  1889. self._mutually_exclusive_groups)
  1890. return formatter.format_help()
  1891. def format_help(self):
  1892. formatter = self._get_formatter()
  1893. # usage
  1894. formatter.add_usage(self.usage, self._actions,
  1895. self._mutually_exclusive_groups)
  1896. # description
  1897. formatter.add_text(self.description)
  1898. # positionals, optionals and user-defined groups
  1899. for action_group in self._action_groups:
  1900. formatter.start_section(action_group.title)
  1901. formatter.add_text(action_group.description)
  1902. formatter.add_arguments(action_group._group_actions)
  1903. formatter.end_section()
  1904. # epilog
  1905. formatter.add_text(self.epilog)
  1906. # determine help from format above
  1907. return formatter.format_help()
  1908. def format_version(self):
  1909. import warnings
  1910. warnings.warn(
  1911. 'The format_version method is deprecated -- the "version" '
  1912. 'argument to ArgumentParser is no longer supported.',
  1913. DeprecationWarning)
  1914. formatter = self._get_formatter()
  1915. formatter.add_text(self.version)
  1916. return formatter.format_help()
  1917. def _get_formatter(self):
  1918. return self.formatter_class(prog=self.prog)
  1919. # =====================
  1920. # Help-printing methods
  1921. # =====================
  1922. def print_usage(self, file=None):
  1923. if file is None:
  1924. file = _sys.stdout
  1925. self._print_message(self.format_usage(), file)
  1926. def print_help(self, file=None):
  1927. if file is None:
  1928. file = _sys.stdout
  1929. self._print_message(self.format_help(), file)
  1930. def print_version(self, file=None):
  1931. import warnings
  1932. warnings.warn(
  1933. 'The print_version method is deprecated -- the "version" '
  1934. 'argument to ArgumentParser is no longer supported.',
  1935. DeprecationWarning)
  1936. self._print_message(self.format_version(), file)
  1937. def _print_message(self, message, file=None):
  1938. if message:
  1939. if file is None:
  1940. file = _sys.stderr
  1941. file.write(message)
  1942. # ===============
  1943. # Exiting methods
  1944. # ===============
  1945. def exit(self, status=0, message=None):
  1946. if message:
  1947. self._print_message(message, _sys.stderr)
  1948. _sys.exit(status)
  1949. def error(self, message):
  1950. """error(message: string)
  1951. Prints a usage message incorporating the message to stderr and
  1952. exits.
  1953. If you override this in a subclass, it should not return -- it
  1954. should either exit or raise an exception.
  1955. """
  1956. self.print_usage(_sys.stderr)
  1957. args = {'prog': self.prog, 'message': message}
  1958. self.exit(2, _('%(prog)s: error: %(message)s\n') % args)