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