PageRenderTime 34ms CodeModel.GetById 1ms RepoModel.GetById 1ms app.codeStats 0ms

/External.LCA_RESTRICTED/Languages/IronPython/27/Lib/argparse.py

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