PageRenderTime 74ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 0ms

/lib-python/2.7/optparse.py

https://bitbucket.org/dac_io/pypy
Python | 1703 lines | 1633 code | 3 blank | 67 comment | 16 complexity | b3d4c9e26fb64537629d2c37e7952945 MD5 | raw file

Large files files are truncated, but you can click here to view the full file

  1. """A powerful, extensible, and easy-to-use option parser.
  2. By Greg Ward <gward@python.net>
  3. Originally distributed as Optik.
  4. For support, use the optik-users@lists.sourceforge.net mailing list
  5. (http://lists.sourceforge.net/lists/listinfo/optik-users).
  6. Simple usage example:
  7. from optparse import OptionParser
  8. parser = OptionParser()
  9. parser.add_option("-f", "--file", dest="filename",
  10. help="write report to FILE", metavar="FILE")
  11. parser.add_option("-q", "--quiet",
  12. action="store_false", dest="verbose", default=True,
  13. help="don't print status messages to stdout")
  14. (options, args) = parser.parse_args()
  15. """
  16. __version__ = "1.5.3"
  17. __all__ = ['Option',
  18. 'make_option',
  19. 'SUPPRESS_HELP',
  20. 'SUPPRESS_USAGE',
  21. 'Values',
  22. 'OptionContainer',
  23. 'OptionGroup',
  24. 'OptionParser',
  25. 'HelpFormatter',
  26. 'IndentedHelpFormatter',
  27. 'TitledHelpFormatter',
  28. 'OptParseError',
  29. 'OptionError',
  30. 'OptionConflictError',
  31. 'OptionValueError',
  32. 'BadOptionError']
  33. __copyright__ = """
  34. Copyright (c) 2001-2006 Gregory P. Ward. All rights reserved.
  35. Copyright (c) 2002-2006 Python Software Foundation. All rights reserved.
  36. Redistribution and use in source and binary forms, with or without
  37. modification, are permitted provided that the following conditions are
  38. met:
  39. * Redistributions of source code must retain the above copyright
  40. notice, this list of conditions and the following disclaimer.
  41. * Redistributions in binary form must reproduce the above copyright
  42. notice, this list of conditions and the following disclaimer in the
  43. documentation and/or other materials provided with the distribution.
  44. * Neither the name of the author nor the names of its
  45. contributors may be used to endorse or promote products derived from
  46. this software without specific prior written permission.
  47. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
  48. IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
  49. TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
  50. PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR
  51. CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
  52. EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  53. PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  54. PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  55. LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  56. NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  57. SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  58. """
  59. import sys, os
  60. import types
  61. import textwrap
  62. def _repr(self):
  63. return "<%s at 0x%x: %s>" % (self.__class__.__name__, id(self), self)
  64. # This file was generated from:
  65. # Id: option_parser.py 527 2006-07-23 15:21:30Z greg
  66. # Id: option.py 522 2006-06-11 16:22:03Z gward
  67. # Id: help.py 527 2006-07-23 15:21:30Z greg
  68. # Id: errors.py 509 2006-04-20 00:58:24Z gward
  69. try:
  70. from gettext import gettext
  71. except ImportError:
  72. def gettext(message):
  73. return message
  74. _ = gettext
  75. class OptParseError (Exception):
  76. def __init__(self, msg):
  77. self.msg = msg
  78. def __str__(self):
  79. return self.msg
  80. class OptionError (OptParseError):
  81. """
  82. Raised if an Option instance is created with invalid or
  83. inconsistent arguments.
  84. """
  85. def __init__(self, msg, option):
  86. self.msg = msg
  87. self.option_id = str(option)
  88. def __str__(self):
  89. if self.option_id:
  90. return "option %s: %s" % (self.option_id, self.msg)
  91. else:
  92. return self.msg
  93. class OptionConflictError (OptionError):
  94. """
  95. Raised if conflicting options are added to an OptionParser.
  96. """
  97. class OptionValueError (OptParseError):
  98. """
  99. Raised if an invalid option value is encountered on the command
  100. line.
  101. """
  102. class BadOptionError (OptParseError):
  103. """
  104. Raised if an invalid option is seen on the command line.
  105. """
  106. def __init__(self, opt_str):
  107. self.opt_str = opt_str
  108. def __str__(self):
  109. return _("no such option: %s") % self.opt_str
  110. class AmbiguousOptionError (BadOptionError):
  111. """
  112. Raised if an ambiguous option is seen on the command line.
  113. """
  114. def __init__(self, opt_str, possibilities):
  115. BadOptionError.__init__(self, opt_str)
  116. self.possibilities = possibilities
  117. def __str__(self):
  118. return (_("ambiguous option: %s (%s?)")
  119. % (self.opt_str, ", ".join(self.possibilities)))
  120. class HelpFormatter:
  121. """
  122. Abstract base class for formatting option help. OptionParser
  123. instances should use one of the HelpFormatter subclasses for
  124. formatting help; by default IndentedHelpFormatter is used.
  125. Instance attributes:
  126. parser : OptionParser
  127. the controlling OptionParser instance
  128. indent_increment : int
  129. the number of columns to indent per nesting level
  130. max_help_position : int
  131. the maximum starting column for option help text
  132. help_position : int
  133. the calculated starting column for option help text;
  134. initially the same as the maximum
  135. width : int
  136. total number of columns for output (pass None to constructor for
  137. this value to be taken from the $COLUMNS environment variable)
  138. level : int
  139. current indentation level
  140. current_indent : int
  141. current indentation level (in columns)
  142. help_width : int
  143. number of columns available for option help text (calculated)
  144. default_tag : str
  145. text to replace with each option's default value, "%default"
  146. by default. Set to false value to disable default value expansion.
  147. option_strings : { Option : str }
  148. maps Option instances to the snippet of help text explaining
  149. the syntax of that option, e.g. "-h, --help" or
  150. "-fFILE, --file=FILE"
  151. _short_opt_fmt : str
  152. format string controlling how short options with values are
  153. printed in help text. Must be either "%s%s" ("-fFILE") or
  154. "%s %s" ("-f FILE"), because those are the two syntaxes that
  155. Optik supports.
  156. _long_opt_fmt : str
  157. similar but for long options; must be either "%s %s" ("--file FILE")
  158. or "%s=%s" ("--file=FILE").
  159. """
  160. NO_DEFAULT_VALUE = "none"
  161. def __init__(self,
  162. indent_increment,
  163. max_help_position,
  164. width,
  165. short_first):
  166. self.parser = None
  167. self.indent_increment = indent_increment
  168. self.help_position = self.max_help_position = max_help_position
  169. if width is None:
  170. try:
  171. width = int(os.environ['COLUMNS'])
  172. except (KeyError, ValueError):
  173. width = 80
  174. width -= 2
  175. self.width = width
  176. self.current_indent = 0
  177. self.level = 0
  178. self.help_width = None # computed later
  179. self.short_first = short_first
  180. self.default_tag = "%default"
  181. self.option_strings = {}
  182. self._short_opt_fmt = "%s %s"
  183. self._long_opt_fmt = "%s=%s"
  184. def set_parser(self, parser):
  185. self.parser = parser
  186. def set_short_opt_delimiter(self, delim):
  187. if delim not in ("", " "):
  188. raise ValueError(
  189. "invalid metavar delimiter for short options: %r" % delim)
  190. self._short_opt_fmt = "%s" + delim + "%s"
  191. def set_long_opt_delimiter(self, delim):
  192. if delim not in ("=", " "):
  193. raise ValueError(
  194. "invalid metavar delimiter for long options: %r" % delim)
  195. self._long_opt_fmt = "%s" + delim + "%s"
  196. def indent(self):
  197. self.current_indent += self.indent_increment
  198. self.level += 1
  199. def dedent(self):
  200. self.current_indent -= self.indent_increment
  201. assert self.current_indent >= 0, "Indent decreased below 0."
  202. self.level -= 1
  203. def format_usage(self, usage):
  204. raise NotImplementedError, "subclasses must implement"
  205. def format_heading(self, heading):
  206. raise NotImplementedError, "subclasses must implement"
  207. def _format_text(self, text):
  208. """
  209. Format a paragraph of free-form text for inclusion in the
  210. help output at the current indentation level.
  211. """
  212. text_width = self.width - self.current_indent
  213. indent = " "*self.current_indent
  214. return textwrap.fill(text,
  215. text_width,
  216. initial_indent=indent,
  217. subsequent_indent=indent)
  218. def format_description(self, description):
  219. if description:
  220. return self._format_text(description) + "\n"
  221. else:
  222. return ""
  223. def format_epilog(self, epilog):
  224. if epilog:
  225. return "\n" + self._format_text(epilog) + "\n"
  226. else:
  227. return ""
  228. def expand_default(self, option):
  229. if self.parser is None or not self.default_tag:
  230. return option.help
  231. default_value = self.parser.defaults.get(option.dest)
  232. if default_value is NO_DEFAULT or default_value is None:
  233. default_value = self.NO_DEFAULT_VALUE
  234. return option.help.replace(self.default_tag, str(default_value))
  235. def format_option(self, option):
  236. # The help for each option consists of two parts:
  237. # * the opt strings and metavars
  238. # eg. ("-x", or "-fFILENAME, --file=FILENAME")
  239. # * the user-supplied help string
  240. # eg. ("turn on expert mode", "read data from FILENAME")
  241. #
  242. # If possible, we write both of these on the same line:
  243. # -x turn on expert mode
  244. #
  245. # But if the opt string list is too long, we put the help
  246. # string on a second line, indented to the same column it would
  247. # start in if it fit on the first line.
  248. # -fFILENAME, --file=FILENAME
  249. # read data from FILENAME
  250. result = []
  251. opts = self.option_strings[option]
  252. opt_width = self.help_position - self.current_indent - 2
  253. if len(opts) > opt_width:
  254. opts = "%*s%s\n" % (self.current_indent, "", opts)
  255. indent_first = self.help_position
  256. else: # start help on same line as opts
  257. opts = "%*s%-*s " % (self.current_indent, "", opt_width, opts)
  258. indent_first = 0
  259. result.append(opts)
  260. if option.help:
  261. help_text = self.expand_default(option)
  262. help_lines = textwrap.wrap(help_text, self.help_width)
  263. result.append("%*s%s\n" % (indent_first, "", help_lines[0]))
  264. result.extend(["%*s%s\n" % (self.help_position, "", line)
  265. for line in help_lines[1:]])
  266. elif opts[-1] != "\n":
  267. result.append("\n")
  268. return "".join(result)
  269. def store_option_strings(self, parser):
  270. self.indent()
  271. max_len = 0
  272. for opt in parser.option_list:
  273. strings = self.format_option_strings(opt)
  274. self.option_strings[opt] = strings
  275. max_len = max(max_len, len(strings) + self.current_indent)
  276. self.indent()
  277. for group in parser.option_groups:
  278. for opt in group.option_list:
  279. strings = self.format_option_strings(opt)
  280. self.option_strings[opt] = strings
  281. max_len = max(max_len, len(strings) + self.current_indent)
  282. self.dedent()
  283. self.dedent()
  284. self.help_position = min(max_len + 2, self.max_help_position)
  285. self.help_width = self.width - self.help_position
  286. def format_option_strings(self, option):
  287. """Return a comma-separated list of option strings & metavariables."""
  288. if option.takes_value():
  289. metavar = option.metavar or option.dest.upper()
  290. short_opts = [self._short_opt_fmt % (sopt, metavar)
  291. for sopt in option._short_opts]
  292. long_opts = [self._long_opt_fmt % (lopt, metavar)
  293. for lopt in option._long_opts]
  294. else:
  295. short_opts = option._short_opts
  296. long_opts = option._long_opts
  297. if self.short_first:
  298. opts = short_opts + long_opts
  299. else:
  300. opts = long_opts + short_opts
  301. return ", ".join(opts)
  302. class IndentedHelpFormatter (HelpFormatter):
  303. """Format help with indented section bodies.
  304. """
  305. def __init__(self,
  306. indent_increment=2,
  307. max_help_position=24,
  308. width=None,
  309. short_first=1):
  310. HelpFormatter.__init__(
  311. self, indent_increment, max_help_position, width, short_first)
  312. def format_usage(self, usage):
  313. return _("Usage: %s\n") % usage
  314. def format_heading(self, heading):
  315. return "%*s%s:\n" % (self.current_indent, "", heading)
  316. class TitledHelpFormatter (HelpFormatter):
  317. """Format help with underlined section headers.
  318. """
  319. def __init__(self,
  320. indent_increment=0,
  321. max_help_position=24,
  322. width=None,
  323. short_first=0):
  324. HelpFormatter.__init__ (
  325. self, indent_increment, max_help_position, width, short_first)
  326. def format_usage(self, usage):
  327. return "%s %s\n" % (self.format_heading(_("Usage")), usage)
  328. def format_heading(self, heading):
  329. return "%s\n%s\n" % (heading, "=-"[self.level] * len(heading))
  330. def _parse_num(val, type):
  331. if val[:2].lower() == "0x": # hexadecimal
  332. radix = 16
  333. elif val[:2].lower() == "0b": # binary
  334. radix = 2
  335. val = val[2:] or "0" # have to remove "0b" prefix
  336. elif val[:1] == "0": # octal
  337. radix = 8
  338. else: # decimal
  339. radix = 10
  340. return type(val, radix)
  341. def _parse_int(val):
  342. return _parse_num(val, int)
  343. def _parse_long(val):
  344. return _parse_num(val, long)
  345. _builtin_cvt = { "int" : (_parse_int, _("integer")),
  346. "long" : (_parse_long, _("long integer")),
  347. "float" : (float, _("floating-point")),
  348. "complex" : (complex, _("complex")) }
  349. def check_builtin(option, opt, value):
  350. (cvt, what) = _builtin_cvt[option.type]
  351. try:
  352. return cvt(value)
  353. except ValueError:
  354. raise OptionValueError(
  355. _("option %s: invalid %s value: %r") % (opt, what, value))
  356. def check_choice(option, opt, value):
  357. if value in option.choices:
  358. return value
  359. else:
  360. choices = ", ".join(map(repr, option.choices))
  361. raise OptionValueError(
  362. _("option %s: invalid choice: %r (choose from %s)")
  363. % (opt, value, choices))
  364. # Not supplying a default is different from a default of None,
  365. # so we need an explicit "not supplied" value.
  366. NO_DEFAULT = ("NO", "DEFAULT")
  367. class Option:
  368. """
  369. Instance attributes:
  370. _short_opts : [string]
  371. _long_opts : [string]
  372. action : string
  373. type : string
  374. dest : string
  375. default : any
  376. nargs : int
  377. const : any
  378. choices : [string]
  379. callback : function
  380. callback_args : (any*)
  381. callback_kwargs : { string : any }
  382. help : string
  383. metavar : string
  384. """
  385. # The list of instance attributes that may be set through
  386. # keyword args to the constructor.
  387. ATTRS = ['action',
  388. 'type',
  389. 'dest',
  390. 'default',
  391. 'nargs',
  392. 'const',
  393. 'choices',
  394. 'callback',
  395. 'callback_args',
  396. 'callback_kwargs',
  397. 'help',
  398. 'metavar']
  399. # The set of actions allowed by option parsers. Explicitly listed
  400. # here so the constructor can validate its arguments.
  401. ACTIONS = ("store",
  402. "store_const",
  403. "store_true",
  404. "store_false",
  405. "append",
  406. "append_const",
  407. "count",
  408. "callback",
  409. "help",
  410. "version")
  411. # The set of actions that involve storing a value somewhere;
  412. # also listed just for constructor argument validation. (If
  413. # the action is one of these, there must be a destination.)
  414. STORE_ACTIONS = ("store",
  415. "store_const",
  416. "store_true",
  417. "store_false",
  418. "append",
  419. "append_const",
  420. "count")
  421. # The set of actions for which it makes sense to supply a value
  422. # type, ie. which may consume an argument from the command line.
  423. TYPED_ACTIONS = ("store",
  424. "append",
  425. "callback")
  426. # The set of actions which *require* a value type, ie. that
  427. # always consume an argument from the command line.
  428. ALWAYS_TYPED_ACTIONS = ("store",
  429. "append")
  430. # The set of actions which take a 'const' attribute.
  431. CONST_ACTIONS = ("store_const",
  432. "append_const")
  433. # The set of known types for option parsers. Again, listed here for
  434. # constructor argument validation.
  435. TYPES = ("string", "int", "long", "float", "complex", "choice")
  436. # Dictionary of argument checking functions, which convert and
  437. # validate option arguments according to the option type.
  438. #
  439. # Signature of checking functions is:
  440. # check(option : Option, opt : string, value : string) -> any
  441. # where
  442. # option is the Option instance calling the checker
  443. # opt is the actual option seen on the command-line
  444. # (eg. "-a", "--file")
  445. # value is the option argument seen on the command-line
  446. #
  447. # The return value should be in the appropriate Python type
  448. # for option.type -- eg. an integer if option.type == "int".
  449. #
  450. # If no checker is defined for a type, arguments will be
  451. # unchecked and remain strings.
  452. TYPE_CHECKER = { "int" : check_builtin,
  453. "long" : check_builtin,
  454. "float" : check_builtin,
  455. "complex": check_builtin,
  456. "choice" : check_choice,
  457. }
  458. # CHECK_METHODS is a list of unbound method objects; they are called
  459. # by the constructor, in order, after all attributes are
  460. # initialized. The list is created and filled in later, after all
  461. # the methods are actually defined. (I just put it here because I
  462. # like to define and document all class attributes in the same
  463. # place.) Subclasses that add another _check_*() method should
  464. # define their own CHECK_METHODS list that adds their check method
  465. # to those from this class.
  466. CHECK_METHODS = None
  467. # -- Constructor/initialization methods ----------------------------
  468. def __init__(self, *opts, **attrs):
  469. # Set _short_opts, _long_opts attrs from 'opts' tuple.
  470. # Have to be set now, in case no option strings are supplied.
  471. self._short_opts = []
  472. self._long_opts = []
  473. opts = self._check_opt_strings(opts)
  474. self._set_opt_strings(opts)
  475. # Set all other attrs (action, type, etc.) from 'attrs' dict
  476. self._set_attrs(attrs)
  477. # Check all the attributes we just set. There are lots of
  478. # complicated interdependencies, but luckily they can be farmed
  479. # out to the _check_*() methods listed in CHECK_METHODS -- which
  480. # could be handy for subclasses! The one thing these all share
  481. # is that they raise OptionError if they discover a problem.
  482. for checker in self.CHECK_METHODS:
  483. checker(self)
  484. def _check_opt_strings(self, opts):
  485. # Filter out None because early versions of Optik had exactly
  486. # one short option and one long option, either of which
  487. # could be None.
  488. opts = filter(None, opts)
  489. if not opts:
  490. raise TypeError("at least one option string must be supplied")
  491. return opts
  492. def _set_opt_strings(self, opts):
  493. for opt in opts:
  494. if len(opt) < 2:
  495. raise OptionError(
  496. "invalid option string %r: "
  497. "must be at least two characters long" % opt, self)
  498. elif len(opt) == 2:
  499. if not (opt[0] == "-" and opt[1] != "-"):
  500. raise OptionError(
  501. "invalid short option string %r: "
  502. "must be of the form -x, (x any non-dash char)" % opt,
  503. self)
  504. self._short_opts.append(opt)
  505. else:
  506. if not (opt[0:2] == "--" and opt[2] != "-"):
  507. raise OptionError(
  508. "invalid long option string %r: "
  509. "must start with --, followed by non-dash" % opt,
  510. self)
  511. self._long_opts.append(opt)
  512. def _set_attrs(self, attrs):
  513. for attr in self.ATTRS:
  514. if attr in attrs:
  515. setattr(self, attr, attrs[attr])
  516. del attrs[attr]
  517. else:
  518. if attr == 'default':
  519. setattr(self, attr, NO_DEFAULT)
  520. else:
  521. setattr(self, attr, None)
  522. if attrs:
  523. attrs = attrs.keys()
  524. attrs.sort()
  525. raise OptionError(
  526. "invalid keyword arguments: %s" % ", ".join(attrs),
  527. self)
  528. # -- Constructor validation methods --------------------------------
  529. def _check_action(self):
  530. if self.action is None:
  531. self.action = "store"
  532. elif self.action not in self.ACTIONS:
  533. raise OptionError("invalid action: %r" % self.action, self)
  534. def _check_type(self):
  535. if self.type is None:
  536. if self.action in self.ALWAYS_TYPED_ACTIONS:
  537. if self.choices is not None:
  538. # The "choices" attribute implies "choice" type.
  539. self.type = "choice"
  540. else:
  541. # No type given? "string" is the most sensible default.
  542. self.type = "string"
  543. else:
  544. # Allow type objects or builtin type conversion functions
  545. # (int, str, etc.) as an alternative to their names. (The
  546. # complicated check of __builtin__ is only necessary for
  547. # Python 2.1 and earlier, and is short-circuited by the
  548. # first check on modern Pythons.)
  549. import __builtin__
  550. if ( type(self.type) is types.TypeType or
  551. (hasattr(self.type, "__name__") and
  552. getattr(__builtin__, self.type.__name__, None) is self.type) ):
  553. self.type = self.type.__name__
  554. if self.type == "str":
  555. self.type = "string"
  556. if self.type not in self.TYPES:
  557. raise OptionError("invalid option type: %r" % self.type, self)
  558. if self.action not in self.TYPED_ACTIONS:
  559. raise OptionError(
  560. "must not supply a type for action %r" % self.action, self)
  561. def _check_choice(self):
  562. if self.type == "choice":
  563. if self.choices is None:
  564. raise OptionError(
  565. "must supply a list of choices for type 'choice'", self)
  566. elif type(self.choices) not in (types.TupleType, types.ListType):
  567. raise OptionError(
  568. "choices must be a list of strings ('%s' supplied)"
  569. % str(type(self.choices)).split("'")[1], self)
  570. elif self.choices is not None:
  571. raise OptionError(
  572. "must not supply choices for type %r" % self.type, self)
  573. def _check_dest(self):
  574. # No destination given, and we need one for this action. The
  575. # self.type check is for callbacks that take a value.
  576. takes_value = (self.action in self.STORE_ACTIONS or
  577. self.type is not None)
  578. if self.dest is None and takes_value:
  579. # Glean a destination from the first long option string,
  580. # or from the first short option string if no long options.
  581. if self._long_opts:
  582. # eg. "--foo-bar" -> "foo_bar"
  583. self.dest = self._long_opts[0][2:].replace('-', '_')
  584. else:
  585. self.dest = self._short_opts[0][1]
  586. def _check_const(self):
  587. if self.action not in self.CONST_ACTIONS and self.const is not None:
  588. raise OptionError(
  589. "'const' must not be supplied for action %r" % self.action,
  590. self)
  591. def _check_nargs(self):
  592. if self.action in self.TYPED_ACTIONS:
  593. if self.nargs is None:
  594. self.nargs = 1
  595. elif self.nargs is not None:
  596. raise OptionError(
  597. "'nargs' must not be supplied for action %r" % self.action,
  598. self)
  599. def _check_callback(self):
  600. if self.action == "callback":
  601. if not hasattr(self.callback, '__call__'):
  602. raise OptionError(
  603. "callback not callable: %r" % self.callback, self)
  604. if (self.callback_args is not None and
  605. type(self.callback_args) is not types.TupleType):
  606. raise OptionError(
  607. "callback_args, if supplied, must be a tuple: not %r"
  608. % self.callback_args, self)
  609. if (self.callback_kwargs is not None and
  610. type(self.callback_kwargs) is not types.DictType):
  611. raise OptionError(
  612. "callback_kwargs, if supplied, must be a dict: not %r"
  613. % self.callback_kwargs, self)
  614. else:
  615. if self.callback is not None:
  616. raise OptionError(
  617. "callback supplied (%r) for non-callback option"
  618. % self.callback, self)
  619. if self.callback_args is not None:
  620. raise OptionError(
  621. "callback_args supplied for non-callback option", self)
  622. if self.callback_kwargs is not None:
  623. raise OptionError(
  624. "callback_kwargs supplied for non-callback option", self)
  625. CHECK_METHODS = [_check_action,
  626. _check_type,
  627. _check_choice,
  628. _check_dest,
  629. _check_const,
  630. _check_nargs,
  631. _check_callback]
  632. # -- Miscellaneous methods -----------------------------------------
  633. def __str__(self):
  634. return "/".join(self._short_opts + self._long_opts)
  635. __repr__ = _repr
  636. def takes_value(self):
  637. return self.type is not None
  638. def get_opt_string(self):
  639. if self._long_opts:
  640. return self._long_opts[0]
  641. else:
  642. return self._short_opts[0]
  643. # -- Processing methods --------------------------------------------
  644. def check_value(self, opt, value):
  645. checker = self.TYPE_CHECKER.get(self.type)
  646. if checker is None:
  647. return value
  648. else:
  649. return checker(self, opt, value)
  650. def convert_value(self, opt, value):
  651. if value is not None:
  652. if self.nargs == 1:
  653. return self.check_value(opt, value)
  654. else:
  655. return tuple([self.check_value(opt, v) for v in value])
  656. def process(self, opt, value, values, parser):
  657. # First, convert the value(s) to the right type. Howl if any
  658. # value(s) are bogus.
  659. value = self.convert_value(opt, value)
  660. # And then take whatever action is expected of us.
  661. # This is a separate method to make life easier for
  662. # subclasses to add new actions.
  663. return self.take_action(
  664. self.action, self.dest, opt, value, values, parser)
  665. def take_action(self, action, dest, opt, value, values, parser):
  666. if action == "store":
  667. setattr(values, dest, value)
  668. elif action == "store_const":
  669. setattr(values, dest, self.const)
  670. elif action == "store_true":
  671. setattr(values, dest, True)
  672. elif action == "store_false":
  673. setattr(values, dest, False)
  674. elif action == "append":
  675. values.ensure_value(dest, []).append(value)
  676. elif action == "append_const":
  677. values.ensure_value(dest, []).append(self.const)
  678. elif action == "count":
  679. setattr(values, dest, values.ensure_value(dest, 0) + 1)
  680. elif action == "callback":
  681. args = self.callback_args or ()
  682. kwargs = self.callback_kwargs or {}
  683. self.callback(self, opt, value, parser, *args, **kwargs)
  684. elif action == "help":
  685. parser.print_help()
  686. parser.exit()
  687. elif action == "version":
  688. parser.print_version()
  689. parser.exit()
  690. else:
  691. raise ValueError("unknown action %r" % self.action)
  692. return 1
  693. # class Option
  694. SUPPRESS_HELP = "SUPPRESS"+"HELP"
  695. SUPPRESS_USAGE = "SUPPRESS"+"USAGE"
  696. try:
  697. basestring
  698. except NameError:
  699. def isbasestring(x):
  700. return isinstance(x, (types.StringType, types.UnicodeType))
  701. else:
  702. def isbasestring(x):
  703. return isinstance(x, basestring)
  704. class Values:
  705. def __init__(self, defaults=None):
  706. if defaults:
  707. for (attr, val) in defaults.items():
  708. setattr(self, attr, val)
  709. def __str__(self):
  710. return str(self.__dict__)
  711. __repr__ = _repr
  712. def __cmp__(self, other):
  713. if isinstance(other, Values):
  714. return cmp(self.__dict__, other.__dict__)
  715. elif isinstance(other, types.DictType):
  716. return cmp(self.__dict__, other)
  717. else:
  718. return -1
  719. def _update_careful(self, dict):
  720. """
  721. Update the option values from an arbitrary dictionary, but only
  722. use keys from dict that already have a corresponding attribute
  723. in self. Any keys in dict without a corresponding attribute
  724. are silently ignored.
  725. """
  726. for attr in dir(self):
  727. if attr in dict:
  728. dval = dict[attr]
  729. if dval is not None:
  730. setattr(self, attr, dval)
  731. def _update_loose(self, dict):
  732. """
  733. Update the option values from an arbitrary dictionary,
  734. using all keys from the dictionary regardless of whether
  735. they have a corresponding attribute in self or not.
  736. """
  737. self.__dict__.update(dict)
  738. def _update(self, dict, mode):
  739. if mode == "careful":
  740. self._update_careful(dict)
  741. elif mode == "loose":
  742. self._update_loose(dict)
  743. else:
  744. raise ValueError, "invalid update mode: %r" % mode
  745. def read_module(self, modname, mode="careful"):
  746. __import__(modname)
  747. mod = sys.modules[modname]
  748. self._update(vars(mod), mode)
  749. def read_file(self, filename, mode="careful"):
  750. vars = {}
  751. execfile(filename, vars)
  752. self._update(vars, mode)
  753. def ensure_value(self, attr, value):
  754. if not hasattr(self, attr) or getattr(self, attr) is None:
  755. setattr(self, attr, value)
  756. return getattr(self, attr)
  757. class OptionContainer:
  758. """
  759. Abstract base class.
  760. Class attributes:
  761. standard_option_list : [Option]
  762. list of standard options that will be accepted by all instances
  763. of this parser class (intended to be overridden by subclasses).
  764. Instance attributes:
  765. option_list : [Option]
  766. the list of Option objects contained by this OptionContainer
  767. _short_opt : { string : Option }
  768. dictionary mapping short option strings, eg. "-f" or "-X",
  769. to the Option instances that implement them. If an Option
  770. has multiple short option strings, it will appears in this
  771. dictionary multiple times. [1]
  772. _long_opt : { string : Option }
  773. dictionary mapping long option strings, eg. "--file" or
  774. "--exclude", to the Option instances that implement them.
  775. Again, a given Option can occur multiple times in this
  776. dictionary. [1]
  777. defaults : { string : any }
  778. dictionary mapping option destination names to default
  779. values for each destination [1]
  780. [1] These mappings are common to (shared by) all components of the
  781. controlling OptionParser, where they are initially created.
  782. """
  783. def __init__(self, option_class, conflict_handler, description):
  784. # Initialize the option list and related data structures.
  785. # This method must be provided by subclasses, and it must
  786. # initialize at least the following instance attributes:
  787. # option_list, _short_opt, _long_opt, defaults.
  788. self._create_option_list()
  789. self.option_class = option_class
  790. self.set_conflict_handler(conflict_handler)
  791. self.set_description(description)
  792. def _create_option_mappings(self):
  793. # For use by OptionParser constructor -- create the master
  794. # option mappings used by this OptionParser and all
  795. # OptionGroups that it owns.
  796. self._short_opt = {} # single letter -> Option instance
  797. self._long_opt = {} # long option -> Option instance
  798. self.defaults = {} # maps option dest -> default value
  799. def _share_option_mappings(self, parser):
  800. # For use by OptionGroup constructor -- use shared option
  801. # mappings from the OptionParser that owns this OptionGroup.
  802. self._short_opt = parser._short_opt
  803. self._long_opt = parser._long_opt
  804. self.defaults = parser.defaults
  805. def set_conflict_handler(self, handler):
  806. if handler not in ("error", "resolve"):
  807. raise ValueError, "invalid conflict_resolution value %r" % handler
  808. self.conflict_handler = handler
  809. def set_description(self, description):
  810. self.description = description
  811. def get_description(self):
  812. return self.description
  813. def destroy(self):
  814. """see OptionParser.destroy()."""
  815. del self._short_opt
  816. del self._long_opt
  817. del self.defaults
  818. # -- Option-adding methods -----------------------------------------
  819. def _check_conflict(self, option):
  820. conflict_opts = []
  821. for opt in option._short_opts:
  822. if opt in self._short_opt:
  823. conflict_opts.append((opt, self._short_opt[opt]))
  824. for opt in option._long_opts:
  825. if opt in self._long_opt:
  826. conflict_opts.append((opt, self._long_opt[opt]))
  827. if conflict_opts:
  828. handler = self.conflict_handler
  829. if handler == "error":
  830. raise OptionConflictError(
  831. "conflicting option string(s): %s"
  832. % ", ".join([co[0] for co in conflict_opts]),
  833. option)
  834. elif handler == "resolve":
  835. for (opt, c_option) in conflict_opts:
  836. if opt.startswith("--"):
  837. c_option._long_opts.remove(opt)
  838. del self._long_opt[opt]
  839. else:
  840. c_option._short_opts.remove(opt)
  841. del self._short_opt[opt]
  842. if not (c_option._short_opts or c_option._long_opts):
  843. c_option.container.option_list.remove(c_option)
  844. def add_option(self, *args, **kwargs):
  845. """add_option(Option)
  846. add_option(opt_str, ..., kwarg=val, ...)
  847. """
  848. if type(args[0]) in types.StringTypes:
  849. option = self.option_class(*args, **kwargs)
  850. elif len(args) == 1 and not kwargs:
  851. option = args[0]
  852. if not isinstance(option, Option):
  853. raise TypeError, "not an Option instance: %r" % option
  854. else:
  855. raise TypeError, "invalid arguments"
  856. self._check_conflict(option)
  857. self.option_list.append(option)
  858. option.container = self
  859. for opt in option._short_opts:
  860. self._short_opt[opt] = option
  861. for opt in option._long_opts:
  862. self._long_opt[opt] = option
  863. if option.dest is not None: # option has a dest, we need a default
  864. if option.default is not NO_DEFAULT:
  865. self.defaults[option.dest] = option.default
  866. elif option.dest not in self.defaults:
  867. self.defaults[option.dest] = None
  868. return option
  869. def add_options(self, option_list):
  870. for option in option_list:
  871. self.add_option(option)
  872. # -- Option query/removal methods ----------------------------------
  873. def get_option(self, opt_str):
  874. return (self._short_opt.get(opt_str) or
  875. self._long_opt.get(opt_str))
  876. def has_option(self, opt_str):
  877. return (opt_str in self._short_opt or
  878. opt_str in self._long_opt)
  879. def remove_option(self, opt_str):
  880. option = self._short_opt.get(opt_str)
  881. if option is None:
  882. option = self._long_opt.get(opt_str)
  883. if option is None:
  884. raise ValueError("no such option %r" % opt_str)
  885. for opt in option._short_opts:
  886. del self._short_opt[opt]
  887. for opt in option._long_opts:
  888. del self._long_opt[opt]
  889. option.container.option_list.remove(option)
  890. # -- Help-formatting methods ---------------------------------------
  891. def format_option_help(self, formatter):
  892. if not self.option_list:
  893. return ""
  894. result = []
  895. for option in self.option_list:
  896. if not option.help is SUPPRESS_HELP:
  897. result.append(formatter.format_option(option))
  898. return "".join(result)
  899. def format_description(self, formatter):
  900. return formatter.format_description(self.get_description())
  901. def format_help(self, formatter):
  902. result = []
  903. if self.description:
  904. result.append(self.format_description(formatter))
  905. if self.option_list:
  906. result.append(self.format_option_help(formatter))
  907. return "\n".join(result)
  908. class OptionGroup (OptionContainer):
  909. def __init__(self, parser, title, description=None):
  910. self.parser = parser
  911. OptionContainer.__init__(
  912. self, parser.option_class, parser.conflict_handler, description)
  913. self.title = title
  914. def _create_option_list(self):
  915. self.option_list = []
  916. self._share_option_mappings(self.parser)
  917. def set_title(self, title):
  918. self.title = title
  919. def destroy(self):
  920. """see OptionParser.destroy()."""
  921. OptionContainer.destroy(self)
  922. del self.option_list
  923. # -- Help-formatting methods ---------------------------------------
  924. def format_help(self, formatter):
  925. result = formatter.format_heading(self.title)
  926. formatter.indent()
  927. result += OptionContainer.format_help(self, formatter)
  928. formatter.dedent()
  929. return result
  930. class OptionParser (OptionContainer):
  931. """
  932. Class attributes:
  933. standard_option_list : [Option]
  934. list of standard options that will be accepted by all instances
  935. of this parser class (intended to be overridden by subclasses).
  936. Instance attributes:
  937. usage : string
  938. a usage string for your program. Before it is displayed
  939. to the user, "%prog" will be expanded to the name of
  940. your program (self.prog or os.path.basename(sys.argv[0])).
  941. prog : string
  942. the name of the current program (to override
  943. os.path.basename(sys.argv[0])).
  944. description : string
  945. A paragraph of text giving a brief overview of your program.
  946. optparse reformats this paragraph to fit the current terminal
  947. width and prints it when the user requests help (after usage,
  948. but before the list of options).
  949. epilog : string
  950. paragraph of help text to print after option help
  951. option_groups : [OptionGroup]
  952. list of option groups in this parser (option groups are
  953. irrelevant for parsing the command-line, but very useful
  954. for generating help)
  955. allow_interspersed_args : bool = true
  956. if true, positional arguments may be interspersed with options.
  957. Assuming -a and -b each take a single argument, the command-line
  958. -ablah foo bar -bboo baz
  959. will be interpreted the same as
  960. -ablah -bboo -- foo bar baz
  961. If this flag were false, that command line would be interpreted as
  962. -ablah -- foo bar -bboo baz
  963. -- ie. we stop processing options as soon as we see the first
  964. non-option argument. (This is the tradition followed by
  965. Python's getopt module, Perl's Getopt::Std, and other argument-
  966. parsing libraries, but it is generally annoying to users.)
  967. process_default_values : bool = true
  968. if true, option default values are processed similarly to option
  969. values from the command line: that is, they are passed to the
  970. type-checking function for the option's type (as long as the
  971. default value is a string). (This really only matters if you
  972. have defined custom types; see SF bug #955889.) Set it to false
  973. to restore the behaviour of Optik 1.4.1 and earlier.
  974. rargs : [string]
  975. the argument list currently being parsed. Only set when
  976. parse_args() is active, and continually trimmed down as
  977. we consume arguments. Mainly there for the benefit of
  978. callback options.
  979. largs : [string]
  980. the list of leftover arguments that we have skipped while
  981. parsing options. If allow_interspersed_args is false, this
  982. list is always empty.
  983. values : Values
  984. the set of option values currently being accumulated. Only
  985. set when parse_args() is active. Also mainly for callbacks.
  986. Because of the 'rargs', 'largs', and 'values' attributes,
  987. OptionParser is not thread-safe. If, for some perverse reason, you
  988. need to parse command-line arguments simultaneously in different
  989. threads, use different OptionParser instances.
  990. """
  991. standard_option_list = []
  992. def __init__(self,
  993. usage=None,
  994. option_list=None,
  995. option_class=Option,
  996. version=None,
  997. conflict_handler="error",
  998. description=None,
  999. formatter=None,
  1000. add_help_option=True,
  1001. prog=None,
  1002. epilog=None):
  1003. OptionContainer.__init__(
  1004. self, option_class, conflict_handler, description)
  1005. self.set_usage(usage)
  1006. self.prog = prog
  1007. self.version = version
  1008. self.allow_interspersed_args = True
  1009. self.process_default_values = True
  1010. if formatter is None:
  1011. formatter = IndentedHelpFormatter()
  1012. self.formatter = formatter
  1013. self.formatter.set_parser(self)
  1014. self.epilog = epilog
  1015. # Populate the option list; initial sources are the
  1016. # standard_option_list class attribute, the 'option_list'
  1017. # argument, and (if applicable) the _add_version_option() and
  1018. # _add_help_option() methods.
  1019. self._populate_option_list(option_list,
  1020. add_help=add_help_option)
  1021. self._init_parsing_state()
  1022. def destroy(self):
  1023. """
  1024. Declare that you are done with this OptionParser. This cleans up
  1025. reference cycles so the OptionParser (and all objects referenced by
  1026. it) can be garbage-collected promptly. After calling destroy(), the
  1027. OptionParser is unusable.
  1028. """
  1029. OptionContainer.destroy(self)
  1030. for group in self.option_groups:
  1031. group.destroy()
  1032. del self.option_list
  1033. del self.option_groups
  1034. del self.formatter
  1035. # -- Private methods -----------------------------------------------
  1036. # (used by our or OptionContainer's constructor)
  1037. def _create_option_list(self):
  1038. self.option_list = []
  1039. self.option_groups = []
  1040. self._create_option_mappings()
  1041. def _add_help_option(self):
  1042. self.add_option("-h", "--help",
  1043. action="help",
  1044. help=_("show this help message and exit"))
  1045. def _add_version_option(self):
  1046. self.add_option("--version",
  1047. action="version",
  1048. help=_("show program's version number and exit"))
  1049. def _populate_option_list(self, option_list, add_help=True):
  1050. if self.standard_option_list:
  1051. self.add_options(self.standard_option_list)
  1052. if option_list:
  1053. self.add_options(option_list)
  1054. if self.version:
  1055. self._add_version_option()
  1056. if add_help:
  1057. self._add_help_option()
  1058. def _init_parsing_state(self):
  1059. # These are set in parse_args() for the convenience of callbacks.
  1060. self.rargs = None
  1061. self.largs = None
  1062. self.values = None
  1063. # -- Simple modifier methods ---------------------------------------
  1064. def set_usage(self, usage):
  1065. if usage is None:
  1066. self.usage = _("%prog [options]")
  1067. elif usage is SUPPRESS_USAGE:
  1068. self.usage = None
  1069. # For backwards compatibility with Optik 1.3 and earlier.
  1070. elif usage.lower().startswith("usage: "):
  1071. self.usage = usage[7:]
  1072. else:
  1073. self.usage = usage
  1074. def enable_interspersed_args(self):
  1075. """Set parsing to not stop on the first non-option, allowing
  1076. interspersing switches with command arguments. This is the
  1077. default behavior. See also disable_interspersed_args() and the
  1078. class documentation description of the attribute
  1079. allow_interspersed_args."""
  1080. self.allow_interspersed_args = True
  1081. def disable_interspersed_args(self):
  1082. """Set parsing to stop on the first non-option. Use this if
  1083. you have a command processor which runs another command that
  1084. has options of its own and you want to make sure these options
  1085. don't get confused.
  1086. """
  1087. self.allow_interspersed_args = False
  1088. def set_process_default_values(self, process):
  1089. self.process_default_values = process
  1090. def set_default(self, dest, value):
  1091. self.defaults[dest] = value
  1092. def set_defaults(self, **kwargs):
  1093. self.defaults.update(kwargs)
  1094. def _get_all_options(self):
  1095. options = self.option_list[:]
  1096. for group in self.option_groups:
  1097. options.extend(group.option_list)
  1098. return options
  1099. def get_default_values(self):
  1100. if not self.process_default_values:
  1101. # Old, pre-Optik 1.5 behaviour.
  1102. return Values(self.defaults)
  1103. defaults = self.defaults.copy()
  1104. for option in self._get_all_options():
  1105. default = defaults.get(option.dest)
  1106. if isbasestring(default):
  1107. opt_str = option.get_opt_string()
  1108. defaults[option.dest] = option.check_value(opt_str, default)
  1109. return Values(defaults)
  1110. # -- OptionGroup methods -------------------------------------------
  1111. def add_option_group(self, *args, **kwargs):
  1112. # XXX lots of overlap with OptionContainer.add_option()
  1113. if type(args[0]) is types.StringType:
  1114. group = OptionGroup(self, *args, **kwargs)
  1115. elif len(args) == 1 and not kwargs:
  1116. group = args[0]
  1117. if not isinstance(group, OptionGroup):
  1118. raise TypeError, "not an OptionGroup instance: %r" % group
  1119. if group.parser is not self:
  1120. raise ValueError, "invalid OptionGroup (wrong parser)"
  1121. else:
  1122. raise TypeError, "invalid arguments"
  1123. self.option_groups.append(group)
  1124. return group
  1125. def get_option_group(self, opt_str):
  1126. option = (self._short_opt.get(opt_str) or
  1127. self._long_opt.get(opt_str))
  1128. if option and option.container is not self:
  1129. return option.container
  1130. return None
  1131. # -- Option-parsing methods ----------------------------------------
  1132. def _get_args(self, args):
  1133. if args is None:
  1134. return sys.argv[1:]
  1135. else:
  1136. return args[:] # don't modify caller's list
  1137. def parse_args(self, args=None, values=None):
  1138. """
  1139. parse_args(args : [string] = sys.argv[1:],
  1140. values : Values = None)
  1141. -> (values : Values, args : [string])
  1142. Parse the command-line options found in 'args' (default:
  1143. sys.argv[1:]). Any errors result in a call to 'error()', which
  1144. by default prints the usage message to stderr and calls
  1145. sys.exit() with an error message. On success returns a pair
  1146. (values, args) where 'values' is an Values instance (with all
  1147. your option values) and 'args' is the list of arguments left
  1148. over after parsing options.
  1149. """
  1150. rargs = self._get_args(args)
  1151. if values is None:
  1152. values = self.get_default_values()
  1153. # Store the halves of the argument list as attributes for the
  1154. # convenience of callbacks:
  1155. # rargs
  1156. # the rest of the command-line (the "r" stands for
  1157. # "remaining" or "right-hand")
  1158. # largs
  1159. # the leftover arguments -- ie. what's left after removing
  1160. # options and their arguments (the "l" stands for "leftover"
  1161. # or "left-hand")
  1162. self.rargs = rargs
  1163. self.largs = largs = []

Large files files are truncated, but you can click here to view the full file