optparse.py 59 KB

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