logo

oasis-root

Compiled tree of Oasis Linux based on own branch at <https://hacktivis.me/git/oasis/> git clone https://anongit.hacktivis.me/git/oasis-root.git

argparse.py (97785B)


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