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.

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