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.

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