optparse.py 60 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704
  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. if width is None:
  169. try:
  170. width = int(os.environ['COLUMNS'])
  171. except (KeyError, ValueError):
  172. width = 80
  173. width -= 2
  174. self.width = width
  175. self.help_position = self.max_help_position = \
  176. min(max_help_position, max(width - 20, indent_increment * 2))
  177. self.current_indent = 0
  178. self.level = 0
  179. self.help_width = None # computed later
  180. self.short_first = short_first
  181. self.default_tag = "%default"
  182. self.option_strings = {}
  183. self._short_opt_fmt = "%s %s"
  184. self._long_opt_fmt = "%s=%s"
  185. def set_parser(self, parser):
  186. self.parser = parser
  187. def set_short_opt_delimiter(self, delim):
  188. if delim not in ("", " "):
  189. raise ValueError(
  190. "invalid metavar delimiter for short options: %r" % delim)
  191. self._short_opt_fmt = "%s" + delim + "%s"
  192. def set_long_opt_delimiter(self, delim):
  193. if delim not in ("=", " "):
  194. raise ValueError(
  195. "invalid metavar delimiter for long options: %r" % delim)
  196. self._long_opt_fmt = "%s" + delim + "%s"
  197. def indent(self):
  198. self.current_indent += self.indent_increment
  199. self.level += 1
  200. def dedent(self):
  201. self.current_indent -= self.indent_increment
  202. assert self.current_indent >= 0, "Indent decreased below 0."
  203. self.level -= 1
  204. def format_usage(self, usage):
  205. raise NotImplementedError, "subclasses must implement"
  206. def format_heading(self, heading):
  207. raise NotImplementedError, "subclasses must implement"
  208. def _format_text(self, text):
  209. """
  210. Format a paragraph of free-form text for inclusion in the
  211. help output at the current indentation level.
  212. """
  213. text_width = max(self.width - self.current_indent, 11)
  214. indent = " "*self.current_indent
  215. return textwrap.fill(text,
  216. text_width,
  217. initial_indent=indent,
  218. subsequent_indent=indent)
  219. def format_description(self, description):
  220. if description:
  221. return self._format_text(description) + "\n"
  222. else:
  223. return ""
  224. def format_epilog(self, epilog):
  225. if epilog:
  226. return "\n" + self._format_text(epilog) + "\n"
  227. else:
  228. return ""
  229. def expand_default(self, option):
  230. if self.parser is None or not self.default_tag:
  231. return option.help
  232. default_value = self.parser.defaults.get(option.dest)
  233. if default_value is NO_DEFAULT or default_value is None:
  234. default_value = self.NO_DEFAULT_VALUE
  235. return option.help.replace(self.default_tag, str(default_value))
  236. def format_option(self, option):
  237. # The help for each option consists of two parts:
  238. # * the opt strings and metavars
  239. # eg. ("-x", or "-fFILENAME, --file=FILENAME")
  240. # * the user-supplied help string
  241. # eg. ("turn on expert mode", "read data from FILENAME")
  242. #
  243. # If possible, we write both of these on the same line:
  244. # -x turn on expert mode
  245. #
  246. # But if the opt string list is too long, we put the help
  247. # string on a second line, indented to the same column it would
  248. # start in if it fit on the first line.
  249. # -fFILENAME, --file=FILENAME
  250. # read data from FILENAME
  251. result = []
  252. opts = self.option_strings[option]
  253. opt_width = self.help_position - self.current_indent - 2
  254. if len(opts) > opt_width:
  255. opts = "%*s%s\n" % (self.current_indent, "", opts)
  256. indent_first = self.help_position
  257. else: # start help on same line as opts
  258. opts = "%*s%-*s " % (self.current_indent, "", opt_width, opts)
  259. indent_first = 0
  260. result.append(opts)
  261. if option.help:
  262. help_text = self.expand_default(option)
  263. help_lines = textwrap.wrap(help_text, self.help_width)
  264. result.append("%*s%s\n" % (indent_first, "", help_lines[0]))
  265. result.extend(["%*s%s\n" % (self.help_position, "", line)
  266. for line in help_lines[1:]])
  267. elif opts[-1] != "\n":
  268. result.append("\n")
  269. return "".join(result)
  270. def store_option_strings(self, parser):
  271. self.indent()
  272. max_len = 0
  273. for opt in parser.option_list:
  274. strings = self.format_option_strings(opt)
  275. self.option_strings[opt] = strings
  276. max_len = max(max_len, len(strings) + self.current_indent)
  277. self.indent()
  278. for group in parser.option_groups:
  279. for opt in group.option_list:
  280. strings = self.format_option_strings(opt)
  281. self.option_strings[opt] = strings
  282. max_len = max(max_len, len(strings) + self.current_indent)
  283. self.dedent()
  284. self.dedent()
  285. self.help_position = min(max_len + 2, self.max_help_position)
  286. self.help_width = max(self.width - self.help_position, 11)
  287. def format_option_strings(self, option):
  288. """Return a comma-separated list of option strings & metavariables."""
  289. if option.takes_value():
  290. metavar = option.metavar or option.dest.upper()
  291. short_opts = [self._short_opt_fmt % (sopt, metavar)
  292. for sopt in option._short_opts]
  293. long_opts = [self._long_opt_fmt % (lopt, metavar)
  294. for lopt in option._long_opts]
  295. else:
  296. short_opts = option._short_opts
  297. long_opts = option._long_opts
  298. if self.short_first:
  299. opts = short_opts + long_opts
  300. else:
  301. opts = long_opts + short_opts
  302. return ", ".join(opts)
  303. class IndentedHelpFormatter (HelpFormatter):
  304. """Format help with indented section bodies.
  305. """
  306. def __init__(self,
  307. indent_increment=2,
  308. max_help_position=24,
  309. width=None,
  310. short_first=1):
  311. HelpFormatter.__init__(
  312. self, indent_increment, max_help_position, width, short_first)
  313. def format_usage(self, usage):
  314. return _("Usage: %s\n") % usage
  315. def format_heading(self, heading):
  316. return "%*s%s:\n" % (self.current_indent, "", heading)
  317. class TitledHelpFormatter (HelpFormatter):
  318. """Format help with underlined section headers.
  319. """
  320. def __init__(self,
  321. indent_increment=0,
  322. max_help_position=24,
  323. width=None,
  324. short_first=0):
  325. HelpFormatter.__init__ (
  326. self, indent_increment, max_help_position, width, short_first)
  327. def format_usage(self, usage):
  328. return "%s %s\n" % (self.format_heading(_("Usage")), usage)
  329. def format_heading(self, heading):
  330. return "%s\n%s\n" % (heading, "=-"[self.level] * len(heading))
  331. def _parse_num(val, type):
  332. if val[:2].lower() == "0x": # hexadecimal
  333. radix = 16
  334. elif val[:2].lower() == "0b": # binary
  335. radix = 2
  336. val = val[2:] or "0" # have to remove "0b" prefix
  337. elif val[:1] == "0": # octal
  338. radix = 8
  339. else: # decimal
  340. radix = 10
  341. return type(val, radix)
  342. def _parse_int(val):
  343. return _parse_num(val, int)
  344. def _parse_long(val):
  345. return _parse_num(val, long)
  346. _builtin_cvt = { "int" : (_parse_int, _("integer")),
  347. "long" : (_parse_long, _("long integer")),
  348. "float" : (float, _("floating-point")),
  349. "complex" : (complex, _("complex")) }
  350. def check_builtin(option, opt, value):
  351. (cvt, what) = _builtin_cvt[option.type]
  352. try:
  353. return cvt(value)
  354. except ValueError:
  355. raise OptionValueError(
  356. _("option %s: invalid %s value: %r") % (opt, what, value))
  357. def check_choice(option, opt, value):
  358. if value in option.choices:
  359. return value
  360. else:
  361. choices = ", ".join(map(repr, option.choices))
  362. raise OptionValueError(
  363. _("option %s: invalid choice: %r (choose from %s)")
  364. % (opt, value, choices))
  365. # Not supplying a default is different from a default of None,
  366. # so we need an explicit "not supplied" value.
  367. NO_DEFAULT = ("NO", "DEFAULT")
  368. class Option:
  369. """
  370. Instance attributes:
  371. _short_opts : [string]
  372. _long_opts : [string]
  373. action : string
  374. type : string
  375. dest : string
  376. default : any
  377. nargs : int
  378. const : any
  379. choices : [string]
  380. callback : function
  381. callback_args : (any*)
  382. callback_kwargs : { string : any }
  383. help : string
  384. metavar : string
  385. """
  386. # The list of instance attributes that may be set through
  387. # keyword args to the constructor.
  388. ATTRS = ['action',
  389. 'type',
  390. 'dest',
  391. 'default',
  392. 'nargs',
  393. 'const',
  394. 'choices',
  395. 'callback',
  396. 'callback_args',
  397. 'callback_kwargs',
  398. 'help',
  399. 'metavar']
  400. # The set of actions allowed by option parsers. Explicitly listed
  401. # here so the constructor can validate its arguments.
  402. ACTIONS = ("store",
  403. "store_const",
  404. "store_true",
  405. "store_false",
  406. "append",
  407. "append_const",
  408. "count",
  409. "callback",
  410. "help",
  411. "version")
  412. # The set of actions that involve storing a value somewhere;
  413. # also listed just for constructor argument validation. (If
  414. # the action is one of these, there must be a destination.)
  415. STORE_ACTIONS = ("store",
  416. "store_const",
  417. "store_true",
  418. "store_false",
  419. "append",
  420. "append_const",
  421. "count")
  422. # The set of actions for which it makes sense to supply a value
  423. # type, ie. which may consume an argument from the command line.
  424. TYPED_ACTIONS = ("store",
  425. "append",
  426. "callback")
  427. # The set of actions which *require* a value type, ie. that
  428. # always consume an argument from the command line.
  429. ALWAYS_TYPED_ACTIONS = ("store",
  430. "append")
  431. # The set of actions which take a 'const' attribute.
  432. CONST_ACTIONS = ("store_const",
  433. "append_const")
  434. # The set of known types for option parsers. Again, listed here for
  435. # constructor argument validation.
  436. TYPES = ("string", "int", "long", "float", "complex", "choice")
  437. # Dictionary of argument checking functions, which convert and
  438. # validate option arguments according to the option type.
  439. #
  440. # Signature of checking functions is:
  441. # check(option : Option, opt : string, value : string) -> any
  442. # where
  443. # option is the Option instance calling the checker
  444. # opt is the actual option seen on the command-line
  445. # (eg. "-a", "--file")
  446. # value is the option argument seen on the command-line
  447. #
  448. # The return value should be in the appropriate Python type
  449. # for option.type -- eg. an integer if option.type == "int".
  450. #
  451. # If no checker is defined for a type, arguments will be
  452. # unchecked and remain strings.
  453. TYPE_CHECKER = { "int" : check_builtin,
  454. "long" : check_builtin,
  455. "float" : check_builtin,
  456. "complex": check_builtin,
  457. "choice" : check_choice,
  458. }
  459. # CHECK_METHODS is a list of unbound method objects; they are called
  460. # by the constructor, in order, after all attributes are
  461. # initialized. The list is created and filled in later, after all
  462. # the methods are actually defined. (I just put it here because I
  463. # like to define and document all class attributes in the same
  464. # place.) Subclasses that add another _check_*() method should
  465. # define their own CHECK_METHODS list that adds their check method
  466. # to those from this class.
  467. CHECK_METHODS = None
  468. # -- Constructor/initialization methods ----------------------------
  469. def __init__(self, *opts, **attrs):
  470. # Set _short_opts, _long_opts attrs from 'opts' tuple.
  471. # Have to be set now, in case no option strings are supplied.
  472. self._short_opts = []
  473. self._long_opts = []
  474. opts = self._check_opt_strings(opts)
  475. self._set_opt_strings(opts)
  476. # Set all other attrs (action, type, etc.) from 'attrs' dict
  477. self._set_attrs(attrs)
  478. # Check all the attributes we just set. There are lots of
  479. # complicated interdependencies, but luckily they can be farmed
  480. # out to the _check_*() methods listed in CHECK_METHODS -- which
  481. # could be handy for subclasses! The one thing these all share
  482. # is that they raise OptionError if they discover a problem.
  483. for checker in self.CHECK_METHODS:
  484. checker(self)
  485. def _check_opt_strings(self, opts):
  486. # Filter out None because early versions of Optik had exactly
  487. # one short option and one long option, either of which
  488. # could be None.
  489. opts = filter(None, opts)
  490. if not opts:
  491. raise TypeError("at least one option string must be supplied")
  492. return opts
  493. def _set_opt_strings(self, opts):
  494. for opt in opts:
  495. if len(opt) < 2:
  496. raise OptionError(
  497. "invalid option string %r: "
  498. "must be at least two characters long" % opt, self)
  499. elif len(opt) == 2:
  500. if not (opt[0] == "-" and opt[1] != "-"):
  501. raise OptionError(
  502. "invalid short option string %r: "
  503. "must be of the form -x, (x any non-dash char)" % opt,
  504. self)
  505. self._short_opts.append(opt)
  506. else:
  507. if not (opt[0:2] == "--" and opt[2] != "-"):
  508. raise OptionError(
  509. "invalid long option string %r: "
  510. "must start with --, followed by non-dash" % opt,
  511. self)
  512. self._long_opts.append(opt)
  513. def _set_attrs(self, attrs):
  514. for attr in self.ATTRS:
  515. if attr in attrs:
  516. setattr(self, attr, attrs[attr])
  517. del attrs[attr]
  518. else:
  519. if attr == 'default':
  520. setattr(self, attr, NO_DEFAULT)
  521. else:
  522. setattr(self, attr, None)
  523. if attrs:
  524. attrs = attrs.keys()
  525. attrs.sort()
  526. raise OptionError(
  527. "invalid keyword arguments: %s" % ", ".join(attrs),
  528. self)
  529. # -- Constructor validation methods --------------------------------
  530. def _check_action(self):
  531. if self.action is None:
  532. self.action = "store"
  533. elif self.action not in self.ACTIONS:
  534. raise OptionError("invalid action: %r" % self.action, self)
  535. def _check_type(self):
  536. if self.type is None:
  537. if self.action in self.ALWAYS_TYPED_ACTIONS:
  538. if self.choices is not None:
  539. # The "choices" attribute implies "choice" type.
  540. self.type = "choice"
  541. else:
  542. # No type given? "string" is the most sensible default.
  543. self.type = "string"
  544. else:
  545. # Allow type objects or builtin type conversion functions
  546. # (int, str, etc.) as an alternative to their names. (The
  547. # complicated check of __builtin__ is only necessary for
  548. # Python 2.1 and earlier, and is short-circuited by the
  549. # first check on modern Pythons.)
  550. import __builtin__
  551. if ( type(self.type) is types.TypeType or
  552. (hasattr(self.type, "__name__") and
  553. getattr(__builtin__, self.type.__name__, None) is self.type) ):
  554. self.type = self.type.__name__
  555. if self.type == "str":
  556. self.type = "string"
  557. if self.type not in self.TYPES:
  558. raise OptionError("invalid option type: %r" % self.type, self)
  559. if self.action not in self.TYPED_ACTIONS:
  560. raise OptionError(
  561. "must not supply a type for action %r" % self.action, self)
  562. def _check_choice(self):
  563. if self.type == "choice":
  564. if self.choices is None:
  565. raise OptionError(
  566. "must supply a list of choices for type 'choice'", self)
  567. elif type(self.choices) not in (types.TupleType, types.ListType):
  568. raise OptionError(
  569. "choices must be a list of strings ('%s' supplied)"
  570. % str(type(self.choices)).split("'")[1], self)
  571. elif self.choices is not None:
  572. raise OptionError(
  573. "must not supply choices for type %r" % self.type, self)
  574. def _check_dest(self):
  575. # No destination given, and we need one for this action. The
  576. # self.type check is for callbacks that take a value.
  577. takes_value = (self.action in self.STORE_ACTIONS or
  578. self.type is not None)
  579. if self.dest is None and takes_value:
  580. # Glean a destination from the first long option string,
  581. # or from the first short option string if no long options.
  582. if self._long_opts:
  583. # eg. "--foo-bar" -> "foo_bar"
  584. self.dest = self._long_opts[0][2:].replace('-', '_')
  585. else:
  586. self.dest = self._short_opts[0][1]
  587. def _check_const(self):
  588. if self.action not in self.CONST_ACTIONS and self.const is not None:
  589. raise OptionError(
  590. "'const' must not be supplied for action %r" % self.action,
  591. self)
  592. def _check_nargs(self):
  593. if self.action in self.TYPED_ACTIONS:
  594. if self.nargs is None:
  595. self.nargs = 1
  596. elif self.nargs is not None:
  597. raise OptionError(
  598. "'nargs' must not be supplied for action %r" % self.action,
  599. self)
  600. def _check_callback(self):
  601. if self.action == "callback":
  602. if not hasattr(self.callback, '__call__'):
  603. raise OptionError(
  604. "callback not callable: %r" % self.callback, self)
  605. if (self.callback_args is not None and
  606. type(self.callback_args) is not types.TupleType):
  607. raise OptionError(
  608. "callback_args, if supplied, must be a tuple: not %r"
  609. % self.callback_args, self)
  610. if (self.callback_kwargs is not None and
  611. type(self.callback_kwargs) is not types.DictType):
  612. raise OptionError(
  613. "callback_kwargs, if supplied, must be a dict: not %r"
  614. % self.callback_kwargs, self)
  615. else:
  616. if self.callback is not None:
  617. raise OptionError(
  618. "callback supplied (%r) for non-callback option"
  619. % self.callback, self)
  620. if self.callback_args is not None:
  621. raise OptionError(
  622. "callback_args supplied for non-callback option", self)
  623. if self.callback_kwargs is not None:
  624. raise OptionError(
  625. "callback_kwargs supplied for non-callback option", self)
  626. CHECK_METHODS = [_check_action,
  627. _check_type,
  628. _check_choice,
  629. _check_dest,
  630. _check_const,
  631. _check_nargs,
  632. _check_callback]
  633. # -- Miscellaneous methods -----------------------------------------
  634. def __str__(self):
  635. return "/".join(self._short_opts + self._long_opts)
  636. __repr__ = _repr
  637. def takes_value(self):
  638. return self.type is not None
  639. def get_opt_string(self):
  640. if self._long_opts:
  641. return self._long_opts[0]
  642. else:
  643. return self._short_opts[0]
  644. # -- Processing methods --------------------------------------------
  645. def check_value(self, opt, value):
  646. checker = self.TYPE_CHECKER.get(self.type)
  647. if checker is None:
  648. return value
  649. else:
  650. return checker(self, opt, value)
  651. def convert_value(self, opt, value):
  652. if value is not None:
  653. if self.nargs == 1:
  654. return self.check_value(opt, value)
  655. else:
  656. return tuple([self.check_value(opt, v) for v in value])
  657. def process(self, opt, value, values, parser):
  658. # First, convert the value(s) to the right type. Howl if any
  659. # value(s) are bogus.
  660. value = self.convert_value(opt, value)
  661. # And then take whatever action is expected of us.
  662. # This is a separate method to make life easier for
  663. # subclasses to add new actions.
  664. return self.take_action(
  665. self.action, self.dest, opt, value, values, parser)
  666. def take_action(self, action, dest, opt, value, values, parser):
  667. if action == "store":
  668. setattr(values, dest, value)
  669. elif action == "store_const":
  670. setattr(values, dest, self.const)
  671. elif action == "store_true":
  672. setattr(values, dest, True)
  673. elif action == "store_false":
  674. setattr(values, dest, False)
  675. elif action == "append":
  676. values.ensure_value(dest, []).append(value)
  677. elif action == "append_const":
  678. values.ensure_value(dest, []).append(self.const)
  679. elif action == "count":
  680. setattr(values, dest, values.ensure_value(dest, 0) + 1)
  681. elif action == "callback":
  682. args = self.callback_args or ()
  683. kwargs = self.callback_kwargs or {}
  684. self.callback(self, opt, value, parser, *args, **kwargs)
  685. elif action == "help":
  686. parser.print_help()
  687. parser.exit()
  688. elif action == "version":
  689. parser.print_version()
  690. parser.exit()
  691. else:
  692. raise ValueError("unknown action %r" % self.action)
  693. return 1
  694. # class Option
  695. SUPPRESS_HELP = "SUPPRESS"+"HELP"
  696. SUPPRESS_USAGE = "SUPPRESS"+"USAGE"
  697. try:
  698. basestring
  699. except NameError:
  700. def isbasestring(x):
  701. return isinstance(x, (types.StringType, types.UnicodeType))
  702. else:
  703. def isbasestring(x):
  704. return isinstance(x, basestring)
  705. class Values:
  706. def __init__(self, defaults=None):
  707. if defaults:
  708. for (attr, val) in defaults.items():
  709. setattr(self, attr, val)
  710. def __str__(self):
  711. return str(self.__dict__)
  712. __repr__ = _repr
  713. def __cmp__(self, other):
  714. if isinstance(other, Values):
  715. return cmp(self.__dict__, other.__dict__)
  716. elif isinstance(other, types.DictType):
  717. return cmp(self.__dict__, other)
  718. else:
  719. return -1
  720. def _update_careful(self, dict):
  721. """
  722. Update the option values from an arbitrary dictionary, but only
  723. use keys from dict that already have a corresponding attribute
  724. in self. Any keys in dict without a corresponding attribute
  725. are silently ignored.
  726. """
  727. for attr in dir(self):
  728. if attr in dict:
  729. dval = dict[attr]
  730. if dval is not None:
  731. setattr(self, attr, dval)
  732. def _update_loose(self, dict):
  733. """
  734. Update the option values from an arbitrary dictionary,
  735. using all keys from the dictionary regardless of whether
  736. they have a corresponding attribute in self or not.
  737. """
  738. self.__dict__.update(dict)
  739. def _update(self, dict, mode):
  740. if mode == "careful":
  741. self._update_careful(dict)
  742. elif mode == "loose":
  743. self._update_loose(dict)
  744. else:
  745. raise ValueError, "invalid update mode: %r" % mode
  746. def read_module(self, modname, mode="careful"):
  747. __import__(modname)
  748. mod = sys.modules[modname]
  749. self._update(vars(mod), mode)
  750. def read_file(self, filename, mode="careful"):
  751. vars = {}
  752. execfile(filename, vars)
  753. self._update(vars, mode)
  754. def ensure_value(self, attr, value):
  755. if not hasattr(self, attr) or getattr(self, attr) is None:
  756. setattr(self, attr, value)
  757. return getattr(self, attr)
  758. class OptionContainer:
  759. """
  760. Abstract base class.
  761. Class attributes:
  762. standard_option_list : [Option]
  763. list of standard options that will be accepted by all instances
  764. of this parser class (intended to be overridden by subclasses).
  765. Instance attributes:
  766. option_list : [Option]
  767. the list of Option objects contained by this OptionContainer
  768. _short_opt : { string : Option }
  769. dictionary mapping short option strings, eg. "-f" or "-X",
  770. to the Option instances that implement them. If an Option
  771. has multiple short option strings, it will appear in this
  772. dictionary multiple times. [1]
  773. _long_opt : { string : Option }
  774. dictionary mapping long option strings, eg. "--file" or
  775. "--exclude", to the Option instances that implement them.
  776. Again, a given Option can occur multiple times in this
  777. dictionary. [1]
  778. defaults : { string : any }
  779. dictionary mapping option destination names to default
  780. values for each destination [1]
  781. [1] These mappings are common to (shared by) all components of the
  782. controlling OptionParser, where they are initially created.
  783. """
  784. def __init__(self, option_class, conflict_handler, description):
  785. # Initialize the option list and related data structures.
  786. # This method must be provided by subclasses, and it must
  787. # initialize at least the following instance attributes:
  788. # option_list, _short_opt, _long_opt, defaults.
  789. self._create_option_list()
  790. self.option_class = option_class
  791. self.set_conflict_handler(conflict_handler)
  792. self.set_description(description)
  793. def _create_option_mappings(self):
  794. # For use by OptionParser constructor -- create the master
  795. # option mappings used by this OptionParser and all
  796. # OptionGroups that it owns.
  797. self._short_opt = {} # single letter -> Option instance
  798. self._long_opt = {} # long option -> Option instance
  799. self.defaults = {} # maps option dest -> default value
  800. def _share_option_mappings(self, parser):
  801. # For use by OptionGroup constructor -- use shared option
  802. # mappings from the OptionParser that owns this OptionGroup.
  803. self._short_opt = parser._short_opt
  804. self._long_opt = parser._long_opt
  805. self.defaults = parser.defaults
  806. def set_conflict_handler(self, handler):
  807. if handler not in ("error", "resolve"):
  808. raise ValueError, "invalid conflict_resolution value %r" % handler
  809. self.conflict_handler = handler
  810. def set_description(self, description):
  811. self.description = description
  812. def get_description(self):
  813. return self.description
  814. def destroy(self):
  815. """see OptionParser.destroy()."""
  816. del self._short_opt
  817. del self._long_opt
  818. del self.defaults
  819. # -- Option-adding methods -----------------------------------------
  820. def _check_conflict(self, option):
  821. conflict_opts = []
  822. for opt in option._short_opts:
  823. if opt in self._short_opt:
  824. conflict_opts.append((opt, self._short_opt[opt]))
  825. for opt in option._long_opts:
  826. if opt in self._long_opt:
  827. conflict_opts.append((opt, self._long_opt[opt]))
  828. if conflict_opts:
  829. handler = self.conflict_handler
  830. if handler == "error":
  831. raise OptionConflictError(
  832. "conflicting option string(s): %s"
  833. % ", ".join([co[0] for co in conflict_opts]),
  834. option)
  835. elif handler == "resolve":
  836. for (opt, c_option) in conflict_opts:
  837. if opt.startswith("--"):
  838. c_option._long_opts.remove(opt)
  839. del self._long_opt[opt]
  840. else:
  841. c_option._short_opts.remove(opt)
  842. del self._short_opt[opt]
  843. if not (c_option._short_opts or c_option._long_opts):
  844. c_option.container.option_list.remove(c_option)
  845. def add_option(self, *args, **kwargs):
  846. """add_option(Option)
  847. add_option(opt_str, ..., kwarg=val, ...)
  848. """
  849. if type(args[0]) in types.StringTypes:
  850. option = self.option_class(*args, **kwargs)
  851. elif len(args) == 1 and not kwargs:
  852. option = args[0]
  853. if not isinstance(option, Option):
  854. raise TypeError, "not an Option instance: %r" % option
  855. else:
  856. raise TypeError, "invalid arguments"
  857. self._check_conflict(option)
  858. self.option_list.append(option)
  859. option.container = self
  860. for opt in option._short_opts:
  861. self._short_opt[opt] = option
  862. for opt in option._long_opts:
  863. self._long_opt[opt] = option
  864. if option.dest is not None: # option has a dest, we need a default
  865. if option.default is not NO_DEFAULT:
  866. self.defaults[option.dest] = option.default
  867. elif option.dest not in self.defaults:
  868. self.defaults[option.dest] = None
  869. return option
  870. def add_options(self, option_list):
  871. for option in option_list:
  872. self.add_option(option)
  873. # -- Option query/removal methods ----------------------------------
  874. def get_option(self, opt_str):
  875. return (self._short_opt.get(opt_str) or
  876. self._long_opt.get(opt_str))
  877. def has_option(self, opt_str):
  878. return (opt_str in self._short_opt or
  879. opt_str in self._long_opt)
  880. def remove_option(self, opt_str):
  881. option = self._short_opt.get(opt_str)
  882. if option is None:
  883. option = self._long_opt.get(opt_str)
  884. if option is None:
  885. raise ValueError("no such option %r" % opt_str)
  886. for opt in option._short_opts:
  887. del self._short_opt[opt]
  888. for opt in option._long_opts:
  889. del self._long_opt[opt]
  890. option.container.option_list.remove(option)
  891. # -- Help-formatting methods ---------------------------------------
  892. def format_option_help(self, formatter):
  893. if not self.option_list:
  894. return ""
  895. result = []
  896. for option in self.option_list:
  897. if not option.help is SUPPRESS_HELP:
  898. result.append(formatter.format_option(option))
  899. return "".join(result)
  900. def format_description(self, formatter):
  901. return formatter.format_description(self.get_description())
  902. def format_help(self, formatter):
  903. result = []
  904. if self.description:
  905. result.append(self.format_description(formatter))
  906. if self.option_list:
  907. result.append(self.format_option_help(formatter))
  908. return "\n".join(result)
  909. class OptionGroup (OptionContainer):
  910. def __init__(self, parser, title, description=None):
  911. self.parser = parser
  912. OptionContainer.__init__(
  913. self, parser.option_class, parser.conflict_handler, description)
  914. self.title = title
  915. def _create_option_list(self):
  916. self.option_list = []
  917. self._share_option_mappings(self.parser)
  918. def set_title(self, title):
  919. self.title = title
  920. def destroy(self):
  921. """see OptionParser.destroy()."""
  922. OptionContainer.destroy(self)
  923. del self.option_list
  924. # -- Help-formatting methods ---------------------------------------
  925. def format_help(self, formatter):
  926. result = formatter.format_heading(self.title)
  927. formatter.indent()
  928. result += OptionContainer.format_help(self, formatter)
  929. formatter.dedent()
  930. return result
  931. class OptionParser (OptionContainer):
  932. """
  933. Class attributes:
  934. standard_option_list : [Option]
  935. list of standard options that will be accepted by all instances
  936. of this parser class (intended to be overridden by subclasses).
  937. Instance attributes:
  938. usage : string
  939. a usage string for your program. Before it is displayed
  940. to the user, "%prog" will be expanded to the name of
  941. your program (self.prog or os.path.basename(sys.argv[0])).
  942. prog : string
  943. the name of the current program (to override
  944. os.path.basename(sys.argv[0])).
  945. description : string
  946. A paragraph of text giving a brief overview of your program.
  947. optparse reformats this paragraph to fit the current terminal
  948. width and prints it when the user requests help (after usage,
  949. but before the list of options).
  950. epilog : string
  951. paragraph of help text to print after option help
  952. option_groups : [OptionGroup]
  953. list of option groups in this parser (option groups are
  954. irrelevant for parsing the command-line, but very useful
  955. for generating help)
  956. allow_interspersed_args : bool = true
  957. if true, positional arguments may be interspersed with options.
  958. Assuming -a and -b each take a single argument, the command-line
  959. -ablah foo bar -bboo baz
  960. will be interpreted the same as
  961. -ablah -bboo -- foo bar baz
  962. If this flag were false, that command line would be interpreted as
  963. -ablah -- foo bar -bboo baz
  964. -- ie. we stop processing options as soon as we see the first
  965. non-option argument. (This is the tradition followed by
  966. Python's getopt module, Perl's Getopt::Std, and other argument-
  967. parsing libraries, but it is generally annoying to users.)
  968. process_default_values : bool = true
  969. if true, option default values are processed similarly to option
  970. values from the command line: that is, they are passed to the
  971. type-checking function for the option's type (as long as the
  972. default value is a string). (This really only matters if you
  973. have defined custom types; see SF bug #955889.) Set it to false
  974. to restore the behaviour of Optik 1.4.1 and earlier.
  975. rargs : [string]
  976. the argument list currently being parsed. Only set when
  977. parse_args() is active, and continually trimmed down as
  978. we consume arguments. Mainly there for the benefit of
  979. callback options.
  980. largs : [string]
  981. the list of leftover arguments that we have skipped while
  982. parsing options. If allow_interspersed_args is false, this
  983. list is always empty.
  984. values : Values
  985. the set of option values currently being accumulated. Only
  986. set when parse_args() is active. Also mainly for callbacks.
  987. Because of the 'rargs', 'largs', and 'values' attributes,
  988. OptionParser is not thread-safe. If, for some perverse reason, you
  989. need to parse command-line arguments simultaneously in different
  990. threads, use different OptionParser instances.
  991. """
  992. standard_option_list = []
  993. def __init__(self,
  994. usage=None,
  995. option_list=None,
  996. option_class=Option,
  997. version=None,
  998. conflict_handler="error",
  999. description=None,
  1000. formatter=None,
  1001. add_help_option=True,
  1002. prog=None,
  1003. epilog=None):
  1004. OptionContainer.__init__(
  1005. self, option_class, conflict_handler, description)
  1006. self.set_usage(usage)
  1007. self.prog = prog
  1008. self.version = version
  1009. self.allow_interspersed_args = True
  1010. self.process_default_values = True
  1011. if formatter is None:
  1012. formatter = IndentedHelpFormatter()
  1013. self.formatter = formatter
  1014. self.formatter.set_parser(self)
  1015. self.epilog = epilog
  1016. # Populate the option list; initial sources are the
  1017. # standard_option_list class attribute, the 'option_list'
  1018. # argument, and (if applicable) the _add_version_option() and
  1019. # _add_help_option() methods.
  1020. self._populate_option_list(option_list,
  1021. add_help=add_help_option)
  1022. self._init_parsing_state()
  1023. def destroy(self):
  1024. """
  1025. Declare that you are done with this OptionParser. This cleans up
  1026. reference cycles so the OptionParser (and all objects referenced by
  1027. it) can be garbage-collected promptly. After calling destroy(), the
  1028. OptionParser is unusable.
  1029. """
  1030. OptionContainer.destroy(self)
  1031. for group in self.option_groups:
  1032. group.destroy()
  1033. del self.option_list
  1034. del self.option_groups
  1035. del self.formatter
  1036. # -- Private methods -----------------------------------------------
  1037. # (used by our or OptionContainer's constructor)
  1038. def _create_option_list(self):
  1039. self.option_list = []
  1040. self.option_groups = []
  1041. self._create_option_mappings()
  1042. def _add_help_option(self):
  1043. self.add_option("-h", "--help",
  1044. action="help",
  1045. help=_("show this help message and exit"))
  1046. def _add_version_option(self):
  1047. self.add_option("--version",
  1048. action="version",
  1049. help=_("show program's version number and exit"))
  1050. def _populate_option_list(self, option_list, add_help=True):
  1051. if self.standard_option_list:
  1052. self.add_options(self.standard_option_list)
  1053. if option_list:
  1054. self.add_options(option_list)
  1055. if self.version:
  1056. self._add_version_option()
  1057. if add_help:
  1058. self._add_help_option()
  1059. def _init_parsing_state(self):
  1060. # These are set in parse_args() for the convenience of callbacks.
  1061. self.rargs = None
  1062. self.largs = None
  1063. self.values = None
  1064. # -- Simple modifier methods ---------------------------------------
  1065. def set_usage(self, usage):
  1066. if usage is None:
  1067. self.usage = _("%prog [options]")
  1068. elif usage is SUPPRESS_USAGE:
  1069. self.usage = None
  1070. # For backwards compatibility with Optik 1.3 and earlier.
  1071. elif usage.lower().startswith("usage: "):
  1072. self.usage = usage[7:]
  1073. else:
  1074. self.usage = usage
  1075. def enable_interspersed_args(self):
  1076. """Set parsing to not stop on the first non-option, allowing
  1077. interspersing switches with command arguments. This is the
  1078. default behavior. See also disable_interspersed_args() and the
  1079. class documentation description of the attribute
  1080. allow_interspersed_args."""
  1081. self.allow_interspersed_args = True
  1082. def disable_interspersed_args(self):
  1083. """Set parsing to stop on the first non-option. Use this if
  1084. you have a command processor which runs another command that
  1085. has options of its own and you want to make sure these options
  1086. don't get confused.
  1087. """
  1088. self.allow_interspersed_args = False
  1089. def set_process_default_values(self, process):
  1090. self.process_default_values = process
  1091. def set_default(self, dest, value):
  1092. self.defaults[dest] = value
  1093. def set_defaults(self, **kwargs):
  1094. self.defaults.update(kwargs)
  1095. def _get_all_options(self):
  1096. options = self.option_list[:]
  1097. for group in self.option_groups:
  1098. options.extend(group.option_list)
  1099. return options
  1100. def get_default_values(self):
  1101. if not self.process_default_values:
  1102. # Old, pre-Optik 1.5 behaviour.
  1103. return Values(self.defaults)
  1104. defaults = self.defaults.copy()
  1105. for option in self._get_all_options():
  1106. default = defaults.get(option.dest)
  1107. if isbasestring(default):
  1108. opt_str = option.get_opt_string()
  1109. defaults[option.dest] = option.check_value(opt_str, default)
  1110. return Values(defaults)
  1111. # -- OptionGroup methods -------------------------------------------
  1112. def add_option_group(self, *args, **kwargs):
  1113. # XXX lots of overlap with OptionContainer.add_option()
  1114. if type(args[0]) is types.StringType:
  1115. group = OptionGroup(self, *args, **kwargs)
  1116. elif len(args) == 1 and not kwargs:
  1117. group = args[0]
  1118. if not isinstance(group, OptionGroup):
  1119. raise TypeError, "not an OptionGroup instance: %r" % group
  1120. if group.parser is not self:
  1121. raise ValueError, "invalid OptionGroup (wrong parser)"
  1122. else:
  1123. raise TypeError, "invalid arguments"
  1124. self.option_groups.append(group)
  1125. return group
  1126. def get_option_group(self, opt_str):
  1127. option = (self._short_opt.get(opt_str) or
  1128. self._long_opt.get(opt_str))
  1129. if option and option.container is not self:
  1130. return option.container
  1131. return None
  1132. # -- Option-parsing methods ----------------------------------------
  1133. def _get_args(self, args):
  1134. if args is None:
  1135. return sys.argv[1:]
  1136. else:
  1137. return args[:] # don't modify caller's list
  1138. def parse_args(self, args=None, values=None):
  1139. """
  1140. parse_args(args : [string] = sys.argv[1:],
  1141. values : Values = None)
  1142. -> (values : Values, args : [string])
  1143. Parse the command-line options found in 'args' (default:
  1144. sys.argv[1:]). Any errors result in a call to 'error()', which
  1145. by default prints the usage message to stderr and calls
  1146. sys.exit() with an error message. On success returns a pair
  1147. (values, args) where 'values' is a Values instance (with all
  1148. your option values) and 'args' is the list of arguments left
  1149. over after parsing options.
  1150. """
  1151. rargs = self._get_args(args)
  1152. if values is None:
  1153. values = self.get_default_values()
  1154. # Store the halves of the argument list as attributes for the
  1155. # convenience of callbacks:
  1156. # rargs
  1157. # the rest of the command-line (the "r" stands for
  1158. # "remaining" or "right-hand")
  1159. # largs
  1160. # the leftover arguments -- ie. what's left after removing
  1161. # options and their arguments (the "l" stands for "leftover"
  1162. # or "left-hand")
  1163. self.rargs = rargs
  1164. self.largs = largs = []
  1165. self.values = values
  1166. try:
  1167. stop = self._process_args(largs, rargs, values)
  1168. except (BadOptionError, OptionValueError), err:
  1169. self.error(str(err))
  1170. args = largs + rargs
  1171. return self.check_values(values, args)
  1172. def check_values(self, values, args):
  1173. """
  1174. check_values(values : Values, args : [string])
  1175. -> (values : Values, args : [string])
  1176. Check that the supplied option values and leftover arguments are
  1177. valid. Returns the option values and leftover arguments
  1178. (possibly adjusted, possibly completely new -- whatever you
  1179. like). Default implementation just returns the passed-in
  1180. values; subclasses may override as desired.
  1181. """
  1182. return (values, args)
  1183. def _process_args(self, largs, rargs, values):
  1184. """_process_args(largs : [string],
  1185. rargs : [string],
  1186. values : Values)
  1187. Process command-line arguments and populate 'values', consuming
  1188. options and arguments from 'rargs'. If 'allow_interspersed_args' is
  1189. false, stop at the first non-option argument. If true, accumulate any
  1190. interspersed non-option arguments in 'largs'.
  1191. """
  1192. while rargs:
  1193. arg = rargs[0]
  1194. # We handle bare "--" explicitly, and bare "-" is handled by the
  1195. # standard arg handler since the short arg case ensures that the
  1196. # len of the opt string is greater than 1.
  1197. if arg == "--":
  1198. del rargs[0]
  1199. return
  1200. elif arg[0:2] == "--":
  1201. # process a single long option (possibly with value(s))
  1202. self._process_long_opt(rargs, values)
  1203. elif arg[:1] == "-" and len(arg) > 1:
  1204. # process a cluster of short options (possibly with
  1205. # value(s) for the last one only)
  1206. self._process_short_opts(rargs, values)
  1207. elif self.allow_interspersed_args:
  1208. largs.append(arg)
  1209. del rargs[0]
  1210. else:
  1211. return # stop now, leave this arg in rargs
  1212. # Say this is the original argument list:
  1213. # [arg0, arg1, ..., arg(i-1), arg(i), arg(i+1), ..., arg(N-1)]
  1214. # ^
  1215. # (we are about to process arg(i)).
  1216. #
  1217. # Then rargs is [arg(i), ..., arg(N-1)] and largs is a *subset* of
  1218. # [arg0, ..., arg(i-1)] (any options and their arguments will have
  1219. # been removed from largs).
  1220. #
  1221. # The while loop will usually consume 1 or more arguments per pass.
  1222. # If it consumes 1 (eg. arg is an option that takes no arguments),
  1223. # then after _process_arg() is done the situation is:
  1224. #
  1225. # largs = subset of [arg0, ..., arg(i)]
  1226. # rargs = [arg(i+1), ..., arg(N-1)]
  1227. #
  1228. # If allow_interspersed_args is false, largs will always be
  1229. # *empty* -- still a subset of [arg0, ..., arg(i-1)], but
  1230. # not a very interesting subset!
  1231. def _match_long_opt(self, opt):
  1232. """_match_long_opt(opt : string) -> string
  1233. Determine which long option string 'opt' matches, ie. which one
  1234. it is an unambiguous abbreviation for. Raises BadOptionError if
  1235. 'opt' doesn't unambiguously match any long option string.
  1236. """
  1237. return _match_abbrev(opt, self._long_opt)
  1238. def _process_long_opt(self, rargs, values):
  1239. arg = rargs.pop(0)
  1240. # Value explicitly attached to arg? Pretend it's the next
  1241. # argument.
  1242. if "=" in arg:
  1243. (opt, next_arg) = arg.split("=", 1)
  1244. rargs.insert(0, next_arg)
  1245. had_explicit_value = True
  1246. else:
  1247. opt = arg
  1248. had_explicit_value = False
  1249. opt = self._match_long_opt(opt)
  1250. option = self._long_opt[opt]
  1251. if option.takes_value():
  1252. nargs = option.nargs
  1253. if len(rargs) < nargs:
  1254. if nargs == 1:
  1255. self.error(_("%s option requires an argument") % opt)
  1256. else:
  1257. self.error(_("%s option requires %d arguments")
  1258. % (opt, nargs))
  1259. elif nargs == 1:
  1260. value = rargs.pop(0)
  1261. else:
  1262. value = tuple(rargs[0:nargs])
  1263. del rargs[0:nargs]
  1264. elif had_explicit_value:
  1265. self.error(_("%s option does not take a value") % opt)
  1266. else:
  1267. value = None
  1268. option.process(opt, value, values, self)
  1269. def _process_short_opts(self, rargs, values):
  1270. arg = rargs.pop(0)
  1271. stop = False
  1272. i = 1
  1273. for ch in arg[1:]:
  1274. opt = "-" + ch
  1275. option = self._short_opt.get(opt)
  1276. i += 1 # we have consumed a character
  1277. if not option:
  1278. raise BadOptionError(opt)
  1279. if option.takes_value():
  1280. # Any characters left in arg? Pretend they're the
  1281. # next arg, and stop consuming characters of arg.
  1282. if i < len(arg):
  1283. rargs.insert(0, arg[i:])
  1284. stop = True
  1285. nargs = option.nargs
  1286. if len(rargs) < nargs:
  1287. if nargs == 1:
  1288. self.error(_("%s option requires an argument") % opt)
  1289. else:
  1290. self.error(_("%s option requires %d arguments")
  1291. % (opt, nargs))
  1292. elif nargs == 1:
  1293. value = rargs.pop(0)
  1294. else:
  1295. value = tuple(rargs[0:nargs])
  1296. del rargs[0:nargs]
  1297. else: # option doesn't take a value
  1298. value = None
  1299. option.process(opt, value, values, self)
  1300. if stop:
  1301. break
  1302. # -- Feedback methods ----------------------------------------------
  1303. def get_prog_name(self):
  1304. if self.prog is None:
  1305. return os.path.basename(sys.argv[0])
  1306. else:
  1307. return self.prog
  1308. def expand_prog_name(self, s):
  1309. return s.replace("%prog", self.get_prog_name())
  1310. def get_description(self):
  1311. return self.expand_prog_name(self.description)
  1312. def exit(self, status=0, msg=None):
  1313. if msg:
  1314. sys.stderr.write(msg)
  1315. sys.exit(status)
  1316. def error(self, msg):
  1317. """error(msg : string)
  1318. Print a usage message incorporating 'msg' to stderr and exit.
  1319. If you override this in a subclass, it should not return -- it
  1320. should either exit or raise an exception.
  1321. """
  1322. self.print_usage(sys.stderr)
  1323. self.exit(2, "%s: error: %s\n" % (self.get_prog_name(), msg))
  1324. def get_usage(self):
  1325. if self.usage:
  1326. return self.formatter.format_usage(
  1327. self.expand_prog_name(self.usage))
  1328. else:
  1329. return ""
  1330. def print_usage(self, file=None):
  1331. """print_usage(file : file = stdout)
  1332. Print the usage message for the current program (self.usage) to
  1333. 'file' (default stdout). Any occurrence of the string "%prog" in
  1334. self.usage is replaced with the name of the current program
  1335. (basename of sys.argv[0]). Does nothing if self.usage is empty
  1336. or not defined.
  1337. """
  1338. if self.usage:
  1339. print >>file, self.get_usage()
  1340. def get_version(self):
  1341. if self.version:
  1342. return self.expand_prog_name(self.version)
  1343. else:
  1344. return ""
  1345. def print_version(self, file=None):
  1346. """print_version(file : file = stdout)
  1347. Print the version message for this program (self.version) to
  1348. 'file' (default stdout). As with print_usage(), any occurrence
  1349. of "%prog" in self.version is replaced by the current program's
  1350. name. Does nothing if self.version is empty or undefined.
  1351. """
  1352. if self.version:
  1353. print >>file, self.get_version()
  1354. def format_option_help(self, formatter=None):
  1355. if formatter is None:
  1356. formatter = self.formatter
  1357. formatter.store_option_strings(self)
  1358. result = []
  1359. result.append(formatter.format_heading(_("Options")))
  1360. formatter.indent()
  1361. if self.option_list:
  1362. result.append(OptionContainer.format_option_help(self, formatter))
  1363. result.append("\n")
  1364. for group in self.option_groups:
  1365. result.append(group.format_help(formatter))
  1366. result.append("\n")
  1367. formatter.dedent()
  1368. # Drop the last "\n", or the header if no options or option groups:
  1369. return "".join(result[:-1])
  1370. def format_epilog(self, formatter):
  1371. return formatter.format_epilog(self.epilog)
  1372. def format_help(self, formatter=None):
  1373. if formatter is None:
  1374. formatter = self.formatter
  1375. result = []
  1376. if self.usage:
  1377. result.append(self.get_usage() + "\n")
  1378. if self.description:
  1379. result.append(self.format_description(formatter) + "\n")
  1380. result.append(self.format_option_help(formatter))
  1381. result.append(self.format_epilog(formatter))
  1382. return "".join(result)
  1383. # used by test suite
  1384. def _get_encoding(self, file):
  1385. encoding = getattr(file, "encoding", None)
  1386. if not encoding:
  1387. encoding = sys.getdefaultencoding()
  1388. return encoding
  1389. def print_help(self, file=None):
  1390. """print_help(file : file = stdout)
  1391. Print an extended help message, listing all options and any
  1392. help text provided with them, to 'file' (default stdout).
  1393. """
  1394. if file is None:
  1395. file = sys.stdout
  1396. encoding = self._get_encoding(file)
  1397. file.write(self.format_help().encode(encoding, "replace"))
  1398. # class OptionParser
  1399. def _match_abbrev(s, wordmap):
  1400. """_match_abbrev(s : string, wordmap : {string : Option}) -> string
  1401. Return the string key in 'wordmap' for which 's' is an unambiguous
  1402. abbreviation. If 's' is found to be ambiguous or doesn't match any of
  1403. 'words', raise BadOptionError.
  1404. """
  1405. # Is there an exact match?
  1406. if s in wordmap:
  1407. return s
  1408. else:
  1409. # Isolate all words with s as a prefix.
  1410. possibilities = [word for word in wordmap.keys()
  1411. if word.startswith(s)]
  1412. # No exact match, so there had better be just one possibility.
  1413. if len(possibilities) == 1:
  1414. return possibilities[0]
  1415. elif not possibilities:
  1416. raise BadOptionError(s)
  1417. else:
  1418. # More than one possible completion: ambiguous prefix.
  1419. possibilities.sort()
  1420. raise AmbiguousOptionError(s, possibilities)
  1421. # Some day, there might be many Option classes. As of Optik 1.3, the
  1422. # preferred way to instantiate Options is indirectly, via make_option(),
  1423. # which will become a factory function when there are many Option
  1424. # classes.
  1425. make_option = Option