├── .hgignore ├── LICENSE.txt ├── MANIFEST.in ├── NEWS.txt ├── README.txt ├── argparse.py ├── doc ├── Makefile ├── make.bat └── source │ ├── Python-License.txt │ ├── argparse.rst │ ├── conf.py │ ├── index.rst │ └── license.rst ├── setup.cfg ├── setup.py ├── test └── test_argparse.py └── tox.ini /.hgignore: -------------------------------------------------------------------------------- 1 | .*\.py[co]$ 2 | ^build/ 3 | ^dist/ 4 | ^env24/ 5 | ^env25/ 6 | ^env26/ 7 | ^env27/ 8 | ^argparse.egg-info/ 9 | ^doc/_build/ 10 | ^MANIFEST$ 11 | .DS_Store 12 | .orig$ 13 | .rej$ 14 | .~$ 15 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | argparse is (c) 2006-2009 Steven J. Bethard . 2 | 3 | The argparse module was contributed to Python as of Python 2.7 and thus 4 | was licensed under the Python license. Same license applies to all files in 5 | the argparse package project. 6 | 7 | For details about the Python License, please see doc/Python-License.txt. 8 | 9 | History 10 | ------- 11 | 12 | Before (and including) argparse 1.1, the argparse package was licensed under 13 | Apache License v2.0. 14 | 15 | After argparse 1.1, all project files from the argparse project were deleted 16 | due to license compatibility issues between Apache License 2.0 and GNU GPL v2. 17 | 18 | The project repository then had a clean start with some files taken from 19 | Python 2.7.1, so definitely all files are under Python License now. 20 | 21 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include README.txt LICENSE.txt NEWS.txt 2 | 3 | recursive-include doc * 4 | 5 | global-exclude *.pyc 6 | global-exclude *.pyo 7 | global-exclude *.orig 8 | global-exclude *.rej 9 | 10 | prune doc/_build 11 | prune env24 12 | prune env25 13 | prune env26 14 | prune env27 15 | 16 | -------------------------------------------------------------------------------- /NEWS.txt: -------------------------------------------------------------------------------- 1 | What's New 2 | ========== 3 | 4 | argparse 1.4.1 5 | -------------- 6 | - fix issue #12353 argparse cannot handle empty arguments 7 | 8 | argparse 1.4.0 9 | -------------- 10 | 11 | - make argparse behave for default args aka 12 | issue #12776, #11839: call argparse type function only once. 13 | - move to github:ThomasWaldmann/argparse 14 | - add TW as maintainer / give TW's email 15 | - add some usecase to README, clarify issue tracking 16 | - add a note to tox.ini about testing on dead snakes 17 | 18 | argparse 1.3.0 19 | -------------- 20 | 21 | - added aliases support (thanks to Roland Kammerer!) + tests for it 22 | - use tox for testing python >= 2.6 23 | - tests successfully on 3.4 also (without random hash seed) 24 | - added argparse.__external_lib__ = True so one can test one is really using / 25 | testing the external library (and not the builtin one in stdlib of recent 26 | Pythons) 27 | 28 | argparse 1.2.2 29 | -------------- 30 | 31 | - added universal wheel support, built, signed and uploaded with: 32 | python setup.py sdist bdist_wheel upload --identity="Thomas Waldmann" --sign 33 | - host the files on pypi 34 | 35 | argparse 1.2.1 36 | -------------- 37 | 38 | - fixed Issue #82: argparse 1.2 incompatible with Python 3.1 39 | - hacked the tests so they don't have the minor failures that were caused 40 | by the compatibility stuff for python 2.3 and 3.1 41 | 42 | argparse 1.2 43 | ------------ 44 | 45 | - fixed Issue #79: re-licensed argparse package under same license as py 2.7 stdlib argparse code 46 | - fixed Issue #80: argparse 1.2 is now same archive on pypi / on google code 47 | 48 | -------------------------------------------------------------------------------- /README.txt: -------------------------------------------------------------------------------- 1 | This repo is archived now and completely unsupported 2 | ---------------------------------------------------- 3 | 4 | All python versions addressed by this code are out of support since long. 5 | 6 | DO NOT WRITE EMAIL TO ME ABOUT THIS REPO, I WILL NOT RESPOND. 7 | 8 | For details about this, just read the text below. 9 | 10 | 11 | Important Note about the PyPi argparse package 12 | ---------------------------------------------- 13 | argparse development happens in the python standard library nowadays, NOT HERE. 14 | 15 | The PyPi argparse package is mostly for people who want to have argparse on 16 | older Pythons, like < 2.7 or < 3.2 because it was not in stdlib back then. 17 | 18 | Thus, do not file issues, feature requests or pull requests for the PyPi 19 | version of argparse if they also apply to standard library argparse. 20 | 21 | If you find a bug in argparse (PyPi), please try to reproduce it with latest 22 | python 2.7 and 3.4/3.5 (and use argparse from stdlib). 23 | 24 | If it happens there also, please file a bug in the python.org issue tracker. 25 | If it does not happen there, file a bug in the argparse package issue tracker. 26 | 27 | 28 | About argparse 29 | -------------- 30 | The argparse module makes it easy to write user friendly command line 31 | interfaces. 32 | 33 | The program defines what arguments it requires, and argparse will figure out 34 | how to parse those out of sys.argv. The argparse module also automatically 35 | generates help and usage messages and issues errors when users give the 36 | program invalid arguments. 37 | 38 | As of Python >= 2.7 and >= 3.2, the argparse module is maintained within the 39 | Python standard library. For users who still need to support Python < 2.7 or 40 | < 3.2, it is also provided as a separate package, which tries to stay 41 | compatible with the module in the standard library, but also supports older 42 | Python versions. 43 | 44 | Also, we can fix bugs here for users who are stuck on some non-current python 45 | version, like e.g. 3.2.3 (which has bugs that were fixed in a later 3.2.x 46 | release). 47 | 48 | argparse is licensed under the Python license, for details see LICENSE.txt. 49 | 50 | 51 | Compatibility 52 | ------------- 53 | 54 | argparse should work on Python >= 2.3, it was tested on: 55 | 56 | * 2.3, 2.4, 2.5, 2.6 and 2.7 57 | * 3.1, 3.2, 3.3, 3.4 58 | 59 | 60 | Installation 61 | ------------ 62 | 63 | Try one of these: 64 | 65 | python setup.py install 66 | 67 | easy_install argparse 68 | 69 | pip install argparse 70 | 71 | putting argparse.py in some directory listed in sys.path should also work 72 | 73 | 74 | -------------------------------------------------------------------------------- /argparse.py: -------------------------------------------------------------------------------- 1 | # Author: Steven J. Bethard . 2 | # Maintainer: Thomas Waldmann 3 | 4 | """Command-line parsing library 5 | 6 | This module is an optparse-inspired command-line parsing library that: 7 | 8 | - handles both optional and positional arguments 9 | - produces highly informative usage messages 10 | - supports parsers that dispatch to sub-parsers 11 | 12 | The following is a simple usage example that sums integers from the 13 | command-line and writes the result to a file:: 14 | 15 | parser = argparse.ArgumentParser( 16 | description='sum the integers at the command line') 17 | parser.add_argument( 18 | 'integers', metavar='int', nargs='+', type=int, 19 | help='an integer to be summed') 20 | parser.add_argument( 21 | '--log', default=sys.stdout, type=argparse.FileType('w'), 22 | help='the file where the sum should be written') 23 | args = parser.parse_args() 24 | args.log.write('%s' % sum(args.integers)) 25 | args.log.close() 26 | 27 | The module contains the following public classes: 28 | 29 | - ArgumentParser -- The main entry point for command-line parsing. As the 30 | example above shows, the add_argument() method is used to populate 31 | the parser with actions for optional and positional arguments. Then 32 | the parse_args() method is invoked to convert the args at the 33 | command-line into an object with attributes. 34 | 35 | - ArgumentError -- The exception raised by ArgumentParser objects when 36 | there are errors with the parser's actions. Errors raised while 37 | parsing the command-line are caught by ArgumentParser and emitted 38 | as command-line messages. 39 | 40 | - FileType -- A factory for defining types of files to be created. As the 41 | example above shows, instances of FileType are typically passed as 42 | the type= argument of add_argument() calls. 43 | 44 | - Action -- The base class for parser actions. Typically actions are 45 | selected by passing strings like 'store_true' or 'append_const' to 46 | the action= argument of add_argument(). However, for greater 47 | customization of ArgumentParser actions, subclasses of Action may 48 | be defined and passed as the action= argument. 49 | 50 | - HelpFormatter, RawDescriptionHelpFormatter, RawTextHelpFormatter, 51 | ArgumentDefaultsHelpFormatter -- Formatter classes which 52 | may be passed as the formatter_class= argument to the 53 | ArgumentParser constructor. HelpFormatter is the default, 54 | RawDescriptionHelpFormatter and RawTextHelpFormatter tell the parser 55 | not to change the formatting for help text, and 56 | ArgumentDefaultsHelpFormatter adds information about argument defaults 57 | to the help. 58 | 59 | All other classes in this module are considered implementation details. 60 | (Also note that HelpFormatter and RawDescriptionHelpFormatter are only 61 | considered public as object names -- the API of the formatter objects is 62 | still considered an implementation detail.) 63 | """ 64 | 65 | __version__ = '1.4.0' # we use our own version number independant of the 66 | # one in stdlib and we release this on pypi. 67 | 68 | __external_lib__ = True # to make sure the tests really test THIS lib, 69 | # not the builtin one in Python stdlib 70 | 71 | __all__ = [ 72 | 'ArgumentParser', 73 | 'ArgumentError', 74 | 'ArgumentTypeError', 75 | 'FileType', 76 | 'HelpFormatter', 77 | 'ArgumentDefaultsHelpFormatter', 78 | 'RawDescriptionHelpFormatter', 79 | 'RawTextHelpFormatter', 80 | 'Namespace', 81 | 'Action', 82 | 'ONE_OR_MORE', 83 | 'OPTIONAL', 84 | 'PARSER', 85 | 'REMAINDER', 86 | 'SUPPRESS', 87 | 'ZERO_OR_MORE', 88 | ] 89 | 90 | 91 | import copy as _copy 92 | import os as _os 93 | import re as _re 94 | import sys as _sys 95 | import textwrap as _textwrap 96 | 97 | from gettext import gettext as _ 98 | 99 | try: 100 | set 101 | except NameError: 102 | # for python < 2.4 compatibility (sets module is there since 2.3): 103 | from sets import Set as set 104 | 105 | try: 106 | basestring 107 | except NameError: 108 | basestring = str 109 | 110 | try: 111 | sorted 112 | except NameError: 113 | # for python < 2.4 compatibility: 114 | def sorted(iterable, reverse=False): 115 | result = list(iterable) 116 | result.sort() 117 | if reverse: 118 | result.reverse() 119 | return result 120 | 121 | 122 | def _callable(obj): 123 | return hasattr(obj, '__call__') or hasattr(obj, '__bases__') 124 | 125 | 126 | SUPPRESS = '==SUPPRESS==' 127 | 128 | OPTIONAL = '?' 129 | ZERO_OR_MORE = '*' 130 | ONE_OR_MORE = '+' 131 | PARSER = 'A...' 132 | REMAINDER = '...' 133 | _UNRECOGNIZED_ARGS_ATTR = '_unrecognized_args' 134 | 135 | # ============================= 136 | # Utility functions and classes 137 | # ============================= 138 | 139 | class _AttributeHolder(object): 140 | """Abstract base class that provides __repr__. 141 | 142 | The __repr__ method returns a string in the format:: 143 | ClassName(attr=name, attr=name, ...) 144 | The attributes are determined either by a class-level attribute, 145 | '_kwarg_names', or by inspecting the instance __dict__. 146 | """ 147 | 148 | def __repr__(self): 149 | type_name = type(self).__name__ 150 | arg_strings = [] 151 | for arg in self._get_args(): 152 | arg_strings.append(repr(arg)) 153 | for name, value in self._get_kwargs(): 154 | arg_strings.append('%s=%r' % (name, value)) 155 | return '%s(%s)' % (type_name, ', '.join(arg_strings)) 156 | 157 | def _get_kwargs(self): 158 | return sorted(self.__dict__.items()) 159 | 160 | def _get_args(self): 161 | return [] 162 | 163 | 164 | def _ensure_value(namespace, name, value): 165 | if getattr(namespace, name, None) is None: 166 | setattr(namespace, name, value) 167 | return getattr(namespace, name) 168 | 169 | 170 | # =============== 171 | # Formatting Help 172 | # =============== 173 | 174 | class HelpFormatter(object): 175 | """Formatter for generating usage messages and argument help strings. 176 | 177 | Only the name of this class is considered a public API. All the methods 178 | provided by the class are considered an implementation detail. 179 | """ 180 | 181 | def __init__(self, 182 | prog, 183 | indent_increment=2, 184 | max_help_position=24, 185 | width=None): 186 | 187 | # default setting for width 188 | if width is None: 189 | try: 190 | width = int(_os.environ['COLUMNS']) 191 | except (KeyError, ValueError): 192 | width = 80 193 | width -= 2 194 | 195 | self._prog = prog 196 | self._indent_increment = indent_increment 197 | self._max_help_position = max_help_position 198 | self._width = width 199 | 200 | self._current_indent = 0 201 | self._level = 0 202 | self._action_max_length = 0 203 | 204 | self._root_section = self._Section(self, None) 205 | self._current_section = self._root_section 206 | 207 | self._whitespace_matcher = _re.compile(r'\s+') 208 | self._long_break_matcher = _re.compile(r'\n\n\n+') 209 | 210 | # =============================== 211 | # Section and indentation methods 212 | # =============================== 213 | def _indent(self): 214 | self._current_indent += self._indent_increment 215 | self._level += 1 216 | 217 | def _dedent(self): 218 | self._current_indent -= self._indent_increment 219 | assert self._current_indent >= 0, 'Indent decreased below 0.' 220 | self._level -= 1 221 | 222 | class _Section(object): 223 | 224 | def __init__(self, formatter, parent, heading=None): 225 | self.formatter = formatter 226 | self.parent = parent 227 | self.heading = heading 228 | self.items = [] 229 | 230 | def format_help(self): 231 | # format the indented section 232 | if self.parent is not None: 233 | self.formatter._indent() 234 | join = self.formatter._join_parts 235 | for func, args in self.items: 236 | func(*args) 237 | item_help = join([func(*args) for func, args in self.items]) 238 | if self.parent is not None: 239 | self.formatter._dedent() 240 | 241 | # return nothing if the section was empty 242 | if not item_help: 243 | return '' 244 | 245 | # add the heading if the section was non-empty 246 | if self.heading is not SUPPRESS and self.heading is not None: 247 | current_indent = self.formatter._current_indent 248 | heading = '%*s%s:\n' % (current_indent, '', self.heading) 249 | else: 250 | heading = '' 251 | 252 | # join the section-initial newline, the heading and the help 253 | return join(['\n', heading, item_help, '\n']) 254 | 255 | def _add_item(self, func, args): 256 | self._current_section.items.append((func, args)) 257 | 258 | # ======================== 259 | # Message building methods 260 | # ======================== 261 | def start_section(self, heading): 262 | self._indent() 263 | section = self._Section(self, self._current_section, heading) 264 | self._add_item(section.format_help, []) 265 | self._current_section = section 266 | 267 | def end_section(self): 268 | self._current_section = self._current_section.parent 269 | self._dedent() 270 | 271 | def add_text(self, text): 272 | if text is not SUPPRESS and text is not None: 273 | self._add_item(self._format_text, [text]) 274 | 275 | def add_usage(self, usage, actions, groups, prefix=None): 276 | if usage is not SUPPRESS: 277 | args = usage, actions, groups, prefix 278 | self._add_item(self._format_usage, args) 279 | 280 | def add_argument(self, action): 281 | if action.help is not SUPPRESS: 282 | 283 | # find all invocations 284 | get_invocation = self._format_action_invocation 285 | invocations = [get_invocation(action)] 286 | for subaction in self._iter_indented_subactions(action): 287 | invocations.append(get_invocation(subaction)) 288 | 289 | # update the maximum item length 290 | invocation_length = max([len(s) for s in invocations]) 291 | action_length = invocation_length + self._current_indent 292 | self._action_max_length = max(self._action_max_length, 293 | action_length) 294 | 295 | # add the item to the list 296 | self._add_item(self._format_action, [action]) 297 | 298 | def add_arguments(self, actions): 299 | for action in actions: 300 | self.add_argument(action) 301 | 302 | # ======================= 303 | # Help-formatting methods 304 | # ======================= 305 | def format_help(self): 306 | help = self._root_section.format_help() 307 | if help: 308 | help = self._long_break_matcher.sub('\n\n', help) 309 | help = help.strip('\n') + '\n' 310 | return help 311 | 312 | def _join_parts(self, part_strings): 313 | return ''.join([part 314 | for part in part_strings 315 | if part and part is not SUPPRESS]) 316 | 317 | def _format_usage(self, usage, actions, groups, prefix): 318 | if prefix is None: 319 | prefix = _('usage: ') 320 | 321 | # if usage is specified, use that 322 | if usage is not None: 323 | usage = usage % dict(prog=self._prog) 324 | 325 | # if no optionals or positionals are available, usage is just prog 326 | elif usage is None and not actions: 327 | usage = '%(prog)s' % dict(prog=self._prog) 328 | 329 | # if optionals and positionals are available, calculate usage 330 | elif usage is None: 331 | prog = '%(prog)s' % dict(prog=self._prog) 332 | 333 | # split optionals from positionals 334 | optionals = [] 335 | positionals = [] 336 | for action in actions: 337 | if action.option_strings: 338 | optionals.append(action) 339 | else: 340 | positionals.append(action) 341 | 342 | # build full usage string 343 | format = self._format_actions_usage 344 | action_usage = format(optionals + positionals, groups) 345 | usage = ' '.join([s for s in [prog, action_usage] if s]) 346 | 347 | # wrap the usage parts if it's too long 348 | text_width = self._width - self._current_indent 349 | if len(prefix) + len(usage) > text_width: 350 | 351 | # break usage into wrappable parts 352 | part_regexp = r'\(.*?\)+|\[.*?\]+|\S+' 353 | opt_usage = format(optionals, groups) 354 | pos_usage = format(positionals, groups) 355 | opt_parts = _re.findall(part_regexp, opt_usage) 356 | pos_parts = _re.findall(part_regexp, pos_usage) 357 | assert ' '.join(opt_parts) == opt_usage 358 | assert ' '.join(pos_parts) == pos_usage 359 | 360 | # helper for wrapping lines 361 | def get_lines(parts, indent, prefix=None): 362 | lines = [] 363 | line = [] 364 | if prefix is not None: 365 | line_len = len(prefix) - 1 366 | else: 367 | line_len = len(indent) - 1 368 | for part in parts: 369 | if line_len + 1 + len(part) > text_width: 370 | lines.append(indent + ' '.join(line)) 371 | line = [] 372 | line_len = len(indent) - 1 373 | line.append(part) 374 | line_len += len(part) + 1 375 | if line: 376 | lines.append(indent + ' '.join(line)) 377 | if prefix is not None: 378 | lines[0] = lines[0][len(indent):] 379 | return lines 380 | 381 | # if prog is short, follow it with optionals or positionals 382 | if len(prefix) + len(prog) <= 0.75 * text_width: 383 | indent = ' ' * (len(prefix) + len(prog) + 1) 384 | if opt_parts: 385 | lines = get_lines([prog] + opt_parts, indent, prefix) 386 | lines.extend(get_lines(pos_parts, indent)) 387 | elif pos_parts: 388 | lines = get_lines([prog] + pos_parts, indent, prefix) 389 | else: 390 | lines = [prog] 391 | 392 | # if prog is long, put it on its own line 393 | else: 394 | indent = ' ' * len(prefix) 395 | parts = opt_parts + pos_parts 396 | lines = get_lines(parts, indent) 397 | if len(lines) > 1: 398 | lines = [] 399 | lines.extend(get_lines(opt_parts, indent)) 400 | lines.extend(get_lines(pos_parts, indent)) 401 | lines = [prog] + lines 402 | 403 | # join lines into usage 404 | usage = '\n'.join(lines) 405 | 406 | # prefix with 'usage:' 407 | return '%s%s\n\n' % (prefix, usage) 408 | 409 | def _format_actions_usage(self, actions, groups): 410 | # find group indices and identify actions in groups 411 | group_actions = set() 412 | inserts = {} 413 | for group in groups: 414 | try: 415 | start = actions.index(group._group_actions[0]) 416 | except ValueError: 417 | continue 418 | else: 419 | end = start + len(group._group_actions) 420 | if actions[start:end] == group._group_actions: 421 | for action in group._group_actions: 422 | group_actions.add(action) 423 | if not group.required: 424 | if start in inserts: 425 | inserts[start] += ' [' 426 | else: 427 | inserts[start] = '[' 428 | inserts[end] = ']' 429 | else: 430 | if start in inserts: 431 | inserts[start] += ' (' 432 | else: 433 | inserts[start] = '(' 434 | inserts[end] = ')' 435 | for i in range(start + 1, end): 436 | inserts[i] = '|' 437 | 438 | # collect all actions format strings 439 | parts = [] 440 | for i, action in enumerate(actions): 441 | 442 | # suppressed arguments are marked with None 443 | # remove | separators for suppressed arguments 444 | if action.help is SUPPRESS: 445 | parts.append(None) 446 | if inserts.get(i) == '|': 447 | inserts.pop(i) 448 | elif inserts.get(i + 1) == '|': 449 | inserts.pop(i + 1) 450 | 451 | # produce all arg strings 452 | elif not action.option_strings: 453 | part = self._format_args(action, action.dest) 454 | 455 | # if it's in a group, strip the outer [] 456 | if action in group_actions: 457 | if part[0] == '[' and part[-1] == ']': 458 | part = part[1:-1] 459 | 460 | # add the action string to the list 461 | parts.append(part) 462 | 463 | # produce the first way to invoke the option in brackets 464 | else: 465 | option_string = action.option_strings[0] 466 | 467 | # if the Optional doesn't take a value, format is: 468 | # -s or --long 469 | if action.nargs == 0: 470 | part = '%s' % option_string 471 | 472 | # if the Optional takes a value, format is: 473 | # -s ARGS or --long ARGS 474 | else: 475 | default = action.dest.upper() 476 | args_string = self._format_args(action, default) 477 | part = '%s %s' % (option_string, args_string) 478 | 479 | # make it look optional if it's not required or in a group 480 | if not action.required and action not in group_actions: 481 | part = '[%s]' % part 482 | 483 | # add the action string to the list 484 | parts.append(part) 485 | 486 | # insert things at the necessary indices 487 | for i in sorted(inserts, reverse=True): 488 | parts[i:i] = [inserts[i]] 489 | 490 | # join all the action items with spaces 491 | text = ' '.join([item for item in parts if item is not None]) 492 | 493 | # clean up separators for mutually exclusive groups 494 | open = r'[\[(]' 495 | close = r'[\])]' 496 | text = _re.sub(r'(%s) ' % open, r'\1', text) 497 | text = _re.sub(r' (%s)' % close, r'\1', text) 498 | text = _re.sub(r'%s *%s' % (open, close), r'', text) 499 | text = _re.sub(r'\(([^|]*)\)', r'\1', text) 500 | text = text.strip() 501 | 502 | # return the text 503 | return text 504 | 505 | def _format_text(self, text): 506 | if '%(prog)' in text: 507 | text = text % dict(prog=self._prog) 508 | text_width = self._width - self._current_indent 509 | indent = ' ' * self._current_indent 510 | return self._fill_text(text, text_width, indent) + '\n\n' 511 | 512 | def _format_action(self, action): 513 | # determine the required width and the entry label 514 | help_position = min(self._action_max_length + 2, 515 | self._max_help_position) 516 | help_width = self._width - help_position 517 | action_width = help_position - self._current_indent - 2 518 | action_header = self._format_action_invocation(action) 519 | 520 | # ho nelp; start on same line and add a final newline 521 | if not action.help: 522 | tup = self._current_indent, '', action_header 523 | action_header = '%*s%s\n' % tup 524 | 525 | # short action name; start on the same line and pad two spaces 526 | elif len(action_header) <= action_width: 527 | tup = self._current_indent, '', action_width, action_header 528 | action_header = '%*s%-*s ' % tup 529 | indent_first = 0 530 | 531 | # long action name; start on the next line 532 | else: 533 | tup = self._current_indent, '', action_header 534 | action_header = '%*s%s\n' % tup 535 | indent_first = help_position 536 | 537 | # collect the pieces of the action help 538 | parts = [action_header] 539 | 540 | # if there was help for the action, add lines of help text 541 | if action.help: 542 | help_text = self._expand_help(action) 543 | help_lines = self._split_lines(help_text, help_width) 544 | parts.append('%*s%s\n' % (indent_first, '', help_lines[0])) 545 | for line in help_lines[1:]: 546 | parts.append('%*s%s\n' % (help_position, '', line)) 547 | 548 | # or add a newline if the description doesn't end with one 549 | elif not action_header.endswith('\n'): 550 | parts.append('\n') 551 | 552 | # if there are any sub-actions, add their help as well 553 | for subaction in self._iter_indented_subactions(action): 554 | parts.append(self._format_action(subaction)) 555 | 556 | # return a single string 557 | return self._join_parts(parts) 558 | 559 | def _format_action_invocation(self, action): 560 | if not action.option_strings: 561 | metavar, = self._metavar_formatter(action, action.dest)(1) 562 | return metavar 563 | 564 | else: 565 | parts = [] 566 | 567 | # if the Optional doesn't take a value, format is: 568 | # -s, --long 569 | if action.nargs == 0: 570 | parts.extend(action.option_strings) 571 | 572 | # if the Optional takes a value, format is: 573 | # -s ARGS, --long ARGS 574 | else: 575 | default = action.dest.upper() 576 | args_string = self._format_args(action, default) 577 | for option_string in action.option_strings: 578 | parts.append('%s %s' % (option_string, args_string)) 579 | 580 | return ', '.join(parts) 581 | 582 | def _metavar_formatter(self, action, default_metavar): 583 | if action.metavar is not None: 584 | result = action.metavar 585 | elif action.choices is not None: 586 | choice_strs = [str(choice) for choice in action.choices] 587 | result = '{%s}' % ','.join(choice_strs) 588 | else: 589 | result = default_metavar 590 | 591 | def format(tuple_size): 592 | if isinstance(result, tuple): 593 | return result 594 | else: 595 | return (result, ) * tuple_size 596 | return format 597 | 598 | def _format_args(self, action, default_metavar): 599 | get_metavar = self._metavar_formatter(action, default_metavar) 600 | if action.nargs is None: 601 | result = '%s' % get_metavar(1) 602 | elif action.nargs == OPTIONAL: 603 | result = '[%s]' % get_metavar(1) 604 | elif action.nargs == ZERO_OR_MORE: 605 | result = '[%s [%s ...]]' % get_metavar(2) 606 | elif action.nargs == ONE_OR_MORE: 607 | result = '%s [%s ...]' % get_metavar(2) 608 | elif action.nargs == REMAINDER: 609 | result = '...' 610 | elif action.nargs == PARSER: 611 | result = '%s ...' % get_metavar(1) 612 | else: 613 | formats = ['%s' for _ in range(action.nargs)] 614 | result = ' '.join(formats) % get_metavar(action.nargs) 615 | return result 616 | 617 | def _expand_help(self, action): 618 | params = dict(vars(action), prog=self._prog) 619 | for name in list(params): 620 | if params[name] is SUPPRESS: 621 | del params[name] 622 | for name in list(params): 623 | if hasattr(params[name], '__name__'): 624 | params[name] = params[name].__name__ 625 | if params.get('choices') is not None: 626 | choices_str = ', '.join([str(c) for c in params['choices']]) 627 | params['choices'] = choices_str 628 | return self._get_help_string(action) % params 629 | 630 | def _iter_indented_subactions(self, action): 631 | try: 632 | get_subactions = action._get_subactions 633 | except AttributeError: 634 | pass 635 | else: 636 | self._indent() 637 | for subaction in get_subactions(): 638 | yield subaction 639 | self._dedent() 640 | 641 | def _split_lines(self, text, width): 642 | text = self._whitespace_matcher.sub(' ', text).strip() 643 | return _textwrap.wrap(text, width) 644 | 645 | def _fill_text(self, text, width, indent): 646 | text = self._whitespace_matcher.sub(' ', text).strip() 647 | return _textwrap.fill(text, width, initial_indent=indent, 648 | subsequent_indent=indent) 649 | 650 | def _get_help_string(self, action): 651 | return action.help 652 | 653 | 654 | class RawDescriptionHelpFormatter(HelpFormatter): 655 | """Help message formatter which retains any formatting in descriptions. 656 | 657 | Only the name of this class is considered a public API. All the methods 658 | provided by the class are considered an implementation detail. 659 | """ 660 | 661 | def _fill_text(self, text, width, indent): 662 | return ''.join([indent + line for line in text.splitlines(True)]) 663 | 664 | 665 | class RawTextHelpFormatter(RawDescriptionHelpFormatter): 666 | """Help message formatter which retains formatting of all help text. 667 | 668 | Only the name of this class is considered a public API. All the methods 669 | provided by the class are considered an implementation detail. 670 | """ 671 | 672 | def _split_lines(self, text, width): 673 | return text.splitlines() 674 | 675 | 676 | class ArgumentDefaultsHelpFormatter(HelpFormatter): 677 | """Help message formatter which adds default values to argument help. 678 | 679 | Only the name of this class is considered a public API. All the methods 680 | provided by the class are considered an implementation detail. 681 | """ 682 | 683 | def _get_help_string(self, action): 684 | help = action.help 685 | if '%(default)' not in action.help: 686 | if action.default is not SUPPRESS: 687 | defaulting_nargs = [OPTIONAL, ZERO_OR_MORE] 688 | if action.option_strings or action.nargs in defaulting_nargs: 689 | help += ' (default: %(default)s)' 690 | return help 691 | 692 | 693 | # ===================== 694 | # Options and Arguments 695 | # ===================== 696 | 697 | def _get_action_name(argument): 698 | if argument is None: 699 | return None 700 | elif argument.option_strings: 701 | return '/'.join(argument.option_strings) 702 | elif argument.metavar not in (None, SUPPRESS): 703 | return argument.metavar 704 | elif argument.dest not in (None, SUPPRESS): 705 | return argument.dest 706 | else: 707 | return None 708 | 709 | 710 | class ArgumentError(Exception): 711 | """An error from creating or using an argument (optional or positional). 712 | 713 | The string value of this exception is the message, augmented with 714 | information about the argument that caused it. 715 | """ 716 | 717 | def __init__(self, argument, message): 718 | self.argument_name = _get_action_name(argument) 719 | self.message = message 720 | 721 | def __str__(self): 722 | if self.argument_name is None: 723 | format = '%(message)s' 724 | else: 725 | format = 'argument %(argument_name)s: %(message)s' 726 | return format % dict(message=self.message, 727 | argument_name=self.argument_name) 728 | 729 | 730 | class ArgumentTypeError(Exception): 731 | """An error from trying to convert a command line string to a type.""" 732 | pass 733 | 734 | 735 | # ============== 736 | # Action classes 737 | # ============== 738 | 739 | class Action(_AttributeHolder): 740 | """Information about how to convert command line strings to Python objects. 741 | 742 | Action objects are used by an ArgumentParser to represent the information 743 | needed to parse a single argument from one or more strings from the 744 | command line. The keyword arguments to the Action constructor are also 745 | all attributes of Action instances. 746 | 747 | Keyword Arguments: 748 | 749 | - option_strings -- A list of command-line option strings which 750 | should be associated with this action. 751 | 752 | - dest -- The name of the attribute to hold the created object(s) 753 | 754 | - nargs -- The number of command-line arguments that should be 755 | consumed. By default, one argument will be consumed and a single 756 | value will be produced. Other values include: 757 | - N (an integer) consumes N arguments (and produces a list) 758 | - '?' consumes zero or one arguments 759 | - '*' consumes zero or more arguments (and produces a list) 760 | - '+' consumes one or more arguments (and produces a list) 761 | Note that the difference between the default and nargs=1 is that 762 | with the default, a single value will be produced, while with 763 | nargs=1, a list containing a single value will be produced. 764 | 765 | - const -- The value to be produced if the option is specified and the 766 | option uses an action that takes no values. 767 | 768 | - default -- The value to be produced if the option is not specified. 769 | 770 | - type -- The type which the command-line arguments should be converted 771 | to, should be one of 'string', 'int', 'float', 'complex' or a 772 | callable object that accepts a single string argument. If None, 773 | 'string' is assumed. 774 | 775 | - choices -- A container of values that should be allowed. If not None, 776 | after a command-line argument has been converted to the appropriate 777 | type, an exception will be raised if it is not a member of this 778 | collection. 779 | 780 | - required -- True if the action must always be specified at the 781 | command line. This is only meaningful for optional command-line 782 | arguments. 783 | 784 | - help -- The help string describing the argument. 785 | 786 | - metavar -- The name to be used for the option's argument with the 787 | help string. If None, the 'dest' value will be used as the name. 788 | """ 789 | 790 | def __init__(self, 791 | option_strings, 792 | dest, 793 | nargs=None, 794 | const=None, 795 | default=None, 796 | type=None, 797 | choices=None, 798 | required=False, 799 | help=None, 800 | metavar=None): 801 | self.option_strings = option_strings 802 | self.dest = dest 803 | self.nargs = nargs 804 | self.const = const 805 | self.default = default 806 | self.type = type 807 | self.choices = choices 808 | self.required = required 809 | self.help = help 810 | self.metavar = metavar 811 | 812 | def _get_kwargs(self): 813 | names = [ 814 | 'option_strings', 815 | 'dest', 816 | 'nargs', 817 | 'const', 818 | 'default', 819 | 'type', 820 | 'choices', 821 | 'help', 822 | 'metavar', 823 | ] 824 | return [(name, getattr(self, name)) for name in names] 825 | 826 | def __call__(self, parser, namespace, values, option_string=None): 827 | raise NotImplementedError(_('.__call__() not defined')) 828 | 829 | 830 | class _StoreAction(Action): 831 | 832 | def __init__(self, 833 | option_strings, 834 | dest, 835 | nargs=None, 836 | const=None, 837 | default=None, 838 | type=None, 839 | choices=None, 840 | required=False, 841 | help=None, 842 | metavar=None): 843 | if nargs == 0: 844 | raise ValueError('nargs for store actions must be > 0; if you ' 845 | 'have nothing to store, actions such as store ' 846 | 'true or store const may be more appropriate') 847 | if const is not None and nargs != OPTIONAL: 848 | raise ValueError('nargs must be %r to supply const' % OPTIONAL) 849 | super(_StoreAction, self).__init__( 850 | option_strings=option_strings, 851 | dest=dest, 852 | nargs=nargs, 853 | const=const, 854 | default=default, 855 | type=type, 856 | choices=choices, 857 | required=required, 858 | help=help, 859 | metavar=metavar) 860 | 861 | def __call__(self, parser, namespace, values, option_string=None): 862 | setattr(namespace, self.dest, values) 863 | 864 | 865 | class _StoreConstAction(Action): 866 | 867 | def __init__(self, 868 | option_strings, 869 | dest, 870 | const, 871 | default=None, 872 | required=False, 873 | help=None, 874 | metavar=None): 875 | super(_StoreConstAction, self).__init__( 876 | option_strings=option_strings, 877 | dest=dest, 878 | nargs=0, 879 | const=const, 880 | default=default, 881 | required=required, 882 | help=help) 883 | 884 | def __call__(self, parser, namespace, values, option_string=None): 885 | setattr(namespace, self.dest, self.const) 886 | 887 | 888 | class _StoreTrueAction(_StoreConstAction): 889 | 890 | def __init__(self, 891 | option_strings, 892 | dest, 893 | default=False, 894 | required=False, 895 | help=None): 896 | super(_StoreTrueAction, self).__init__( 897 | option_strings=option_strings, 898 | dest=dest, 899 | const=True, 900 | default=default, 901 | required=required, 902 | help=help) 903 | 904 | 905 | class _StoreFalseAction(_StoreConstAction): 906 | 907 | def __init__(self, 908 | option_strings, 909 | dest, 910 | default=True, 911 | required=False, 912 | help=None): 913 | super(_StoreFalseAction, self).__init__( 914 | option_strings=option_strings, 915 | dest=dest, 916 | const=False, 917 | default=default, 918 | required=required, 919 | help=help) 920 | 921 | 922 | class _AppendAction(Action): 923 | 924 | def __init__(self, 925 | option_strings, 926 | dest, 927 | nargs=None, 928 | const=None, 929 | default=None, 930 | type=None, 931 | choices=None, 932 | required=False, 933 | help=None, 934 | metavar=None): 935 | if nargs == 0: 936 | raise ValueError('nargs for append actions must be > 0; if arg ' 937 | 'strings are not supplying the value to append, ' 938 | 'the append const action may be more appropriate') 939 | if const is not None and nargs != OPTIONAL: 940 | raise ValueError('nargs must be %r to supply const' % OPTIONAL) 941 | super(_AppendAction, self).__init__( 942 | option_strings=option_strings, 943 | dest=dest, 944 | nargs=nargs, 945 | const=const, 946 | default=default, 947 | type=type, 948 | choices=choices, 949 | required=required, 950 | help=help, 951 | metavar=metavar) 952 | 953 | def __call__(self, parser, namespace, values, option_string=None): 954 | items = _copy.copy(_ensure_value(namespace, self.dest, [])) 955 | items.append(values) 956 | setattr(namespace, self.dest, items) 957 | 958 | 959 | class _AppendConstAction(Action): 960 | 961 | def __init__(self, 962 | option_strings, 963 | dest, 964 | const, 965 | default=None, 966 | required=False, 967 | help=None, 968 | metavar=None): 969 | super(_AppendConstAction, self).__init__( 970 | option_strings=option_strings, 971 | dest=dest, 972 | nargs=0, 973 | const=const, 974 | default=default, 975 | required=required, 976 | help=help, 977 | metavar=metavar) 978 | 979 | def __call__(self, parser, namespace, values, option_string=None): 980 | items = _copy.copy(_ensure_value(namespace, self.dest, [])) 981 | items.append(self.const) 982 | setattr(namespace, self.dest, items) 983 | 984 | 985 | class _CountAction(Action): 986 | 987 | def __init__(self, 988 | option_strings, 989 | dest, 990 | default=None, 991 | required=False, 992 | help=None): 993 | super(_CountAction, self).__init__( 994 | option_strings=option_strings, 995 | dest=dest, 996 | nargs=0, 997 | default=default, 998 | required=required, 999 | help=help) 1000 | 1001 | def __call__(self, parser, namespace, values, option_string=None): 1002 | new_count = _ensure_value(namespace, self.dest, 0) + 1 1003 | setattr(namespace, self.dest, new_count) 1004 | 1005 | 1006 | class _HelpAction(Action): 1007 | 1008 | def __init__(self, 1009 | option_strings, 1010 | dest=SUPPRESS, 1011 | default=SUPPRESS, 1012 | help=None): 1013 | super(_HelpAction, self).__init__( 1014 | option_strings=option_strings, 1015 | dest=dest, 1016 | default=default, 1017 | nargs=0, 1018 | help=help) 1019 | 1020 | def __call__(self, parser, namespace, values, option_string=None): 1021 | parser.print_help() 1022 | parser.exit() 1023 | 1024 | 1025 | class _VersionAction(Action): 1026 | 1027 | def __init__(self, 1028 | option_strings, 1029 | version=None, 1030 | dest=SUPPRESS, 1031 | default=SUPPRESS, 1032 | help="show program's version number and exit"): 1033 | super(_VersionAction, self).__init__( 1034 | option_strings=option_strings, 1035 | dest=dest, 1036 | default=default, 1037 | nargs=0, 1038 | help=help) 1039 | self.version = version 1040 | 1041 | def __call__(self, parser, namespace, values, option_string=None): 1042 | version = self.version 1043 | if version is None: 1044 | version = parser.version 1045 | formatter = parser._get_formatter() 1046 | formatter.add_text(version) 1047 | parser.exit(message=formatter.format_help()) 1048 | 1049 | 1050 | class _SubParsersAction(Action): 1051 | 1052 | class _ChoicesPseudoAction(Action): 1053 | 1054 | def __init__(self, name, aliases, help): 1055 | metavar = dest = name 1056 | if aliases: 1057 | metavar += ' (%s)' % ', '.join(aliases) 1058 | sup = super(_SubParsersAction._ChoicesPseudoAction, self) 1059 | sup.__init__(option_strings=[], dest=dest, help=help, 1060 | metavar=metavar) 1061 | 1062 | def __init__(self, 1063 | option_strings, 1064 | prog, 1065 | parser_class, 1066 | dest=SUPPRESS, 1067 | help=None, 1068 | metavar=None): 1069 | 1070 | self._prog_prefix = prog 1071 | self._parser_class = parser_class 1072 | self._name_parser_map = {} 1073 | self._choices_actions = [] 1074 | 1075 | super(_SubParsersAction, self).__init__( 1076 | option_strings=option_strings, 1077 | dest=dest, 1078 | nargs=PARSER, 1079 | choices=self._name_parser_map, 1080 | help=help, 1081 | metavar=metavar) 1082 | 1083 | def add_parser(self, name, **kwargs): 1084 | # set prog from the existing prefix 1085 | if kwargs.get('prog') is None: 1086 | kwargs['prog'] = '%s %s' % (self._prog_prefix, name) 1087 | 1088 | aliases = kwargs.pop('aliases', ()) 1089 | 1090 | # create a pseudo-action to hold the choice help 1091 | if 'help' in kwargs: 1092 | help = kwargs.pop('help') 1093 | choice_action = self._ChoicesPseudoAction(name, aliases, help) 1094 | self._choices_actions.append(choice_action) 1095 | 1096 | # create the parser and add it to the map 1097 | parser = self._parser_class(**kwargs) 1098 | self._name_parser_map[name] = parser 1099 | 1100 | # make parser available under aliases also 1101 | for alias in aliases: 1102 | self._name_parser_map[alias] = parser 1103 | 1104 | return parser 1105 | 1106 | def _get_subactions(self): 1107 | return self._choices_actions 1108 | 1109 | def __call__(self, parser, namespace, values, option_string=None): 1110 | parser_name = values[0] 1111 | arg_strings = values[1:] 1112 | 1113 | # set the parser name if requested 1114 | if self.dest is not SUPPRESS: 1115 | setattr(namespace, self.dest, parser_name) 1116 | 1117 | # select the parser 1118 | try: 1119 | parser = self._name_parser_map[parser_name] 1120 | except KeyError: 1121 | tup = parser_name, ', '.join(self._name_parser_map) 1122 | msg = _('unknown parser %r (choices: %s)' % tup) 1123 | raise ArgumentError(self, msg) 1124 | 1125 | # parse all the remaining options into the namespace 1126 | # store any unrecognized options on the object, so that the top 1127 | # level parser can decide what to do with them 1128 | namespace, arg_strings = parser.parse_known_args(arg_strings, namespace) 1129 | if arg_strings: 1130 | vars(namespace).setdefault(_UNRECOGNIZED_ARGS_ATTR, []) 1131 | getattr(namespace, _UNRECOGNIZED_ARGS_ATTR).extend(arg_strings) 1132 | 1133 | 1134 | # ============== 1135 | # Type classes 1136 | # ============== 1137 | 1138 | class FileType(object): 1139 | """Factory for creating file object types 1140 | 1141 | Instances of FileType are typically passed as type= arguments to the 1142 | ArgumentParser add_argument() method. 1143 | 1144 | Keyword Arguments: 1145 | - mode -- A string indicating how the file is to be opened. Accepts the 1146 | same values as the builtin open() function. 1147 | - bufsize -- The file's desired buffer size. Accepts the same values as 1148 | the builtin open() function. 1149 | """ 1150 | 1151 | def __init__(self, mode='r', bufsize=None): 1152 | self._mode = mode 1153 | self._bufsize = bufsize 1154 | 1155 | def __call__(self, string): 1156 | # the special argument "-" means sys.std{in,out} 1157 | if string == '-': 1158 | if 'r' in self._mode: 1159 | return _sys.stdin 1160 | elif 'w' in self._mode: 1161 | return _sys.stdout 1162 | else: 1163 | msg = _('argument "-" with mode %r' % self._mode) 1164 | raise ValueError(msg) 1165 | 1166 | try: 1167 | # all other arguments are used as file names 1168 | if self._bufsize: 1169 | return open(string, self._mode, self._bufsize) 1170 | else: 1171 | return open(string, self._mode) 1172 | except IOError: 1173 | err = _sys.exc_info()[1] 1174 | message = _("can't open '%s': %s") 1175 | raise ArgumentTypeError(message % (string, err)) 1176 | 1177 | def __repr__(self): 1178 | args = [self._mode, self._bufsize] 1179 | args_str = ', '.join([repr(arg) for arg in args if arg is not None]) 1180 | return '%s(%s)' % (type(self).__name__, args_str) 1181 | 1182 | # =========================== 1183 | # Optional and Positional Parsing 1184 | # =========================== 1185 | 1186 | class Namespace(_AttributeHolder): 1187 | """Simple object for storing attributes. 1188 | 1189 | Implements equality by attribute names and values, and provides a simple 1190 | string representation. 1191 | """ 1192 | 1193 | def __init__(self, **kwargs): 1194 | for name in kwargs: 1195 | setattr(self, name, kwargs[name]) 1196 | 1197 | __hash__ = None 1198 | 1199 | def __eq__(self, other): 1200 | return vars(self) == vars(other) 1201 | 1202 | def __ne__(self, other): 1203 | return not (self == other) 1204 | 1205 | def __contains__(self, key): 1206 | return key in self.__dict__ 1207 | 1208 | 1209 | class _ActionsContainer(object): 1210 | 1211 | def __init__(self, 1212 | description, 1213 | prefix_chars, 1214 | argument_default, 1215 | conflict_handler): 1216 | super(_ActionsContainer, self).__init__() 1217 | 1218 | self.description = description 1219 | self.argument_default = argument_default 1220 | self.prefix_chars = prefix_chars 1221 | self.conflict_handler = conflict_handler 1222 | 1223 | # set up registries 1224 | self._registries = {} 1225 | 1226 | # register actions 1227 | self.register('action', None, _StoreAction) 1228 | self.register('action', 'store', _StoreAction) 1229 | self.register('action', 'store_const', _StoreConstAction) 1230 | self.register('action', 'store_true', _StoreTrueAction) 1231 | self.register('action', 'store_false', _StoreFalseAction) 1232 | self.register('action', 'append', _AppendAction) 1233 | self.register('action', 'append_const', _AppendConstAction) 1234 | self.register('action', 'count', _CountAction) 1235 | self.register('action', 'help', _HelpAction) 1236 | self.register('action', 'version', _VersionAction) 1237 | self.register('action', 'parsers', _SubParsersAction) 1238 | 1239 | # raise an exception if the conflict handler is invalid 1240 | self._get_handler() 1241 | 1242 | # action storage 1243 | self._actions = [] 1244 | self._option_string_actions = {} 1245 | 1246 | # groups 1247 | self._action_groups = [] 1248 | self._mutually_exclusive_groups = [] 1249 | 1250 | # defaults storage 1251 | self._defaults = {} 1252 | 1253 | # determines whether an "option" looks like a negative number 1254 | self._negative_number_matcher = _re.compile(r'^-\d+$|^-\d*\.\d+$') 1255 | 1256 | # whether or not there are any optionals that look like negative 1257 | # numbers -- uses a list so it can be shared and edited 1258 | self._has_negative_number_optionals = [] 1259 | 1260 | # ==================== 1261 | # Registration methods 1262 | # ==================== 1263 | def register(self, registry_name, value, object): 1264 | registry = self._registries.setdefault(registry_name, {}) 1265 | registry[value] = object 1266 | 1267 | def _registry_get(self, registry_name, value, default=None): 1268 | return self._registries[registry_name].get(value, default) 1269 | 1270 | # ================================== 1271 | # Namespace default accessor methods 1272 | # ================================== 1273 | def set_defaults(self, **kwargs): 1274 | self._defaults.update(kwargs) 1275 | 1276 | # if these defaults match any existing arguments, replace 1277 | # the previous default on the object with the new one 1278 | for action in self._actions: 1279 | if action.dest in kwargs: 1280 | action.default = kwargs[action.dest] 1281 | 1282 | def get_default(self, dest): 1283 | for action in self._actions: 1284 | if action.dest == dest and action.default is not None: 1285 | return action.default 1286 | return self._defaults.get(dest, None) 1287 | 1288 | 1289 | # ======================= 1290 | # Adding argument actions 1291 | # ======================= 1292 | def add_argument(self, *args, **kwargs): 1293 | """ 1294 | add_argument(dest, ..., name=value, ...) 1295 | add_argument(option_string, option_string, ..., name=value, ...) 1296 | """ 1297 | 1298 | # if no positional args are supplied or only one is supplied and 1299 | # it doesn't look like an option string, parse a positional 1300 | # argument 1301 | chars = self.prefix_chars 1302 | if not args or len(args) == 1 and args[0][0] not in chars: 1303 | if args and 'dest' in kwargs: 1304 | raise ValueError('dest supplied twice for positional argument') 1305 | kwargs = self._get_positional_kwargs(*args, **kwargs) 1306 | 1307 | # otherwise, we're adding an optional argument 1308 | else: 1309 | kwargs = self._get_optional_kwargs(*args, **kwargs) 1310 | 1311 | # if no default was supplied, use the parser-level default 1312 | if 'default' not in kwargs: 1313 | dest = kwargs['dest'] 1314 | if dest in self._defaults: 1315 | kwargs['default'] = self._defaults[dest] 1316 | elif self.argument_default is not None: 1317 | kwargs['default'] = self.argument_default 1318 | 1319 | # create the action object, and add it to the parser 1320 | action_class = self._pop_action_class(kwargs) 1321 | if not _callable(action_class): 1322 | raise ValueError('unknown action "%s"' % action_class) 1323 | action = action_class(**kwargs) 1324 | 1325 | # raise an error if the action type is not callable 1326 | type_func = self._registry_get('type', action.type, action.type) 1327 | if not _callable(type_func): 1328 | raise ValueError('%r is not callable' % type_func) 1329 | 1330 | return self._add_action(action) 1331 | 1332 | def add_argument_group(self, *args, **kwargs): 1333 | group = _ArgumentGroup(self, *args, **kwargs) 1334 | self._action_groups.append(group) 1335 | return group 1336 | 1337 | def add_mutually_exclusive_group(self, **kwargs): 1338 | group = _MutuallyExclusiveGroup(self, **kwargs) 1339 | self._mutually_exclusive_groups.append(group) 1340 | return group 1341 | 1342 | def _add_action(self, action): 1343 | # resolve any conflicts 1344 | self._check_conflict(action) 1345 | 1346 | # add to actions list 1347 | self._actions.append(action) 1348 | action.container = self 1349 | 1350 | # index the action by any option strings it has 1351 | for option_string in action.option_strings: 1352 | self._option_string_actions[option_string] = action 1353 | 1354 | # set the flag if any option strings look like negative numbers 1355 | for option_string in action.option_strings: 1356 | if self._negative_number_matcher.match(option_string): 1357 | if not self._has_negative_number_optionals: 1358 | self._has_negative_number_optionals.append(True) 1359 | 1360 | # return the created action 1361 | return action 1362 | 1363 | def _remove_action(self, action): 1364 | self._actions.remove(action) 1365 | 1366 | def _add_container_actions(self, container): 1367 | # collect groups by titles 1368 | title_group_map = {} 1369 | for group in self._action_groups: 1370 | if group.title in title_group_map: 1371 | msg = _('cannot merge actions - two groups are named %r') 1372 | raise ValueError(msg % (group.title)) 1373 | title_group_map[group.title] = group 1374 | 1375 | # map each action to its group 1376 | group_map = {} 1377 | for group in container._action_groups: 1378 | 1379 | # if a group with the title exists, use that, otherwise 1380 | # create a new group matching the container's group 1381 | if group.title not in title_group_map: 1382 | title_group_map[group.title] = self.add_argument_group( 1383 | title=group.title, 1384 | description=group.description, 1385 | conflict_handler=group.conflict_handler) 1386 | 1387 | # map the actions to their new group 1388 | for action in group._group_actions: 1389 | group_map[action] = title_group_map[group.title] 1390 | 1391 | # add container's mutually exclusive groups 1392 | # NOTE: if add_mutually_exclusive_group ever gains title= and 1393 | # description= then this code will need to be expanded as above 1394 | for group in container._mutually_exclusive_groups: 1395 | mutex_group = self.add_mutually_exclusive_group( 1396 | required=group.required) 1397 | 1398 | # map the actions to their new mutex group 1399 | for action in group._group_actions: 1400 | group_map[action] = mutex_group 1401 | 1402 | # add all actions to this container or their group 1403 | for action in container._actions: 1404 | group_map.get(action, self)._add_action(action) 1405 | 1406 | def _get_positional_kwargs(self, dest, **kwargs): 1407 | # make sure required is not specified 1408 | if 'required' in kwargs: 1409 | msg = _("'required' is an invalid argument for positionals") 1410 | raise TypeError(msg) 1411 | 1412 | # mark positional arguments as required if at least one is 1413 | # always required 1414 | if kwargs.get('nargs') not in [OPTIONAL, ZERO_OR_MORE]: 1415 | kwargs['required'] = True 1416 | if kwargs.get('nargs') == ZERO_OR_MORE and 'default' not in kwargs: 1417 | kwargs['required'] = True 1418 | 1419 | # return the keyword arguments with no option strings 1420 | return dict(kwargs, dest=dest, option_strings=[]) 1421 | 1422 | def _get_optional_kwargs(self, *args, **kwargs): 1423 | # determine short and long option strings 1424 | option_strings = [] 1425 | long_option_strings = [] 1426 | for option_string in args: 1427 | # error on strings that don't start with an appropriate prefix 1428 | if not option_string[0] in self.prefix_chars: 1429 | msg = _('invalid option string %r: ' 1430 | 'must start with a character %r') 1431 | tup = option_string, self.prefix_chars 1432 | raise ValueError(msg % tup) 1433 | 1434 | # strings starting with two prefix characters are long options 1435 | option_strings.append(option_string) 1436 | if option_string[0] in self.prefix_chars: 1437 | if len(option_string) > 1: 1438 | if option_string[1] in self.prefix_chars: 1439 | long_option_strings.append(option_string) 1440 | 1441 | # infer destination, '--foo-bar' -> 'foo_bar' and '-x' -> 'x' 1442 | dest = kwargs.pop('dest', None) 1443 | if dest is None: 1444 | if long_option_strings: 1445 | dest_option_string = long_option_strings[0] 1446 | else: 1447 | dest_option_string = option_strings[0] 1448 | dest = dest_option_string.lstrip(self.prefix_chars) 1449 | if not dest: 1450 | msg = _('dest= is required for options like %r') 1451 | raise ValueError(msg % option_string) 1452 | dest = dest.replace('-', '_') 1453 | 1454 | # return the updated keyword arguments 1455 | return dict(kwargs, dest=dest, option_strings=option_strings) 1456 | 1457 | def _pop_action_class(self, kwargs, default=None): 1458 | action = kwargs.pop('action', default) 1459 | return self._registry_get('action', action, action) 1460 | 1461 | def _get_handler(self): 1462 | # determine function from conflict handler string 1463 | handler_func_name = '_handle_conflict_%s' % self.conflict_handler 1464 | try: 1465 | return getattr(self, handler_func_name) 1466 | except AttributeError: 1467 | msg = _('invalid conflict_resolution value: %r') 1468 | raise ValueError(msg % self.conflict_handler) 1469 | 1470 | def _check_conflict(self, action): 1471 | 1472 | # find all options that conflict with this option 1473 | confl_optionals = [] 1474 | for option_string in action.option_strings: 1475 | if option_string in self._option_string_actions: 1476 | confl_optional = self._option_string_actions[option_string] 1477 | confl_optionals.append((option_string, confl_optional)) 1478 | 1479 | # resolve any conflicts 1480 | if confl_optionals: 1481 | conflict_handler = self._get_handler() 1482 | conflict_handler(action, confl_optionals) 1483 | 1484 | def _handle_conflict_error(self, action, conflicting_actions): 1485 | message = _('conflicting option string(s): %s') 1486 | conflict_string = ', '.join([option_string 1487 | for option_string, action 1488 | in conflicting_actions]) 1489 | raise ArgumentError(action, message % conflict_string) 1490 | 1491 | def _handle_conflict_resolve(self, action, conflicting_actions): 1492 | 1493 | # remove all conflicting options 1494 | for option_string, action in conflicting_actions: 1495 | 1496 | # remove the conflicting option 1497 | action.option_strings.remove(option_string) 1498 | self._option_string_actions.pop(option_string, None) 1499 | 1500 | # if the option now has no option string, remove it from the 1501 | # container holding it 1502 | if not action.option_strings: 1503 | action.container._remove_action(action) 1504 | 1505 | 1506 | class _ArgumentGroup(_ActionsContainer): 1507 | 1508 | def __init__(self, container, title=None, description=None, **kwargs): 1509 | # add any missing keyword arguments by checking the container 1510 | update = kwargs.setdefault 1511 | update('conflict_handler', container.conflict_handler) 1512 | update('prefix_chars', container.prefix_chars) 1513 | update('argument_default', container.argument_default) 1514 | super_init = super(_ArgumentGroup, self).__init__ 1515 | super_init(description=description, **kwargs) 1516 | 1517 | # group attributes 1518 | self.title = title 1519 | self._group_actions = [] 1520 | 1521 | # share most attributes with the container 1522 | self._registries = container._registries 1523 | self._actions = container._actions 1524 | self._option_string_actions = container._option_string_actions 1525 | self._defaults = container._defaults 1526 | self._has_negative_number_optionals = \ 1527 | container._has_negative_number_optionals 1528 | 1529 | def _add_action(self, action): 1530 | action = super(_ArgumentGroup, self)._add_action(action) 1531 | self._group_actions.append(action) 1532 | return action 1533 | 1534 | def _remove_action(self, action): 1535 | super(_ArgumentGroup, self)._remove_action(action) 1536 | self._group_actions.remove(action) 1537 | 1538 | 1539 | class _MutuallyExclusiveGroup(_ArgumentGroup): 1540 | 1541 | def __init__(self, container, required=False): 1542 | super(_MutuallyExclusiveGroup, self).__init__(container) 1543 | self.required = required 1544 | self._container = container 1545 | 1546 | def _add_action(self, action): 1547 | if action.required: 1548 | msg = _('mutually exclusive arguments must be optional') 1549 | raise ValueError(msg) 1550 | action = self._container._add_action(action) 1551 | self._group_actions.append(action) 1552 | return action 1553 | 1554 | def _remove_action(self, action): 1555 | self._container._remove_action(action) 1556 | self._group_actions.remove(action) 1557 | 1558 | 1559 | class ArgumentParser(_AttributeHolder, _ActionsContainer): 1560 | """Object for parsing command line strings into Python objects. 1561 | 1562 | Keyword Arguments: 1563 | - prog -- The name of the program (default: sys.argv[0]) 1564 | - usage -- A usage message (default: auto-generated from arguments) 1565 | - description -- A description of what the program does 1566 | - epilog -- Text following the argument descriptions 1567 | - parents -- Parsers whose arguments should be copied into this one 1568 | - formatter_class -- HelpFormatter class for printing help messages 1569 | - prefix_chars -- Characters that prefix optional arguments 1570 | - fromfile_prefix_chars -- Characters that prefix files containing 1571 | additional arguments 1572 | - argument_default -- The default value for all arguments 1573 | - conflict_handler -- String indicating how to handle conflicts 1574 | - add_help -- Add a -h/-help option 1575 | """ 1576 | 1577 | def __init__(self, 1578 | prog=None, 1579 | usage=None, 1580 | description=None, 1581 | epilog=None, 1582 | version=None, 1583 | parents=[], 1584 | formatter_class=HelpFormatter, 1585 | prefix_chars='-', 1586 | fromfile_prefix_chars=None, 1587 | argument_default=None, 1588 | conflict_handler='error', 1589 | add_help=True): 1590 | 1591 | if version is not None: 1592 | import warnings 1593 | warnings.warn( 1594 | """The "version" argument to ArgumentParser is deprecated. """ 1595 | """Please use """ 1596 | """"add_argument(..., action='version', version="N", ...)" """ 1597 | """instead""", DeprecationWarning) 1598 | 1599 | superinit = super(ArgumentParser, self).__init__ 1600 | superinit(description=description, 1601 | prefix_chars=prefix_chars, 1602 | argument_default=argument_default, 1603 | conflict_handler=conflict_handler) 1604 | 1605 | # default setting for prog 1606 | if prog is None: 1607 | prog = _os.path.basename(_sys.argv[0]) 1608 | 1609 | self.prog = prog 1610 | self.usage = usage 1611 | self.epilog = epilog 1612 | self.version = version 1613 | self.formatter_class = formatter_class 1614 | self.fromfile_prefix_chars = fromfile_prefix_chars 1615 | self.add_help = add_help 1616 | 1617 | add_group = self.add_argument_group 1618 | self._positionals = add_group(_('positional arguments')) 1619 | self._optionals = add_group(_('optional arguments')) 1620 | self._subparsers = None 1621 | 1622 | # register types 1623 | def identity(string): 1624 | return string 1625 | self.register('type', None, identity) 1626 | 1627 | # add help and version arguments if necessary 1628 | # (using explicit default to override global argument_default) 1629 | if '-' in prefix_chars: 1630 | default_prefix = '-' 1631 | else: 1632 | default_prefix = prefix_chars[0] 1633 | if self.add_help: 1634 | self.add_argument( 1635 | default_prefix+'h', default_prefix*2+'help', 1636 | action='help', default=SUPPRESS, 1637 | help=_('show this help message and exit')) 1638 | if self.version: 1639 | self.add_argument( 1640 | default_prefix+'v', default_prefix*2+'version', 1641 | action='version', default=SUPPRESS, 1642 | version=self.version, 1643 | help=_("show program's version number and exit")) 1644 | 1645 | # add parent arguments and defaults 1646 | for parent in parents: 1647 | self._add_container_actions(parent) 1648 | try: 1649 | defaults = parent._defaults 1650 | except AttributeError: 1651 | pass 1652 | else: 1653 | self._defaults.update(defaults) 1654 | 1655 | # ======================= 1656 | # Pretty __repr__ methods 1657 | # ======================= 1658 | def _get_kwargs(self): 1659 | names = [ 1660 | 'prog', 1661 | 'usage', 1662 | 'description', 1663 | 'version', 1664 | 'formatter_class', 1665 | 'conflict_handler', 1666 | 'add_help', 1667 | ] 1668 | return [(name, getattr(self, name)) for name in names] 1669 | 1670 | # ================================== 1671 | # Optional/Positional adding methods 1672 | # ================================== 1673 | def add_subparsers(self, **kwargs): 1674 | if self._subparsers is not None: 1675 | self.error(_('cannot have multiple subparser arguments')) 1676 | 1677 | # add the parser class to the arguments if it's not present 1678 | kwargs.setdefault('parser_class', type(self)) 1679 | 1680 | if 'title' in kwargs or 'description' in kwargs: 1681 | title = _(kwargs.pop('title', 'subcommands')) 1682 | description = _(kwargs.pop('description', None)) 1683 | self._subparsers = self.add_argument_group(title, description) 1684 | else: 1685 | self._subparsers = self._positionals 1686 | 1687 | # prog defaults to the usage message of this parser, skipping 1688 | # optional arguments and with no "usage:" prefix 1689 | if kwargs.get('prog') is None: 1690 | formatter = self._get_formatter() 1691 | positionals = self._get_positional_actions() 1692 | groups = self._mutually_exclusive_groups 1693 | formatter.add_usage(self.usage, positionals, groups, '') 1694 | kwargs['prog'] = formatter.format_help().strip() 1695 | 1696 | # create the parsers action and add it to the positionals list 1697 | parsers_class = self._pop_action_class(kwargs, 'parsers') 1698 | action = parsers_class(option_strings=[], **kwargs) 1699 | self._subparsers._add_action(action) 1700 | 1701 | # return the created parsers action 1702 | return action 1703 | 1704 | def _add_action(self, action): 1705 | if action.option_strings: 1706 | self._optionals._add_action(action) 1707 | else: 1708 | self._positionals._add_action(action) 1709 | return action 1710 | 1711 | def _get_optional_actions(self): 1712 | return [action 1713 | for action in self._actions 1714 | if action.option_strings] 1715 | 1716 | def _get_positional_actions(self): 1717 | return [action 1718 | for action in self._actions 1719 | if not action.option_strings] 1720 | 1721 | # ===================================== 1722 | # Command line argument parsing methods 1723 | # ===================================== 1724 | def parse_args(self, args=None, namespace=None): 1725 | args, argv = self.parse_known_args(args, namespace) 1726 | if argv: 1727 | msg = _('unrecognized arguments: %s') 1728 | self.error(msg % ' '.join(argv)) 1729 | return args 1730 | 1731 | def parse_known_args(self, args=None, namespace=None): 1732 | # args default to the system args 1733 | if args is None: 1734 | args = _sys.argv[1:] 1735 | 1736 | # default Namespace built from parser defaults 1737 | if namespace is None: 1738 | namespace = Namespace() 1739 | 1740 | # add any action defaults that aren't present 1741 | for action in self._actions: 1742 | if action.dest is not SUPPRESS: 1743 | if not hasattr(namespace, action.dest): 1744 | if action.default is not SUPPRESS: 1745 | setattr(namespace, action.dest, action.default) 1746 | 1747 | # add any parser defaults that aren't present 1748 | for dest in self._defaults: 1749 | if not hasattr(namespace, dest): 1750 | setattr(namespace, dest, self._defaults[dest]) 1751 | 1752 | # parse the arguments and exit if there are any errors 1753 | try: 1754 | namespace, args = self._parse_known_args(args, namespace) 1755 | if hasattr(namespace, _UNRECOGNIZED_ARGS_ATTR): 1756 | args.extend(getattr(namespace, _UNRECOGNIZED_ARGS_ATTR)) 1757 | delattr(namespace, _UNRECOGNIZED_ARGS_ATTR) 1758 | return namespace, args 1759 | except ArgumentError: 1760 | err = _sys.exc_info()[1] 1761 | self.error(str(err)) 1762 | 1763 | def _parse_known_args(self, arg_strings, namespace): 1764 | # replace arg strings that are file references 1765 | if self.fromfile_prefix_chars is not None: 1766 | arg_strings = self._read_args_from_files(arg_strings) 1767 | 1768 | # map all mutually exclusive arguments to the other arguments 1769 | # they can't occur with 1770 | action_conflicts = {} 1771 | for mutex_group in self._mutually_exclusive_groups: 1772 | group_actions = mutex_group._group_actions 1773 | for i, mutex_action in enumerate(mutex_group._group_actions): 1774 | conflicts = action_conflicts.setdefault(mutex_action, []) 1775 | conflicts.extend(group_actions[:i]) 1776 | conflicts.extend(group_actions[i + 1:]) 1777 | 1778 | # find all option indices, and determine the arg_string_pattern 1779 | # which has an 'O' if there is an option at an index, 1780 | # an 'A' if there is an argument, or a '-' if there is a '--' 1781 | option_string_indices = {} 1782 | arg_string_pattern_parts = [] 1783 | arg_strings_iter = iter(arg_strings) 1784 | for i, arg_string in enumerate(arg_strings_iter): 1785 | 1786 | # all args after -- are non-options 1787 | if arg_string == '--': 1788 | arg_string_pattern_parts.append('-') 1789 | for arg_string in arg_strings_iter: 1790 | arg_string_pattern_parts.append('A') 1791 | 1792 | # otherwise, add the arg to the arg strings 1793 | # and note the index if it was an option 1794 | else: 1795 | option_tuple = self._parse_optional(arg_string) 1796 | if option_tuple is None: 1797 | pattern = 'A' 1798 | else: 1799 | option_string_indices[i] = option_tuple 1800 | pattern = 'O' 1801 | arg_string_pattern_parts.append(pattern) 1802 | 1803 | # join the pieces together to form the pattern 1804 | arg_strings_pattern = ''.join(arg_string_pattern_parts) 1805 | 1806 | # converts arg strings to the appropriate and then takes the action 1807 | seen_actions = set() 1808 | seen_non_default_actions = set() 1809 | 1810 | def take_action(action, argument_strings, option_string=None): 1811 | seen_actions.add(action) 1812 | argument_values = self._get_values(action, argument_strings) 1813 | 1814 | # error if this argument is not allowed with other previously 1815 | # seen arguments, assuming that actions that use the default 1816 | # value don't really count as "present" 1817 | if argument_values is not action.default: 1818 | seen_non_default_actions.add(action) 1819 | for conflict_action in action_conflicts.get(action, []): 1820 | if conflict_action in seen_non_default_actions: 1821 | msg = _('not allowed with argument %s') 1822 | action_name = _get_action_name(conflict_action) 1823 | raise ArgumentError(action, msg % action_name) 1824 | 1825 | # take the action if we didn't receive a SUPPRESS value 1826 | # (e.g. from a default) 1827 | if argument_values is not SUPPRESS: 1828 | action(self, namespace, argument_values, option_string) 1829 | 1830 | # function to convert arg_strings into an optional action 1831 | def consume_optional(start_index): 1832 | 1833 | # get the optional identified at this index 1834 | option_tuple = option_string_indices[start_index] 1835 | action, option_string, explicit_arg = option_tuple 1836 | 1837 | # identify additional optionals in the same arg string 1838 | # (e.g. -xyz is the same as -x -y -z if no args are required) 1839 | match_argument = self._match_argument 1840 | action_tuples = [] 1841 | while True: 1842 | 1843 | # if we found no optional action, skip it 1844 | if action is None: 1845 | extras.append(arg_strings[start_index]) 1846 | return start_index + 1 1847 | 1848 | # if there is an explicit argument, try to match the 1849 | # optional's string arguments to only this 1850 | if explicit_arg is not None: 1851 | arg_count = match_argument(action, 'A') 1852 | 1853 | # if the action is a single-dash option and takes no 1854 | # arguments, try to parse more single-dash options out 1855 | # of the tail of the option string 1856 | chars = self.prefix_chars 1857 | if arg_count == 0 and option_string[1] not in chars: 1858 | action_tuples.append((action, [], option_string)) 1859 | char = option_string[0] 1860 | option_string = char + explicit_arg[0] 1861 | new_explicit_arg = explicit_arg[1:] or None 1862 | optionals_map = self._option_string_actions 1863 | if option_string in optionals_map: 1864 | action = optionals_map[option_string] 1865 | explicit_arg = new_explicit_arg 1866 | else: 1867 | msg = _('ignored explicit argument %r') 1868 | raise ArgumentError(action, msg % explicit_arg) 1869 | 1870 | # if the action expect exactly one argument, we've 1871 | # successfully matched the option; exit the loop 1872 | elif arg_count == 1: 1873 | stop = start_index + 1 1874 | args = [explicit_arg] 1875 | action_tuples.append((action, args, option_string)) 1876 | break 1877 | 1878 | # error if a double-dash option did not use the 1879 | # explicit argument 1880 | else: 1881 | msg = _('ignored explicit argument %r') 1882 | raise ArgumentError(action, msg % explicit_arg) 1883 | 1884 | # if there is no explicit argument, try to match the 1885 | # optional's string arguments with the following strings 1886 | # if successful, exit the loop 1887 | else: 1888 | start = start_index + 1 1889 | selected_patterns = arg_strings_pattern[start:] 1890 | arg_count = match_argument(action, selected_patterns) 1891 | stop = start + arg_count 1892 | args = arg_strings[start:stop] 1893 | action_tuples.append((action, args, option_string)) 1894 | break 1895 | 1896 | # add the Optional to the list and return the index at which 1897 | # the Optional's string args stopped 1898 | assert action_tuples 1899 | for action, args, option_string in action_tuples: 1900 | take_action(action, args, option_string) 1901 | return stop 1902 | 1903 | # the list of Positionals left to be parsed; this is modified 1904 | # by consume_positionals() 1905 | positionals = self._get_positional_actions() 1906 | 1907 | # function to convert arg_strings into positional actions 1908 | def consume_positionals(start_index): 1909 | # match as many Positionals as possible 1910 | match_partial = self._match_arguments_partial 1911 | selected_pattern = arg_strings_pattern[start_index:] 1912 | arg_counts = match_partial(positionals, selected_pattern) 1913 | 1914 | # slice off the appropriate arg strings for each Positional 1915 | # and add the Positional and its args to the list 1916 | for action, arg_count in zip(positionals, arg_counts): 1917 | args = arg_strings[start_index: start_index + arg_count] 1918 | start_index += arg_count 1919 | take_action(action, args) 1920 | 1921 | # slice off the Positionals that we just parsed and return the 1922 | # index at which the Positionals' string args stopped 1923 | positionals[:] = positionals[len(arg_counts):] 1924 | return start_index 1925 | 1926 | # consume Positionals and Optionals alternately, until we have 1927 | # passed the last option string 1928 | extras = [] 1929 | start_index = 0 1930 | if option_string_indices: 1931 | max_option_string_index = max(option_string_indices) 1932 | else: 1933 | max_option_string_index = -1 1934 | while start_index <= max_option_string_index: 1935 | 1936 | # consume any Positionals preceding the next option 1937 | next_option_string_index = min([ 1938 | index 1939 | for index in option_string_indices 1940 | if index >= start_index]) 1941 | if start_index != next_option_string_index: 1942 | positionals_end_index = consume_positionals(start_index) 1943 | 1944 | # only try to parse the next optional if we didn't consume 1945 | # the option string during the positionals parsing 1946 | if positionals_end_index > start_index: 1947 | start_index = positionals_end_index 1948 | continue 1949 | else: 1950 | start_index = positionals_end_index 1951 | 1952 | # if we consumed all the positionals we could and we're not 1953 | # at the index of an option string, there were extra arguments 1954 | if start_index not in option_string_indices: 1955 | strings = arg_strings[start_index:next_option_string_index] 1956 | extras.extend(strings) 1957 | start_index = next_option_string_index 1958 | 1959 | # consume the next optional and any arguments for it 1960 | start_index = consume_optional(start_index) 1961 | 1962 | # consume any positionals following the last Optional 1963 | stop_index = consume_positionals(start_index) 1964 | 1965 | # if we didn't consume all the argument strings, there were extras 1966 | extras.extend(arg_strings[stop_index:]) 1967 | 1968 | # if we didn't use all the Positional objects, there were too few 1969 | # arg strings supplied. 1970 | if positionals: 1971 | self.error(_('too few arguments')) 1972 | 1973 | # make sure all required actions were present, and convert defaults. 1974 | for action in self._actions: 1975 | if action not in seen_actions: 1976 | if action.required: 1977 | name = _get_action_name(action) 1978 | self.error(_('argument %s is required') % name) 1979 | else: 1980 | # Convert action default now instead of doing it before 1981 | # parsing arguments to avoid calling convert functions 1982 | # twice (which may fail) if the argument was given, but 1983 | # only if it was defined already in the namespace 1984 | if (action.default is not None and 1985 | isinstance(action.default, basestring) and 1986 | hasattr(namespace, action.dest) and 1987 | action.default is getattr(namespace, action.dest)): 1988 | setattr(namespace, action.dest, 1989 | self._get_value(action, action.default)) 1990 | 1991 | # make sure all required groups had one option present 1992 | for group in self._mutually_exclusive_groups: 1993 | if group.required: 1994 | for action in group._group_actions: 1995 | if action in seen_non_default_actions: 1996 | break 1997 | 1998 | # if no actions were used, report the error 1999 | else: 2000 | names = [_get_action_name(action) 2001 | for action in group._group_actions 2002 | if action.help is not SUPPRESS] 2003 | msg = _('one of the arguments %s is required') 2004 | self.error(msg % ' '.join(names)) 2005 | 2006 | # return the updated namespace and the extra arguments 2007 | return namespace, extras 2008 | 2009 | def _read_args_from_files(self, arg_strings): 2010 | # expand arguments referencing files 2011 | new_arg_strings = [] 2012 | for arg_string in arg_strings: 2013 | 2014 | # for regular arguments, just add them back into the list 2015 | if not arg_string or arg_string[0] not in self.fromfile_prefix_chars: 2016 | new_arg_strings.append(arg_string) 2017 | 2018 | # replace arguments referencing files with the file content 2019 | else: 2020 | try: 2021 | args_file = open(arg_string[1:]) 2022 | try: 2023 | arg_strings = [] 2024 | for arg_line in args_file.read().splitlines(): 2025 | for arg in self.convert_arg_line_to_args(arg_line): 2026 | arg_strings.append(arg) 2027 | arg_strings = self._read_args_from_files(arg_strings) 2028 | new_arg_strings.extend(arg_strings) 2029 | finally: 2030 | args_file.close() 2031 | except IOError: 2032 | err = _sys.exc_info()[1] 2033 | self.error(str(err)) 2034 | 2035 | # return the modified argument list 2036 | return new_arg_strings 2037 | 2038 | def convert_arg_line_to_args(self, arg_line): 2039 | return [arg_line] 2040 | 2041 | def _match_argument(self, action, arg_strings_pattern): 2042 | # match the pattern for this action to the arg strings 2043 | nargs_pattern = self._get_nargs_pattern(action) 2044 | match = _re.match(nargs_pattern, arg_strings_pattern) 2045 | 2046 | # raise an exception if we weren't able to find a match 2047 | if match is None: 2048 | nargs_errors = { 2049 | None: _('expected one argument'), 2050 | OPTIONAL: _('expected at most one argument'), 2051 | ONE_OR_MORE: _('expected at least one argument'), 2052 | } 2053 | default = _('expected %s argument(s)') % action.nargs 2054 | msg = nargs_errors.get(action.nargs, default) 2055 | raise ArgumentError(action, msg) 2056 | 2057 | # return the number of arguments matched 2058 | return len(match.group(1)) 2059 | 2060 | def _match_arguments_partial(self, actions, arg_strings_pattern): 2061 | # progressively shorten the actions list by slicing off the 2062 | # final actions until we find a match 2063 | result = [] 2064 | for i in range(len(actions), 0, -1): 2065 | actions_slice = actions[:i] 2066 | pattern = ''.join([self._get_nargs_pattern(action) 2067 | for action in actions_slice]) 2068 | match = _re.match(pattern, arg_strings_pattern) 2069 | if match is not None: 2070 | result.extend([len(string) for string in match.groups()]) 2071 | break 2072 | 2073 | # return the list of arg string counts 2074 | return result 2075 | 2076 | def _parse_optional(self, arg_string): 2077 | # if it's an empty string, it was meant to be a positional 2078 | if not arg_string: 2079 | return None 2080 | 2081 | # if it doesn't start with a prefix, it was meant to be positional 2082 | if not arg_string[0] in self.prefix_chars: 2083 | return None 2084 | 2085 | # if the option string is present in the parser, return the action 2086 | if arg_string in self._option_string_actions: 2087 | action = self._option_string_actions[arg_string] 2088 | return action, arg_string, None 2089 | 2090 | # if it's just a single character, it was meant to be positional 2091 | if len(arg_string) == 1: 2092 | return None 2093 | 2094 | # if the option string before the "=" is present, return the action 2095 | if '=' in arg_string: 2096 | option_string, explicit_arg = arg_string.split('=', 1) 2097 | if option_string in self._option_string_actions: 2098 | action = self._option_string_actions[option_string] 2099 | return action, option_string, explicit_arg 2100 | 2101 | # search through all possible prefixes of the option string 2102 | # and all actions in the parser for possible interpretations 2103 | option_tuples = self._get_option_tuples(arg_string) 2104 | 2105 | # if multiple actions match, the option string was ambiguous 2106 | if len(option_tuples) > 1: 2107 | options = ', '.join([option_string 2108 | for action, option_string, explicit_arg in option_tuples]) 2109 | tup = arg_string, options 2110 | self.error(_('ambiguous option: %s could match %s') % tup) 2111 | 2112 | # if exactly one action matched, this segmentation is good, 2113 | # so return the parsed action 2114 | elif len(option_tuples) == 1: 2115 | option_tuple, = option_tuples 2116 | return option_tuple 2117 | 2118 | # if it was not found as an option, but it looks like a negative 2119 | # number, it was meant to be positional 2120 | # unless there are negative-number-like options 2121 | if self._negative_number_matcher.match(arg_string): 2122 | if not self._has_negative_number_optionals: 2123 | return None 2124 | 2125 | # if it contains a space, it was meant to be a positional 2126 | if ' ' in arg_string: 2127 | return None 2128 | 2129 | # it was meant to be an optional but there is no such option 2130 | # in this parser (though it might be a valid option in a subparser) 2131 | return None, arg_string, None 2132 | 2133 | def _get_option_tuples(self, option_string): 2134 | result = [] 2135 | 2136 | # option strings starting with two prefix characters are only 2137 | # split at the '=' 2138 | chars = self.prefix_chars 2139 | if option_string[0] in chars and option_string[1] in chars: 2140 | if '=' in option_string: 2141 | option_prefix, explicit_arg = option_string.split('=', 1) 2142 | else: 2143 | option_prefix = option_string 2144 | explicit_arg = None 2145 | for option_string in self._option_string_actions: 2146 | if option_string.startswith(option_prefix): 2147 | action = self._option_string_actions[option_string] 2148 | tup = action, option_string, explicit_arg 2149 | result.append(tup) 2150 | 2151 | # single character options can be concatenated with their arguments 2152 | # but multiple character options always have to have their argument 2153 | # separate 2154 | elif option_string[0] in chars and option_string[1] not in chars: 2155 | option_prefix = option_string 2156 | explicit_arg = None 2157 | short_option_prefix = option_string[:2] 2158 | short_explicit_arg = option_string[2:] 2159 | 2160 | for option_string in self._option_string_actions: 2161 | if option_string == short_option_prefix: 2162 | action = self._option_string_actions[option_string] 2163 | tup = action, option_string, short_explicit_arg 2164 | result.append(tup) 2165 | elif option_string.startswith(option_prefix): 2166 | action = self._option_string_actions[option_string] 2167 | tup = action, option_string, explicit_arg 2168 | result.append(tup) 2169 | 2170 | # shouldn't ever get here 2171 | else: 2172 | self.error(_('unexpected option string: %s') % option_string) 2173 | 2174 | # return the collected option tuples 2175 | return result 2176 | 2177 | def _get_nargs_pattern(self, action): 2178 | # in all examples below, we have to allow for '--' args 2179 | # which are represented as '-' in the pattern 2180 | nargs = action.nargs 2181 | 2182 | # the default (None) is assumed to be a single argument 2183 | if nargs is None: 2184 | nargs_pattern = '(-*A-*)' 2185 | 2186 | # allow zero or one arguments 2187 | elif nargs == OPTIONAL: 2188 | nargs_pattern = '(-*A?-*)' 2189 | 2190 | # allow zero or more arguments 2191 | elif nargs == ZERO_OR_MORE: 2192 | nargs_pattern = '(-*[A-]*)' 2193 | 2194 | # allow one or more arguments 2195 | elif nargs == ONE_OR_MORE: 2196 | nargs_pattern = '(-*A[A-]*)' 2197 | 2198 | # allow any number of options or arguments 2199 | elif nargs == REMAINDER: 2200 | nargs_pattern = '([-AO]*)' 2201 | 2202 | # allow one argument followed by any number of options or arguments 2203 | elif nargs == PARSER: 2204 | nargs_pattern = '(-*A[-AO]*)' 2205 | 2206 | # all others should be integers 2207 | else: 2208 | nargs_pattern = '(-*%s-*)' % '-*'.join('A' * nargs) 2209 | 2210 | # if this is an optional action, -- is not allowed 2211 | if action.option_strings: 2212 | nargs_pattern = nargs_pattern.replace('-*', '') 2213 | nargs_pattern = nargs_pattern.replace('-', '') 2214 | 2215 | # return the pattern 2216 | return nargs_pattern 2217 | 2218 | # ======================== 2219 | # Value conversion methods 2220 | # ======================== 2221 | def _get_values(self, action, arg_strings): 2222 | # for everything but PARSER args, strip out '--' 2223 | if action.nargs not in [PARSER, REMAINDER]: 2224 | arg_strings = [s for s in arg_strings if s != '--'] 2225 | 2226 | # optional argument produces a default when not present 2227 | if not arg_strings and action.nargs == OPTIONAL: 2228 | if action.option_strings: 2229 | value = action.const 2230 | else: 2231 | value = action.default 2232 | if isinstance(value, basestring): 2233 | value = self._get_value(action, value) 2234 | self._check_value(action, value) 2235 | 2236 | # when nargs='*' on a positional, if there were no command-line 2237 | # args, use the default if it is anything other than None 2238 | elif (not arg_strings and action.nargs == ZERO_OR_MORE and 2239 | not action.option_strings): 2240 | if action.default is not None: 2241 | value = action.default 2242 | else: 2243 | value = arg_strings 2244 | self._check_value(action, value) 2245 | 2246 | # single argument or optional argument produces a single value 2247 | elif len(arg_strings) == 1 and action.nargs in [None, OPTIONAL]: 2248 | arg_string, = arg_strings 2249 | value = self._get_value(action, arg_string) 2250 | self._check_value(action, value) 2251 | 2252 | # REMAINDER arguments convert all values, checking none 2253 | elif action.nargs == REMAINDER: 2254 | value = [self._get_value(action, v) for v in arg_strings] 2255 | 2256 | # PARSER arguments convert all values, but check only the first 2257 | elif action.nargs == PARSER: 2258 | value = [self._get_value(action, v) for v in arg_strings] 2259 | self._check_value(action, value[0]) 2260 | 2261 | # all other types of nargs produce a list 2262 | else: 2263 | value = [self._get_value(action, v) for v in arg_strings] 2264 | for v in value: 2265 | self._check_value(action, v) 2266 | 2267 | # return the converted value 2268 | return value 2269 | 2270 | def _get_value(self, action, arg_string): 2271 | type_func = self._registry_get('type', action.type, action.type) 2272 | if not _callable(type_func): 2273 | msg = _('%r is not callable') 2274 | raise ArgumentError(action, msg % type_func) 2275 | 2276 | # convert the value to the appropriate type 2277 | try: 2278 | result = type_func(arg_string) 2279 | 2280 | # ArgumentTypeErrors indicate errors 2281 | except ArgumentTypeError: 2282 | name = getattr(action.type, '__name__', repr(action.type)) 2283 | msg = str(_sys.exc_info()[1]) 2284 | raise ArgumentError(action, msg) 2285 | 2286 | # TypeErrors or ValueErrors also indicate errors 2287 | except (TypeError, ValueError): 2288 | name = getattr(action.type, '__name__', repr(action.type)) 2289 | msg = _('invalid %s value: %r') 2290 | raise ArgumentError(action, msg % (name, arg_string)) 2291 | 2292 | # return the converted value 2293 | return result 2294 | 2295 | def _check_value(self, action, value): 2296 | # converted value must be one of the choices (if specified) 2297 | if action.choices is not None and value not in action.choices: 2298 | tup = value, ', '.join(map(repr, action.choices)) 2299 | msg = _('invalid choice: %r (choose from %s)') % tup 2300 | raise ArgumentError(action, msg) 2301 | 2302 | # ======================= 2303 | # Help-formatting methods 2304 | # ======================= 2305 | def format_usage(self): 2306 | formatter = self._get_formatter() 2307 | formatter.add_usage(self.usage, self._actions, 2308 | self._mutually_exclusive_groups) 2309 | return formatter.format_help() 2310 | 2311 | def format_help(self): 2312 | formatter = self._get_formatter() 2313 | 2314 | # usage 2315 | formatter.add_usage(self.usage, self._actions, 2316 | self._mutually_exclusive_groups) 2317 | 2318 | # description 2319 | formatter.add_text(self.description) 2320 | 2321 | # positionals, optionals and user-defined groups 2322 | for action_group in self._action_groups: 2323 | formatter.start_section(action_group.title) 2324 | formatter.add_text(action_group.description) 2325 | formatter.add_arguments(action_group._group_actions) 2326 | formatter.end_section() 2327 | 2328 | # epilog 2329 | formatter.add_text(self.epilog) 2330 | 2331 | # determine help from format above 2332 | return formatter.format_help() 2333 | 2334 | def format_version(self): 2335 | import warnings 2336 | warnings.warn( 2337 | 'The format_version method is deprecated -- the "version" ' 2338 | 'argument to ArgumentParser is no longer supported.', 2339 | DeprecationWarning) 2340 | formatter = self._get_formatter() 2341 | formatter.add_text(self.version) 2342 | return formatter.format_help() 2343 | 2344 | def _get_formatter(self): 2345 | return self.formatter_class(prog=self.prog) 2346 | 2347 | # ===================== 2348 | # Help-printing methods 2349 | # ===================== 2350 | def print_usage(self, file=None): 2351 | if file is None: 2352 | file = _sys.stdout 2353 | self._print_message(self.format_usage(), file) 2354 | 2355 | def print_help(self, file=None): 2356 | if file is None: 2357 | file = _sys.stdout 2358 | self._print_message(self.format_help(), file) 2359 | 2360 | def print_version(self, file=None): 2361 | import warnings 2362 | warnings.warn( 2363 | 'The print_version method is deprecated -- the "version" ' 2364 | 'argument to ArgumentParser is no longer supported.', 2365 | DeprecationWarning) 2366 | self._print_message(self.format_version(), file) 2367 | 2368 | def _print_message(self, message, file=None): 2369 | if message: 2370 | if file is None: 2371 | file = _sys.stderr 2372 | file.write(message) 2373 | 2374 | # =============== 2375 | # Exiting methods 2376 | # =============== 2377 | def exit(self, status=0, message=None): 2378 | if message: 2379 | self._print_message(message, _sys.stderr) 2380 | _sys.exit(status) 2381 | 2382 | def error(self, message): 2383 | """error(message: string) 2384 | 2385 | Prints a usage message incorporating the message to stderr and 2386 | exits. 2387 | 2388 | If you override this in a subclass, it should not return -- it 2389 | should either exit or raise an exception. 2390 | """ 2391 | self.print_usage(_sys.stderr) 2392 | self.exit(2, _('%s: error: %s\n') % (self.prog, message)) 2393 | -------------------------------------------------------------------------------- /doc/Makefile: -------------------------------------------------------------------------------- 1 | # Makefile for Sphinx documentation 2 | # 3 | 4 | # You can set these variables from the command line. 5 | SPHINXOPTS = 6 | SPHINXBUILD = sphinx-build 7 | PAPER = 8 | BUILDDIR = _build 9 | 10 | # Internal variables. 11 | PAPEROPT_a4 = -D latex_paper_size=a4 12 | PAPEROPT_letter = -D latex_paper_size=letter 13 | ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source 14 | 15 | .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext 16 | 17 | help: 18 | @echo "Please use \`make ' where is one of" 19 | @echo " html to make standalone HTML files" 20 | @echo " dirhtml to make HTML files named index.html in directories" 21 | @echo " singlehtml to make a single large HTML file" 22 | @echo " pickle to make pickle files" 23 | @echo " json to make JSON files" 24 | @echo " htmlhelp to make HTML files and a HTML help project" 25 | @echo " qthelp to make HTML files and a qthelp project" 26 | @echo " devhelp to make HTML files and a Devhelp project" 27 | @echo " epub to make an epub" 28 | @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" 29 | @echo " latexpdf to make LaTeX files and run them through pdflatex" 30 | @echo " text to make text files" 31 | @echo " man to make manual pages" 32 | @echo " texinfo to make Texinfo files" 33 | @echo " info to make Texinfo files and run them through makeinfo" 34 | @echo " gettext to make PO message catalogs" 35 | @echo " changes to make an overview of all changed/added/deprecated items" 36 | @echo " linkcheck to check all external links for integrity" 37 | @echo " doctest to run all doctests embedded in the documentation (if enabled)" 38 | 39 | clean: 40 | -rm -rf $(BUILDDIR)/* 41 | 42 | html: 43 | $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html 44 | @echo 45 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." 46 | 47 | dirhtml: 48 | $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml 49 | @echo 50 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." 51 | 52 | singlehtml: 53 | $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml 54 | @echo 55 | @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." 56 | 57 | pickle: 58 | $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle 59 | @echo 60 | @echo "Build finished; now you can process the pickle files." 61 | 62 | json: 63 | $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json 64 | @echo 65 | @echo "Build finished; now you can process the JSON files." 66 | 67 | htmlhelp: 68 | $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp 69 | @echo 70 | @echo "Build finished; now you can run HTML Help Workshop with the" \ 71 | ".hhp project file in $(BUILDDIR)/htmlhelp." 72 | 73 | qthelp: 74 | $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp 75 | @echo 76 | @echo "Build finished; now you can run "qcollectiongenerator" with the" \ 77 | ".qhcp project file in $(BUILDDIR)/qthelp, like this:" 78 | @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/argparse.qhcp" 79 | @echo "To view the help file:" 80 | @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/argparse.qhc" 81 | 82 | devhelp: 83 | $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp 84 | @echo 85 | @echo "Build finished." 86 | @echo "To view the help file:" 87 | @echo "# mkdir -p $$HOME/.local/share/devhelp/argparse" 88 | @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/argparse" 89 | @echo "# devhelp" 90 | 91 | epub: 92 | $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub 93 | @echo 94 | @echo "Build finished. The epub file is in $(BUILDDIR)/epub." 95 | 96 | latex: 97 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 98 | @echo 99 | @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." 100 | @echo "Run \`make' in that directory to run these through (pdf)latex" \ 101 | "(use \`make latexpdf' here to do that automatically)." 102 | 103 | latexpdf: 104 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 105 | @echo "Running LaTeX files through pdflatex..." 106 | make -C $(BUILDDIR)/latex all-pdf 107 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 108 | 109 | text: 110 | $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text 111 | @echo 112 | @echo "Build finished. The text files are in $(BUILDDIR)/text." 113 | 114 | man: 115 | $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man 116 | @echo 117 | @echo "Build finished. The manual pages are in $(BUILDDIR)/man." 118 | 119 | texinfo: 120 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 121 | @echo 122 | @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." 123 | @echo "Run \`make' in that directory to run these through makeinfo" \ 124 | "(use \`make info' here to do that automatically)." 125 | 126 | info: 127 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 128 | @echo "Running Texinfo files through makeinfo..." 129 | make -C $(BUILDDIR)/texinfo info 130 | @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." 131 | 132 | gettext: 133 | $(SPHINXBUILD) -b gettext $(ALLSPHINXOPTS) $(BUILDDIR)/locale 134 | @echo 135 | @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." 136 | 137 | changes: 138 | $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes 139 | @echo 140 | @echo "The overview file is in $(BUILDDIR)/changes." 141 | 142 | linkcheck: 143 | $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck 144 | @echo 145 | @echo "Link check complete; look for any errors in the above output " \ 146 | "or in $(BUILDDIR)/linkcheck/output.txt." 147 | 148 | doctest: 149 | $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest 150 | @echo "Testing of doctests in the sources finished, look at the " \ 151 | "results in $(BUILDDIR)/doctest/output.txt." 152 | -------------------------------------------------------------------------------- /doc/make.bat: -------------------------------------------------------------------------------- 1 | @ECHO OFF 2 | 3 | REM Command file for Sphinx documentation 4 | 5 | if "%SPHINXBUILD%" == "" ( 6 | set SPHINXBUILD=sphinx-build 7 | ) 8 | set BUILDDIR=_build 9 | set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% source 10 | if NOT "%PAPER%" == "" ( 11 | set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS% 12 | ) 13 | 14 | if "%1" == "" goto help 15 | 16 | if "%1" == "help" ( 17 | :help 18 | echo.Please use `make ^` where ^ is one of 19 | echo. html to make standalone HTML files 20 | echo. dirhtml to make HTML files named index.html in directories 21 | echo. singlehtml to make a single large HTML file 22 | echo. pickle to make pickle files 23 | echo. json to make JSON files 24 | echo. htmlhelp to make HTML files and a HTML help project 25 | echo. qthelp to make HTML files and a qthelp project 26 | echo. devhelp to make HTML files and a Devhelp project 27 | echo. epub to make an epub 28 | echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter 29 | echo. text to make text files 30 | echo. man to make manual pages 31 | echo. texinfo to make Texinfo files 32 | echo. gettext to make PO message catalogs 33 | echo. changes to make an overview over all changed/added/deprecated items 34 | echo. linkcheck to check all external links for integrity 35 | echo. doctest to run all doctests embedded in the documentation if enabled 36 | goto end 37 | ) 38 | 39 | if "%1" == "clean" ( 40 | for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i 41 | del /q /s %BUILDDIR%\* 42 | goto end 43 | ) 44 | 45 | if "%1" == "html" ( 46 | %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html 47 | if errorlevel 1 exit /b 1 48 | echo. 49 | echo.Build finished. The HTML pages are in %BUILDDIR%/html. 50 | goto end 51 | ) 52 | 53 | if "%1" == "dirhtml" ( 54 | %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml 55 | if errorlevel 1 exit /b 1 56 | echo. 57 | echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml. 58 | goto end 59 | ) 60 | 61 | if "%1" == "singlehtml" ( 62 | %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml 63 | if errorlevel 1 exit /b 1 64 | echo. 65 | echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml. 66 | goto end 67 | ) 68 | 69 | if "%1" == "pickle" ( 70 | %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle 71 | if errorlevel 1 exit /b 1 72 | echo. 73 | echo.Build finished; now you can process the pickle files. 74 | goto end 75 | ) 76 | 77 | if "%1" == "json" ( 78 | %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json 79 | if errorlevel 1 exit /b 1 80 | echo. 81 | echo.Build finished; now you can process the JSON files. 82 | goto end 83 | ) 84 | 85 | if "%1" == "htmlhelp" ( 86 | %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp 87 | if errorlevel 1 exit /b 1 88 | echo. 89 | echo.Build finished; now you can run HTML Help Workshop with the ^ 90 | .hhp project file in %BUILDDIR%/htmlhelp. 91 | goto end 92 | ) 93 | 94 | if "%1" == "qthelp" ( 95 | %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp 96 | if errorlevel 1 exit /b 1 97 | echo. 98 | echo.Build finished; now you can run "qcollectiongenerator" with the ^ 99 | .qhcp project file in %BUILDDIR%/qthelp, like this: 100 | echo.^> qcollectiongenerator %BUILDDIR%\qthelp\argparse.qhcp 101 | echo.To view the help file: 102 | echo.^> assistant -collectionFile %BUILDDIR%\qthelp\argparse.ghc 103 | goto end 104 | ) 105 | 106 | if "%1" == "devhelp" ( 107 | %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp 108 | if errorlevel 1 exit /b 1 109 | echo. 110 | echo.Build finished. 111 | goto end 112 | ) 113 | 114 | if "%1" == "epub" ( 115 | %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub 116 | if errorlevel 1 exit /b 1 117 | echo. 118 | echo.Build finished. The epub file is in %BUILDDIR%/epub. 119 | goto end 120 | ) 121 | 122 | if "%1" == "latex" ( 123 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex 124 | if errorlevel 1 exit /b 1 125 | echo. 126 | echo.Build finished; the LaTeX files are in %BUILDDIR%/latex. 127 | goto end 128 | ) 129 | 130 | if "%1" == "text" ( 131 | %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text 132 | if errorlevel 1 exit /b 1 133 | echo. 134 | echo.Build finished. The text files are in %BUILDDIR%/text. 135 | goto end 136 | ) 137 | 138 | if "%1" == "man" ( 139 | %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man 140 | if errorlevel 1 exit /b 1 141 | echo. 142 | echo.Build finished. The manual pages are in %BUILDDIR%/man. 143 | goto end 144 | ) 145 | 146 | if "%1" == "texinfo" ( 147 | %SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo 148 | if errorlevel 1 exit /b 1 149 | echo. 150 | echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo. 151 | goto end 152 | ) 153 | 154 | if "%1" == "gettext" ( 155 | %SPHINXBUILD% -b gettext %ALLSPHINXOPTS% %BUILDDIR%/locale 156 | if errorlevel 1 exit /b 1 157 | echo. 158 | echo.Build finished. The message catalogs are in %BUILDDIR%/locale. 159 | goto end 160 | ) 161 | 162 | if "%1" == "changes" ( 163 | %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes 164 | if errorlevel 1 exit /b 1 165 | echo. 166 | echo.The overview file is in %BUILDDIR%/changes. 167 | goto end 168 | ) 169 | 170 | if "%1" == "linkcheck" ( 171 | %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck 172 | if errorlevel 1 exit /b 1 173 | echo. 174 | echo.Link check complete; look for any errors in the above output ^ 175 | or in %BUILDDIR%/linkcheck/output.txt. 176 | goto end 177 | ) 178 | 179 | if "%1" == "doctest" ( 180 | %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest 181 | if errorlevel 1 exit /b 1 182 | echo. 183 | echo.Testing of doctests in the sources finished, look at the ^ 184 | results in %BUILDDIR%/doctest/output.txt. 185 | goto end 186 | ) 187 | 188 | :end 189 | -------------------------------------------------------------------------------- /doc/source/Python-License.txt: -------------------------------------------------------------------------------- 1 | A. HISTORY OF THE SOFTWARE 2 | ========================== 3 | 4 | Python was created in the early 1990s by Guido van Rossum at Stichting 5 | Mathematisch Centrum (CWI, see http://www.cwi.nl) in the Netherlands 6 | as a successor of a language called ABC. Guido remains Python's 7 | principal author, although it includes many contributions from others. 8 | 9 | In 1995, Guido continued his work on Python at the Corporation for 10 | National Research Initiatives (CNRI, see http://www.cnri.reston.va.us) 11 | in Reston, Virginia where he released several versions of the 12 | software. 13 | 14 | In May 2000, Guido and the Python core development team moved to 15 | BeOpen.com to form the BeOpen PythonLabs team. In October of the same 16 | year, the PythonLabs team moved to Digital Creations (now Zope 17 | Corporation, see http://www.zope.com). In 2001, the Python Software 18 | Foundation (PSF, see http://www.python.org/psf/) was formed, a 19 | non-profit organization created specifically to own Python-related 20 | Intellectual Property. Zope Corporation is a sponsoring member of 21 | the PSF. 22 | 23 | All Python releases are Open Source (see http://www.opensource.org for 24 | the Open Source Definition). Historically, most, but not all, Python 25 | releases have also been GPL-compatible; the table below summarizes 26 | the various releases. 27 | 28 | Release Derived Year Owner GPL- 29 | from compatible? (1) 30 | 31 | 0.9.0 thru 1.2 1991-1995 CWI yes 32 | 1.3 thru 1.5.2 1.2 1995-1999 CNRI yes 33 | 1.6 1.5.2 2000 CNRI no 34 | 2.0 1.6 2000 BeOpen.com no 35 | 1.6.1 1.6 2001 CNRI yes (2) 36 | 2.1 2.0+1.6.1 2001 PSF no 37 | 2.0.1 2.0+1.6.1 2001 PSF yes 38 | 2.1.1 2.1+2.0.1 2001 PSF yes 39 | 2.2 2.1.1 2001 PSF yes 40 | 2.1.2 2.1.1 2002 PSF yes 41 | 2.1.3 2.1.2 2002 PSF yes 42 | 2.2.1 2.2 2002 PSF yes 43 | 2.2.2 2.2.1 2002 PSF yes 44 | 2.2.3 2.2.2 2003 PSF yes 45 | 2.3 2.2.2 2002-2003 PSF yes 46 | 2.3.1 2.3 2002-2003 PSF yes 47 | 2.3.2 2.3.1 2002-2003 PSF yes 48 | 2.3.3 2.3.2 2002-2003 PSF yes 49 | 2.3.4 2.3.3 2004 PSF yes 50 | 2.3.5 2.3.4 2005 PSF yes 51 | 2.4 2.3 2004 PSF yes 52 | 2.4.1 2.4 2005 PSF yes 53 | 2.4.2 2.4.1 2005 PSF yes 54 | 2.4.3 2.4.2 2006 PSF yes 55 | 2.4.4 2.4.3 2006 PSF yes 56 | 2.5 2.4 2006 PSF yes 57 | 2.5.1 2.5 2007 PSF yes 58 | 2.5.2 2.5.1 2008 PSF yes 59 | 2.5.3 2.5.2 2008 PSF yes 60 | 2.6 2.5 2008 PSF yes 61 | 2.6.1 2.6 2008 PSF yes 62 | 2.6.2 2.6.1 2009 PSF yes 63 | 2.6.3 2.6.2 2009 PSF yes 64 | 2.6.4 2.6.3 2009 PSF yes 65 | 2.6.5 2.6.4 2010 PSF yes 66 | 2.7 2.6 2010 PSF yes 67 | 68 | Footnotes: 69 | 70 | (1) GPL-compatible doesn't mean that we're distributing Python under 71 | the GPL. All Python licenses, unlike the GPL, let you distribute 72 | a modified version without making your changes open source. The 73 | GPL-compatible licenses make it possible to combine Python with 74 | other software that is released under the GPL; the others don't. 75 | 76 | (2) According to Richard Stallman, 1.6.1 is not GPL-compatible, 77 | because its license has a choice of law clause. According to 78 | CNRI, however, Stallman's lawyer has told CNRI's lawyer that 1.6.1 79 | is "not incompatible" with the GPL. 80 | 81 | Thanks to the many outside volunteers who have worked under Guido's 82 | direction to make these releases possible. 83 | 84 | 85 | B. TERMS AND CONDITIONS FOR ACCESSING OR OTHERWISE USING PYTHON 86 | =============================================================== 87 | 88 | PYTHON SOFTWARE FOUNDATION LICENSE VERSION 2 89 | -------------------------------------------- 90 | 91 | 1. This LICENSE AGREEMENT is between the Python Software Foundation 92 | ("PSF"), and the Individual or Organization ("Licensee") accessing and 93 | otherwise using this software ("Python") in source or binary form and 94 | its associated documentation. 95 | 96 | 2. Subject to the terms and conditions of this License Agreement, PSF hereby 97 | grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce, 98 | analyze, test, perform and/or display publicly, prepare derivative works, 99 | distribute, and otherwise use Python alone or in any derivative version, 100 | provided, however, that PSF's License Agreement and PSF's notice of copyright, 101 | i.e., "Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 102 | Python Software Foundation; All Rights Reserved" are retained in Python alone or 103 | in any derivative version prepared by Licensee. 104 | 105 | 3. In the event Licensee prepares a derivative work that is based on 106 | or incorporates Python or any part thereof, and wants to make 107 | the derivative work available to others as provided herein, then 108 | Licensee hereby agrees to include in any such work a brief summary of 109 | the changes made to Python. 110 | 111 | 4. PSF is making Python available to Licensee on an "AS IS" 112 | basis. PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR 113 | IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND 114 | DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS 115 | FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON WILL NOT 116 | INFRINGE ANY THIRD PARTY RIGHTS. 117 | 118 | 5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON 119 | FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS 120 | A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON, 121 | OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF. 122 | 123 | 6. This License Agreement will automatically terminate upon a material 124 | breach of its terms and conditions. 125 | 126 | 7. Nothing in this License Agreement shall be deemed to create any 127 | relationship of agency, partnership, or joint venture between PSF and 128 | Licensee. This License Agreement does not grant permission to use PSF 129 | trademarks or trade name in a trademark sense to endorse or promote 130 | products or services of Licensee, or any third party. 131 | 132 | 8. By copying, installing or otherwise using Python, Licensee 133 | agrees to be bound by the terms and conditions of this License 134 | Agreement. 135 | 136 | 137 | BEOPEN.COM LICENSE AGREEMENT FOR PYTHON 2.0 138 | ------------------------------------------- 139 | 140 | BEOPEN PYTHON OPEN SOURCE LICENSE AGREEMENT VERSION 1 141 | 142 | 1. This LICENSE AGREEMENT is between BeOpen.com ("BeOpen"), having an 143 | office at 160 Saratoga Avenue, Santa Clara, CA 95051, and the 144 | Individual or Organization ("Licensee") accessing and otherwise using 145 | this software in source or binary form and its associated 146 | documentation ("the Software"). 147 | 148 | 2. Subject to the terms and conditions of this BeOpen Python License 149 | Agreement, BeOpen hereby grants Licensee a non-exclusive, 150 | royalty-free, world-wide license to reproduce, analyze, test, perform 151 | and/or display publicly, prepare derivative works, distribute, and 152 | otherwise use the Software alone or in any derivative version, 153 | provided, however, that the BeOpen Python License is retained in the 154 | Software, alone or in any derivative version prepared by Licensee. 155 | 156 | 3. BeOpen is making the Software available to Licensee on an "AS IS" 157 | basis. BEOPEN MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR 158 | IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, BEOPEN MAKES NO AND 159 | DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS 160 | FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF THE SOFTWARE WILL NOT 161 | INFRINGE ANY THIRD PARTY RIGHTS. 162 | 163 | 4. BEOPEN SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF THE 164 | SOFTWARE FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS 165 | AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THE SOFTWARE, OR ANY 166 | DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF. 167 | 168 | 5. This License Agreement will automatically terminate upon a material 169 | breach of its terms and conditions. 170 | 171 | 6. This License Agreement shall be governed by and interpreted in all 172 | respects by the law of the State of California, excluding conflict of 173 | law provisions. Nothing in this License Agreement shall be deemed to 174 | create any relationship of agency, partnership, or joint venture 175 | between BeOpen and Licensee. This License Agreement does not grant 176 | permission to use BeOpen trademarks or trade names in a trademark 177 | sense to endorse or promote products or services of Licensee, or any 178 | third party. As an exception, the "BeOpen Python" logos available at 179 | http://www.pythonlabs.com/logos.html may be used according to the 180 | permissions granted on that web page. 181 | 182 | 7. By copying, installing or otherwise using the software, Licensee 183 | agrees to be bound by the terms and conditions of this License 184 | Agreement. 185 | 186 | 187 | CNRI LICENSE AGREEMENT FOR PYTHON 1.6.1 188 | --------------------------------------- 189 | 190 | 1. This LICENSE AGREEMENT is between the Corporation for National 191 | Research Initiatives, having an office at 1895 Preston White Drive, 192 | Reston, VA 20191 ("CNRI"), and the Individual or Organization 193 | ("Licensee") accessing and otherwise using Python 1.6.1 software in 194 | source or binary form and its associated documentation. 195 | 196 | 2. Subject to the terms and conditions of this License Agreement, CNRI 197 | hereby grants Licensee a nonexclusive, royalty-free, world-wide 198 | license to reproduce, analyze, test, perform and/or display publicly, 199 | prepare derivative works, distribute, and otherwise use Python 1.6.1 200 | alone or in any derivative version, provided, however, that CNRI's 201 | License Agreement and CNRI's notice of copyright, i.e., "Copyright (c) 202 | 1995-2001 Corporation for National Research Initiatives; All Rights 203 | Reserved" are retained in Python 1.6.1 alone or in any derivative 204 | version prepared by Licensee. Alternately, in lieu of CNRI's License 205 | Agreement, Licensee may substitute the following text (omitting the 206 | quotes): "Python 1.6.1 is made available subject to the terms and 207 | conditions in CNRI's License Agreement. This Agreement together with 208 | Python 1.6.1 may be located on the Internet using the following 209 | unique, persistent identifier (known as a handle): 1895.22/1013. This 210 | Agreement may also be obtained from a proxy server on the Internet 211 | using the following URL: http://hdl.handle.net/1895.22/1013". 212 | 213 | 3. In the event Licensee prepares a derivative work that is based on 214 | or incorporates Python 1.6.1 or any part thereof, and wants to make 215 | the derivative work available to others as provided herein, then 216 | Licensee hereby agrees to include in any such work a brief summary of 217 | the changes made to Python 1.6.1. 218 | 219 | 4. CNRI is making Python 1.6.1 available to Licensee on an "AS IS" 220 | basis. CNRI MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR 221 | IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, CNRI MAKES NO AND 222 | DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS 223 | FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON 1.6.1 WILL NOT 224 | INFRINGE ANY THIRD PARTY RIGHTS. 225 | 226 | 5. CNRI SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON 227 | 1.6.1 FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS 228 | A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON 1.6.1, 229 | OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF. 230 | 231 | 6. This License Agreement will automatically terminate upon a material 232 | breach of its terms and conditions. 233 | 234 | 7. This License Agreement shall be governed by the federal 235 | intellectual property law of the United States, including without 236 | limitation the federal copyright law, and, to the extent such 237 | U.S. federal law does not apply, by the law of the Commonwealth of 238 | Virginia, excluding Virginia's conflict of law provisions. 239 | Notwithstanding the foregoing, with regard to derivative works based 240 | on Python 1.6.1 that incorporate non-separable material that was 241 | previously distributed under the GNU General Public License (GPL), the 242 | law of the Commonwealth of Virginia shall govern this License 243 | Agreement only as to issues arising under or with respect to 244 | Paragraphs 4, 5, and 7 of this License Agreement. Nothing in this 245 | License Agreement shall be deemed to create any relationship of 246 | agency, partnership, or joint venture between CNRI and Licensee. This 247 | License Agreement does not grant permission to use CNRI trademarks or 248 | trade name in a trademark sense to endorse or promote products or 249 | services of Licensee, or any third party. 250 | 251 | 8. By clicking on the "ACCEPT" button where indicated, or by copying, 252 | installing or otherwise using Python 1.6.1, Licensee agrees to be 253 | bound by the terms and conditions of this License Agreement. 254 | 255 | ACCEPT 256 | 257 | 258 | CWI LICENSE AGREEMENT FOR PYTHON 0.9.0 THROUGH 1.2 259 | -------------------------------------------------- 260 | 261 | Copyright (c) 1991 - 1995, Stichting Mathematisch Centrum Amsterdam, 262 | The Netherlands. All rights reserved. 263 | 264 | Permission to use, copy, modify, and distribute this software and its 265 | documentation for any purpose and without fee is hereby granted, 266 | provided that the above copyright notice appear in all copies and that 267 | both that copyright notice and this permission notice appear in 268 | supporting documentation, and that the name of Stichting Mathematisch 269 | Centrum or CWI not be used in advertising or publicity pertaining to 270 | distribution of the software without specific, written prior 271 | permission. 272 | 273 | STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO 274 | THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND 275 | FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLE 276 | FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES 277 | WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN 278 | ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT 279 | OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. 280 | -------------------------------------------------------------------------------- /doc/source/argparse.rst: -------------------------------------------------------------------------------- 1 | :mod:`argparse` --- Parser for command line options, arguments and sub-commands 2 | =============================================================================== 3 | 4 | .. module:: argparse 5 | :synopsis: Command-line option and argument parsing library. 6 | .. moduleauthor:: Steven Bethard 7 | .. versionadded:: 2.7 8 | .. sectionauthor:: Steven Bethard 9 | 10 | 11 | The :mod:`argparse` module makes it easy to write user friendly command line 12 | interfaces. The program defines what arguments it requires, and :mod:`argparse` 13 | will figure out how to parse those out of :data:`sys.argv`. The :mod:`argparse` 14 | module also automatically generates help and usage messages and issues errors 15 | when users give the program invalid arguments. 16 | 17 | 18 | Example 19 | ------- 20 | 21 | The following code is a Python program that takes a list of integers and 22 | produces either the sum or the max:: 23 | 24 | import argparse 25 | 26 | parser = argparse.ArgumentParser(description='Process some integers.') 27 | parser.add_argument('integers', metavar='N', type=int, nargs='+', 28 | help='an integer for the accumulator') 29 | parser.add_argument('--sum', dest='accumulate', action='store_const', 30 | const=sum, default=max, 31 | help='sum the integers (default: find the max)') 32 | 33 | args = parser.parse_args() 34 | print args.accumulate(args.integers) 35 | 36 | Assuming the Python code above is saved into a file called ``prog.py``, it can 37 | be run at the command line and provides useful help messages:: 38 | 39 | $ prog.py -h 40 | usage: prog.py [-h] [--sum] N [N ...] 41 | 42 | Process some integers. 43 | 44 | positional arguments: 45 | N an integer for the accumulator 46 | 47 | optional arguments: 48 | -h, --help show this help message and exit 49 | --sum sum the integers (default: find the max) 50 | 51 | When run with the appropriate arguments, it prints either the sum or the max of 52 | the command-line integers:: 53 | 54 | $ prog.py 1 2 3 4 55 | 4 56 | 57 | $ prog.py 1 2 3 4 --sum 58 | 10 59 | 60 | If invalid arguments are passed in, it will issue an error:: 61 | 62 | $ prog.py a b c 63 | usage: prog.py [-h] [--sum] N [N ...] 64 | prog.py: error: argument N: invalid int value: 'a' 65 | 66 | The following sections walk you through this example. 67 | 68 | 69 | Creating a parser 70 | ^^^^^^^^^^^^^^^^^ 71 | 72 | The first step in using the :mod:`argparse` is creating an 73 | :class:`ArgumentParser` object:: 74 | 75 | >>> parser = argparse.ArgumentParser(description='Process some integers.') 76 | 77 | The :class:`ArgumentParser` object will hold all the information necessary to 78 | parse the command line into python data types. 79 | 80 | 81 | Adding arguments 82 | ^^^^^^^^^^^^^^^^ 83 | 84 | Filling an :class:`ArgumentParser` with information about program arguments is 85 | done by making calls to the :meth:`~ArgumentParser.add_argument` method. 86 | Generally, these calls tell the :class:`ArgumentParser` how to take the strings 87 | on the command line and turn them into objects. This information is stored and 88 | used when :meth:`~ArgumentParser.parse_args` is called. For example:: 89 | 90 | >>> parser.add_argument('integers', metavar='N', type=int, nargs='+', 91 | ... help='an integer for the accumulator') 92 | >>> parser.add_argument('--sum', dest='accumulate', action='store_const', 93 | ... const=sum, default=max, 94 | ... help='sum the integers (default: find the max)') 95 | 96 | Later, calling :meth:`parse_args` will return an object with 97 | two attributes, ``integers`` and ``accumulate``. The ``integers`` attribute 98 | will be a list of one or more ints, and the ``accumulate`` attribute will be 99 | either the :func:`sum` function, if ``--sum`` was specified at the command line, 100 | or the :func:`max` function if it was not. 101 | 102 | 103 | Parsing arguments 104 | ^^^^^^^^^^^^^^^^^ 105 | 106 | :class:`ArgumentParser` parses args through the 107 | :meth:`~ArgumentParser.parse_args` method. This will inspect the command-line, 108 | convert each arg to the appropriate type and then invoke the appropriate action. 109 | In most cases, this means a simple namespace object will be built up from 110 | attributes parsed out of the command-line:: 111 | 112 | >>> parser.parse_args(['--sum', '7', '-1', '42']) 113 | Namespace(accumulate=, integers=[7, -1, 42]) 114 | 115 | In a script, :meth:`~ArgumentParser.parse_args` will typically be called with no 116 | arguments, and the :class:`ArgumentParser` will automatically determine the 117 | command-line args from :data:`sys.argv`. 118 | 119 | 120 | ArgumentParser objects 121 | ---------------------- 122 | 123 | .. class:: ArgumentParser([description], [epilog], [prog], [usage], [add_help], [argument_default], [parents], [prefix_chars], [conflict_handler], [formatter_class]) 124 | 125 | Create a new :class:`ArgumentParser` object. Each parameter has its own more 126 | detailed description below, but in short they are: 127 | 128 | * description_ - Text to display before the argument help. 129 | 130 | * epilog_ - Text to display after the argument help. 131 | 132 | * add_help_ - Add a -h/--help option to the parser. (default: ``True``) 133 | 134 | * argument_default_ - Set the global default value for arguments. 135 | (default: ``None``) 136 | 137 | * parents_ - A list of :class:`ArgumentParser` objects whose arguments should 138 | also be included. 139 | 140 | * prefix_chars_ - The set of characters that prefix optional arguments. 141 | (default: '-') 142 | 143 | * fromfile_prefix_chars_ - The set of characters that prefix files from 144 | which additional arguments should be read. (default: ``None``) 145 | 146 | * formatter_class_ - A class for customizing the help output. 147 | 148 | * conflict_handler_ - Usually unnecessary, defines strategy for resolving 149 | conflicting optionals. 150 | 151 | * prog_ - The name of the program (default: 152 | :data:`sys.argv[0]`) 153 | 154 | * usage_ - The string describing the program usage (default: generated) 155 | 156 | The following sections describe how each of these are used. 157 | 158 | 159 | description 160 | ^^^^^^^^^^^ 161 | 162 | Most calls to the :class:`ArgumentParser` constructor will use the 163 | ``description=`` keyword argument. This argument gives a brief description of 164 | what the program does and how it works. In help messages, the description is 165 | displayed between the command-line usage string and the help messages for the 166 | various arguments:: 167 | 168 | >>> parser = argparse.ArgumentParser(description='A foo that bars') 169 | >>> parser.print_help() 170 | usage: argparse.py [-h] 171 | 172 | A foo that bars 173 | 174 | optional arguments: 175 | -h, --help show this help message and exit 176 | 177 | By default, the description will be line-wrapped so that it fits within the 178 | given space. To change this behavior, see the formatter_class_ argument. 179 | 180 | 181 | epilog 182 | ^^^^^^ 183 | 184 | Some programs like to display additional description of the program after the 185 | description of the arguments. Such text can be specified using the ``epilog=`` 186 | argument to :class:`ArgumentParser`:: 187 | 188 | >>> parser = argparse.ArgumentParser( 189 | ... description='A foo that bars', 190 | ... epilog="And that's how you'd foo a bar") 191 | >>> parser.print_help() 192 | usage: argparse.py [-h] 193 | 194 | A foo that bars 195 | 196 | optional arguments: 197 | -h, --help show this help message and exit 198 | 199 | And that's how you'd foo a bar 200 | 201 | As with the description_ argument, the ``epilog=`` text is by default 202 | line-wrapped, but this behavior can be adjusted with the formatter_class_ 203 | argument to :class:`ArgumentParser`. 204 | 205 | 206 | add_help 207 | ^^^^^^^^ 208 | 209 | By default, ArgumentParser objects add an option which simply displays 210 | the parser's help message. For example, consider a file named 211 | ``myprogram.py`` containing the following code:: 212 | 213 | import argparse 214 | parser = argparse.ArgumentParser() 215 | parser.add_argument('--foo', help='foo help') 216 | args = parser.parse_args() 217 | 218 | If ``-h`` or ``--help`` is supplied is at the command-line, the ArgumentParser 219 | help will be printed:: 220 | 221 | $ python myprogram.py --help 222 | usage: myprogram.py [-h] [--foo FOO] 223 | 224 | optional arguments: 225 | -h, --help show this help message and exit 226 | --foo FOO foo help 227 | 228 | Occasionally, it may be useful to disable the addition of this help option. 229 | This can be achieved by passing ``False`` as the ``add_help=`` argument to 230 | :class:`ArgumentParser`:: 231 | 232 | >>> parser = argparse.ArgumentParser(prog='PROG', add_help=False) 233 | >>> parser.add_argument('--foo', help='foo help') 234 | >>> parser.print_help() 235 | usage: PROG [--foo FOO] 236 | 237 | optional arguments: 238 | --foo FOO foo help 239 | 240 | The help option is typically ``-h/--help``. The exception to this is 241 | if the ``prefix_chars=`` is specified and does not include ``'-'``, in 242 | which case ``-h`` and ``--help`` are not valid options. In 243 | this case, the first character in ``prefix_chars`` is used to prefix 244 | the help options:: 245 | 246 | >>> parser = argparse.ArgumentParser(prog='PROG', prefix_chars='+/') 247 | >>> parser.print_help() 248 | usage: PROG [+h] 249 | 250 | optional arguments: 251 | +h, ++help show this help message and exit 252 | 253 | 254 | prefix_chars 255 | ^^^^^^^^^^^^ 256 | 257 | Most command-line options will use ``'-'`` as the prefix, e.g. ``-f/--foo``. 258 | Parsers that need to support different or additional prefix 259 | characters, e.g. for options 260 | like ``+f`` or ``/foo``, may specify them using the ``prefix_chars=`` argument 261 | to the ArgumentParser constructor:: 262 | 263 | >>> parser = argparse.ArgumentParser(prog='PROG', prefix_chars='-+') 264 | >>> parser.add_argument('+f') 265 | >>> parser.add_argument('++bar') 266 | >>> parser.parse_args('+f X ++bar Y'.split()) 267 | Namespace(bar='Y', f='X') 268 | 269 | The ``prefix_chars=`` argument defaults to ``'-'``. Supplying a set of 270 | characters that does not include ``'-'`` will cause ``-f/--foo`` options to be 271 | disallowed. 272 | 273 | 274 | fromfile_prefix_chars 275 | ^^^^^^^^^^^^^^^^^^^^^ 276 | 277 | Sometimes, for example when dealing with a particularly long argument lists, it 278 | may make sense to keep the list of arguments in a file rather than typing it out 279 | at the command line. If the ``fromfile_prefix_chars=`` argument is given to the 280 | :class:`ArgumentParser` constructor, then arguments that start with any of the 281 | specified characters will be treated as files, and will be replaced by the 282 | arguments they contain. For example:: 283 | 284 | >>> with open('args.txt', 'w') as fp: 285 | ... fp.write('-f\nbar') 286 | >>> parser = argparse.ArgumentParser(fromfile_prefix_chars='@') 287 | >>> parser.add_argument('-f') 288 | >>> parser.parse_args(['-f', 'foo', '@args.txt']) 289 | Namespace(f='bar') 290 | 291 | Arguments read from a file must by default be one per line (but see also 292 | :meth:`convert_arg_line_to_args`) and are treated as if they were in the same 293 | place as the original file referencing argument on the command line. So in the 294 | example above, the expression ``['-f', 'foo', '@args.txt']`` is considered 295 | equivalent to the expression ``['-f', 'foo', '-f', 'bar']``. 296 | 297 | The ``fromfile_prefix_chars=`` argument defaults to ``None``, meaning that 298 | arguments will never be treated as file references. 299 | 300 | 301 | argument_default 302 | ^^^^^^^^^^^^^^^^ 303 | 304 | Generally, argument defaults are specified either by passing a default to 305 | :meth:`add_argument` or by calling the :meth:`set_defaults` methods with a 306 | specific set of name-value pairs. Sometimes however, it may be useful to 307 | specify a single parser-wide default for arguments. This can be accomplished by 308 | passing the ``argument_default=`` keyword argument to :class:`ArgumentParser`. 309 | For example, to globally suppress attribute creation on :meth:`parse_args` 310 | calls, we supply ``argument_default=SUPPRESS``:: 311 | 312 | >>> parser = argparse.ArgumentParser(argument_default=argparse.SUPPRESS) 313 | >>> parser.add_argument('--foo') 314 | >>> parser.add_argument('bar', nargs='?') 315 | >>> parser.parse_args(['--foo', '1', 'BAR']) 316 | Namespace(bar='BAR', foo='1') 317 | >>> parser.parse_args([]) 318 | Namespace() 319 | 320 | 321 | parents 322 | ^^^^^^^ 323 | 324 | Sometimes, several parsers share a common set of arguments. Rather than 325 | repeating the definitions of these arguments, a single parser with all the 326 | shared arguments and passed to ``parents=`` argument to :class:`ArgumentParser` 327 | can be used. The ``parents=`` argument takes a list of :class:`ArgumentParser` 328 | objects, collects all the positional and optional actions from them, and adds 329 | these actions to the :class:`ArgumentParser` object being constructed:: 330 | 331 | >>> parent_parser = argparse.ArgumentParser(add_help=False) 332 | >>> parent_parser.add_argument('--parent', type=int) 333 | 334 | >>> foo_parser = argparse.ArgumentParser(parents=[parent_parser]) 335 | >>> foo_parser.add_argument('foo') 336 | >>> foo_parser.parse_args(['--parent', '2', 'XXX']) 337 | Namespace(foo='XXX', parent=2) 338 | 339 | >>> bar_parser = argparse.ArgumentParser(parents=[parent_parser]) 340 | >>> bar_parser.add_argument('--bar') 341 | >>> bar_parser.parse_args(['--bar', 'YYY']) 342 | Namespace(bar='YYY', parent=None) 343 | 344 | Note that most parent parsers will specify ``add_help=False``. Otherwise, the 345 | :class:`ArgumentParser` will see two ``-h/--help`` options (one in the parent 346 | and one in the child) and raise an error. 347 | 348 | 349 | formatter_class 350 | ^^^^^^^^^^^^^^^ 351 | 352 | :class:`ArgumentParser` objects allow the help formatting to be customized by 353 | specifying an alternate formatting class. Currently, there are three such 354 | classes: :class:`argparse.RawDescriptionHelpFormatter`, 355 | :class:`argparse.RawTextHelpFormatter` and 356 | :class:`argparse.ArgumentDefaultsHelpFormatter`. The first two allow more 357 | control over how textual descriptions are displayed, while the last 358 | automatically adds information about argument default values. 359 | 360 | By default, :class:`ArgumentParser` objects line-wrap the description_ and 361 | epilog_ texts in command-line help messages:: 362 | 363 | >>> parser = argparse.ArgumentParser( 364 | ... prog='PROG', 365 | ... description='''this description 366 | ... was indented weird 367 | ... but that is okay''', 368 | ... epilog=''' 369 | ... likewise for this epilog whose whitespace will 370 | ... be cleaned up and whose words will be wrapped 371 | ... across a couple lines''') 372 | >>> parser.print_help() 373 | usage: PROG [-h] 374 | 375 | this description was indented weird but that is okay 376 | 377 | optional arguments: 378 | -h, --help show this help message and exit 379 | 380 | likewise for this epilog whose whitespace will be cleaned up and whose words 381 | will be wrapped across a couple lines 382 | 383 | Passing :class:`argparse.RawDescriptionHelpFormatter` as ``formatter_class=`` 384 | indicates that description_ and epilog_ are already correctly formatted and 385 | should not be line-wrapped:: 386 | 387 | >>> parser = argparse.ArgumentParser( 388 | ... prog='PROG', 389 | ... formatter_class=argparse.RawDescriptionHelpFormatter, 390 | ... description=textwrap.dedent('''\ 391 | ... Please do not mess up this text! 392 | ... -------------------------------- 393 | ... I have indented it 394 | ... exactly the way 395 | ... I want it 396 | ... ''')) 397 | >>> parser.print_help() 398 | usage: PROG [-h] 399 | 400 | Please do not mess up this text! 401 | -------------------------------- 402 | I have indented it 403 | exactly the way 404 | I want it 405 | 406 | optional arguments: 407 | -h, --help show this help message and exit 408 | 409 | :class:`RawTextHelpFormatter` maintains whitespace for all sorts of help text 410 | including argument descriptions. 411 | 412 | The other formatter class available, :class:`ArgumentDefaultsHelpFormatter`, 413 | will add information about the default value of each of the arguments:: 414 | 415 | >>> parser = argparse.ArgumentParser( 416 | ... prog='PROG', 417 | ... formatter_class=argparse.ArgumentDefaultsHelpFormatter) 418 | >>> parser.add_argument('--foo', type=int, default=42, help='FOO!') 419 | >>> parser.add_argument('bar', nargs='*', default=[1, 2, 3], help='BAR!') 420 | >>> parser.print_help() 421 | usage: PROG [-h] [--foo FOO] [bar [bar ...]] 422 | 423 | positional arguments: 424 | bar BAR! (default: [1, 2, 3]) 425 | 426 | optional arguments: 427 | -h, --help show this help message and exit 428 | --foo FOO FOO! (default: 42) 429 | 430 | 431 | conflict_handler 432 | ^^^^^^^^^^^^^^^^ 433 | 434 | :class:`ArgumentParser` objects do not allow two actions with the same option 435 | string. By default, :class:`ArgumentParser` objects raises an exception if an 436 | attempt is made to create an argument with an option string that is already in 437 | use:: 438 | 439 | >>> parser = argparse.ArgumentParser(prog='PROG') 440 | >>> parser.add_argument('-f', '--foo', help='old foo help') 441 | >>> parser.add_argument('--foo', help='new foo help') 442 | Traceback (most recent call last): 443 | .. 444 | ArgumentError: argument --foo: conflicting option string(s): --foo 445 | 446 | Sometimes (e.g. when using parents_) it may be useful to simply override any 447 | older arguments with the same option string. To get this behavior, the value 448 | ``'resolve'`` can be supplied to the ``conflict_handler=`` argument of 449 | :class:`ArgumentParser`:: 450 | 451 | >>> parser = argparse.ArgumentParser(prog='PROG', conflict_handler='resolve') 452 | >>> parser.add_argument('-f', '--foo', help='old foo help') 453 | >>> parser.add_argument('--foo', help='new foo help') 454 | >>> parser.print_help() 455 | usage: PROG [-h] [-f FOO] [--foo FOO] 456 | 457 | optional arguments: 458 | -h, --help show this help message and exit 459 | -f FOO old foo help 460 | --foo FOO new foo help 461 | 462 | Note that :class:`ArgumentParser` objects only remove an action if all of its 463 | option strings are overridden. So, in the example above, the old ``-f/--foo`` 464 | action is retained as the ``-f`` action, because only the ``--foo`` option 465 | string was overridden. 466 | 467 | 468 | prog 469 | ^^^^ 470 | 471 | By default, :class:`ArgumentParser` objects uses ``sys.argv[0]`` to determine 472 | how to display the name of the program in help messages. This default is almost 473 | always desirable because it will make the help messages match how the program was 474 | invoked on the command line. For example, consider a file named 475 | ``myprogram.py`` with the following code:: 476 | 477 | import argparse 478 | parser = argparse.ArgumentParser() 479 | parser.add_argument('--foo', help='foo help') 480 | args = parser.parse_args() 481 | 482 | The help for this program will display ``myprogram.py`` as the program name 483 | (regardless of where the program was invoked from):: 484 | 485 | $ python myprogram.py --help 486 | usage: myprogram.py [-h] [--foo FOO] 487 | 488 | optional arguments: 489 | -h, --help show this help message and exit 490 | --foo FOO foo help 491 | $ cd .. 492 | $ python subdir\myprogram.py --help 493 | usage: myprogram.py [-h] [--foo FOO] 494 | 495 | optional arguments: 496 | -h, --help show this help message and exit 497 | --foo FOO foo help 498 | 499 | To change this default behavior, another value can be supplied using the 500 | ``prog=`` argument to :class:`ArgumentParser`:: 501 | 502 | >>> parser = argparse.ArgumentParser(prog='myprogram') 503 | >>> parser.print_help() 504 | usage: myprogram [-h] 505 | 506 | optional arguments: 507 | -h, --help show this help message and exit 508 | 509 | Note that the program name, whether determined from ``sys.argv[0]`` or from the 510 | ``prog=`` argument, is available to help messages using the ``%(prog)s`` format 511 | specifier. 512 | 513 | :: 514 | 515 | >>> parser = argparse.ArgumentParser(prog='myprogram') 516 | >>> parser.add_argument('--foo', help='foo of the %(prog)s program') 517 | >>> parser.print_help() 518 | usage: myprogram [-h] [--foo FOO] 519 | 520 | optional arguments: 521 | -h, --help show this help message and exit 522 | --foo FOO foo of the myprogram program 523 | 524 | 525 | usage 526 | ^^^^^ 527 | 528 | By default, :class:`ArgumentParser` calculates the usage message from the 529 | arguments it contains:: 530 | 531 | >>> parser = argparse.ArgumentParser(prog='PROG') 532 | >>> parser.add_argument('--foo', nargs='?', help='foo help') 533 | >>> parser.add_argument('bar', nargs='+', help='bar help') 534 | >>> parser.print_help() 535 | usage: PROG [-h] [--foo [FOO]] bar [bar ...] 536 | 537 | positional arguments: 538 | bar bar help 539 | 540 | optional arguments: 541 | -h, --help show this help message and exit 542 | --foo [FOO] foo help 543 | 544 | The default message can be overridden with the ``usage=`` keyword argument:: 545 | 546 | >>> parser = argparse.ArgumentParser(prog='PROG', usage='%(prog)s [options]') 547 | >>> parser.add_argument('--foo', nargs='?', help='foo help') 548 | >>> parser.add_argument('bar', nargs='+', help='bar help') 549 | >>> parser.print_help() 550 | usage: PROG [options] 551 | 552 | positional arguments: 553 | bar bar help 554 | 555 | optional arguments: 556 | -h, --help show this help message and exit 557 | --foo [FOO] foo help 558 | 559 | The ``%(prog)s`` format specifier is available to fill in the program name in 560 | your usage messages. 561 | 562 | 563 | The add_argument() method 564 | ------------------------- 565 | 566 | .. method:: ArgumentParser.add_argument(name or flags..., [action], [nargs], [const], [default], [type], [choices], [required], [help], [metavar], [dest]) 567 | 568 | Define how a single command line argument should be parsed. Each parameter 569 | has its own more detailed description below, but in short they are: 570 | 571 | * `name or flags`_ - Either a name or a list of option strings, e.g. ``foo`` 572 | or ``-f, --foo`` 573 | 574 | * action_ - The basic type of action to be taken when this argument is 575 | encountered at the command-line. 576 | 577 | * nargs_ - The number of command-line arguments that should be consumed. 578 | 579 | * const_ - A constant value required by some action_ and nargs_ selections. 580 | 581 | * default_ - The value produced if the argument is absent from the 582 | command-line. 583 | 584 | * type_ - The type to which the command-line arg should be converted. 585 | 586 | * choices_ - A container of the allowable values for the argument. 587 | 588 | * required_ - Whether or not the command-line option may be omitted 589 | (optionals only). 590 | 591 | * help_ - A brief description of what the argument does. 592 | 593 | * metavar_ - A name for the argument in usage messages. 594 | 595 | * dest_ - The name of the attribute to be added to the object returned by 596 | :meth:`parse_args`. 597 | 598 | The following sections describe how each of these are used. 599 | 600 | 601 | name or flags 602 | ^^^^^^^^^^^^^ 603 | 604 | The :meth:`add_argument` method must know whether an optional argument, like 605 | ``-f`` or ``--foo``, or a positional argument, like a list of filenames, is 606 | expected. The first arguments passed to :meth:`add_argument` must therefore be 607 | either a series of flags, or a simple argument name. For example, an optional 608 | argument could be created like:: 609 | 610 | >>> parser.add_argument('-f', '--foo') 611 | 612 | while a positional argument could be created like:: 613 | 614 | >>> parser.add_argument('bar') 615 | 616 | When :meth:`parse_args` is called, optional arguments will be identified by the 617 | ``-`` prefix, and the remaining arguments will be assumed to be positional:: 618 | 619 | >>> parser = argparse.ArgumentParser(prog='PROG') 620 | >>> parser.add_argument('-f', '--foo') 621 | >>> parser.add_argument('bar') 622 | >>> parser.parse_args(['BAR']) 623 | Namespace(bar='BAR', foo=None) 624 | >>> parser.parse_args(['BAR', '--foo', 'FOO']) 625 | Namespace(bar='BAR', foo='FOO') 626 | >>> parser.parse_args(['--foo', 'FOO']) 627 | usage: PROG [-h] [-f FOO] bar 628 | PROG: error: too few arguments 629 | 630 | 631 | action 632 | ^^^^^^ 633 | 634 | :class:`ArgumentParser` objects associate command-line args with actions. These 635 | actions can do just about anything with the command-line args associated with 636 | them, though most actions simply add an attribute to the object returned by 637 | :meth:`parse_args`. The ``action`` keyword argument specifies how the 638 | command-line args should be handled. The supported actions are: 639 | 640 | * ``'store'`` - This just stores the argument's value. This is the default 641 | action. For example:: 642 | 643 | >>> parser = argparse.ArgumentParser() 644 | >>> parser.add_argument('--foo') 645 | >>> parser.parse_args('--foo 1'.split()) 646 | Namespace(foo='1') 647 | 648 | * ``'store_const'`` - This stores the value specified by the const_ keyword 649 | argument. (Note that the const_ keyword argument defaults to the rather 650 | unhelpful ``None``.) The ``'store_const'`` action is most commonly used with 651 | optional arguments that specify some sort of flag. For example:: 652 | 653 | >>> parser = argparse.ArgumentParser() 654 | >>> parser.add_argument('--foo', action='store_const', const=42) 655 | >>> parser.parse_args('--foo'.split()) 656 | Namespace(foo=42) 657 | 658 | * ``'store_true'`` and ``'store_false'`` - These store the values ``True`` and 659 | ``False`` respectively. These are special cases of ``'store_const'``. For 660 | example:: 661 | 662 | >>> parser = argparse.ArgumentParser() 663 | >>> parser.add_argument('--foo', action='store_true') 664 | >>> parser.add_argument('--bar', action='store_false') 665 | >>> parser.parse_args('--foo --bar'.split()) 666 | Namespace(bar=False, foo=True) 667 | 668 | * ``'append'`` - This stores a list, and appends each argument value to the 669 | list. This is useful to allow an option to be specified multiple times. 670 | Example usage:: 671 | 672 | >>> parser = argparse.ArgumentParser() 673 | >>> parser.add_argument('--foo', action='append') 674 | >>> parser.parse_args('--foo 1 --foo 2'.split()) 675 | Namespace(foo=['1', '2']) 676 | 677 | * ``'append_const'`` - This stores a list, and appends the value specified by 678 | the const_ keyword argument to the list. (Note that the const_ keyword 679 | argument defaults to ``None``.) The ``'append_const'`` action is typically 680 | useful when multiple arguments need to store constants to the same list. For 681 | example:: 682 | 683 | >>> parser = argparse.ArgumentParser() 684 | >>> parser.add_argument('--str', dest='types', action='append_const', const=str) 685 | >>> parser.add_argument('--int', dest='types', action='append_const', const=int) 686 | >>> parser.parse_args('--str --int'.split()) 687 | Namespace(types=[, ]) 688 | 689 | * ``'version'`` - This expects a ``version=`` keyword argument in the 690 | :meth:`add_argument` call, and prints version information and exits when 691 | invoked. 692 | 693 | >>> import argparse 694 | >>> parser = argparse.ArgumentParser(prog='PROG') 695 | >>> parser.add_argument('--version', action='version', version='%(prog)s 2.0') 696 | >>> parser.parse_args(['--version']) 697 | PROG 2.0 698 | 699 | You can also specify an arbitrary action by passing an object that implements 700 | the Action API. The easiest way to do this is to extend 701 | :class:`argparse.Action`, supplying an appropriate ``__call__`` method. The 702 | ``__call__`` method should accept four parameters: 703 | 704 | * ``parser`` - The ArgumentParser object which contains this action. 705 | 706 | * ``namespace`` - The namespace object that will be returned by 707 | :meth:`parse_args`. Most actions add an attribute to this object. 708 | 709 | * ``values`` - The associated command-line args, with any type-conversions 710 | applied. (Type-conversions are specified with the type_ keyword argument to 711 | :meth:`add_argument`. 712 | 713 | * ``option_string`` - The option string that was used to invoke this action. 714 | The ``option_string`` argument is optional, and will be absent if the action 715 | is associated with a positional argument. 716 | 717 | An example of a custom action:: 718 | 719 | >>> class FooAction(argparse.Action): 720 | ... def __call__(self, parser, namespace, values, option_string=None): 721 | ... print '%r %r %r' % (namespace, values, option_string) 722 | ... setattr(namespace, self.dest, values) 723 | ... 724 | >>> parser = argparse.ArgumentParser() 725 | >>> parser.add_argument('--foo', action=FooAction) 726 | >>> parser.add_argument('bar', action=FooAction) 727 | >>> args = parser.parse_args('1 --foo 2'.split()) 728 | Namespace(bar=None, foo=None) '1' None 729 | Namespace(bar='1', foo=None) '2' '--foo' 730 | >>> args 731 | Namespace(bar='1', foo='2') 732 | 733 | 734 | nargs 735 | ^^^^^ 736 | 737 | ArgumentParser objects usually associate a single command-line argument with a 738 | single action to be taken. The ``nargs`` keyword argument associates a 739 | different number of command-line arguments with a single action.. The supported 740 | values are: 741 | 742 | * N (an integer). N args from the command-line will be gathered together into a 743 | list. For example:: 744 | 745 | >>> parser = argparse.ArgumentParser() 746 | >>> parser.add_argument('--foo', nargs=2) 747 | >>> parser.add_argument('bar', nargs=1) 748 | >>> parser.parse_args('c --foo a b'.split()) 749 | Namespace(bar=['c'], foo=['a', 'b']) 750 | 751 | Note that ``nargs=1`` produces a list of one item. This is different from 752 | the default, in which the item is produced by itself. 753 | 754 | * ``'?'``. One arg will be consumed from the command-line if possible, and 755 | produced as a single item. If no command-line arg is present, the value from 756 | default_ will be produced. Note that for optional arguments, there is an 757 | additional case - the option string is present but not followed by a 758 | command-line arg. In this case the value from const_ will be produced. Some 759 | examples to illustrate this:: 760 | 761 | >>> parser = argparse.ArgumentParser() 762 | >>> parser.add_argument('--foo', nargs='?', const='c', default='d') 763 | >>> parser.add_argument('bar', nargs='?', default='d') 764 | >>> parser.parse_args('XX --foo YY'.split()) 765 | Namespace(bar='XX', foo='YY') 766 | >>> parser.parse_args('XX --foo'.split()) 767 | Namespace(bar='XX', foo='c') 768 | >>> parser.parse_args(''.split()) 769 | Namespace(bar='d', foo='d') 770 | 771 | One of the more common uses of ``nargs='?'`` is to allow optional input and 772 | output files:: 773 | 774 | >>> parser = argparse.ArgumentParser() 775 | >>> parser.add_argument('infile', nargs='?', type=argparse.FileType('r'), 776 | ... default=sys.stdin) 777 | >>> parser.add_argument('outfile', nargs='?', type=argparse.FileType('w'), 778 | ... default=sys.stdout) 779 | >>> parser.parse_args(['input.txt', 'output.txt']) 780 | Namespace(infile=, outfile=) 781 | >>> parser.parse_args([]) 782 | Namespace(infile=', mode 'r' at 0x...>, outfile=', mode 'w' at 0x...>) 783 | 784 | * ``'*'``. All command-line args present are gathered into a list. Note that 785 | it generally doesn't make much sense to have more than one positional argument 786 | with ``nargs='*'``, but multiple optional arguments with ``nargs='*'`` is 787 | possible. For example:: 788 | 789 | >>> parser = argparse.ArgumentParser() 790 | >>> parser.add_argument('--foo', nargs='*') 791 | >>> parser.add_argument('--bar', nargs='*') 792 | >>> parser.add_argument('baz', nargs='*') 793 | >>> parser.parse_args('a b --foo x y --bar 1 2'.split()) 794 | Namespace(bar=['1', '2'], baz=['a', 'b'], foo=['x', 'y']) 795 | 796 | * ``'+'``. Just like ``'*'``, all command-line args present are gathered into a 797 | list. Additionally, an error message will be generated if there wasn't at 798 | least one command-line arg present. For example:: 799 | 800 | >>> parser = argparse.ArgumentParser(prog='PROG') 801 | >>> parser.add_argument('foo', nargs='+') 802 | >>> parser.parse_args('a b'.split()) 803 | Namespace(foo=['a', 'b']) 804 | >>> parser.parse_args(''.split()) 805 | usage: PROG [-h] foo [foo ...] 806 | PROG: error: too few arguments 807 | 808 | If the ``nargs`` keyword argument is not provided, the number of args consumed 809 | is determined by the action_. Generally this means a single command-line arg 810 | will be consumed and a single item (not a list) will be produced. 811 | 812 | 813 | const 814 | ^^^^^ 815 | 816 | The ``const`` argument of :meth:`add_argument` is used to hold constant values 817 | that are not read from the command line but are required for the various 818 | ArgumentParser actions. The two most common uses of it are: 819 | 820 | * When :meth:`add_argument` is called with ``action='store_const'`` or 821 | ``action='append_const'``. These actions add the ``const`` value to one of 822 | the attributes of the object returned by :meth:`parse_args`. See the action_ 823 | description for examples. 824 | 825 | * When :meth:`add_argument` is called with option strings (like ``-f`` or 826 | ``--foo``) and ``nargs='?'``. This creates an optional argument that can be 827 | followed by zero or one command-line args. When parsing the command-line, if 828 | the option string is encountered with no command-line arg following it, the 829 | value of ``const`` will be assumed instead. See the nargs_ description for 830 | examples. 831 | 832 | The ``const`` keyword argument defaults to ``None``. 833 | 834 | 835 | default 836 | ^^^^^^^ 837 | 838 | All optional arguments and some positional arguments may be omitted at the 839 | command-line. The ``default`` keyword argument of :meth:`add_argument`, whose 840 | value defaults to ``None``, specifies what value should be used if the 841 | command-line arg is not present. For optional arguments, the ``default`` value 842 | is used when the option string was not present at the command line:: 843 | 844 | >>> parser = argparse.ArgumentParser() 845 | >>> parser.add_argument('--foo', default=42) 846 | >>> parser.parse_args('--foo 2'.split()) 847 | Namespace(foo='2') 848 | >>> parser.parse_args(''.split()) 849 | Namespace(foo=42) 850 | 851 | For positional arguments with nargs_ ``='?'`` or ``'*'``, the ``default`` value 852 | is used when no command-line arg was present:: 853 | 854 | >>> parser = argparse.ArgumentParser() 855 | >>> parser.add_argument('foo', nargs='?', default=42) 856 | >>> parser.parse_args('a'.split()) 857 | Namespace(foo='a') 858 | >>> parser.parse_args(''.split()) 859 | Namespace(foo=42) 860 | 861 | 862 | Providing ``default=argparse.SUPPRESS`` causes no attribute to be added if the 863 | command-line argument was not present.:: 864 | 865 | >>> parser = argparse.ArgumentParser() 866 | >>> parser.add_argument('--foo', default=argparse.SUPPRESS) 867 | >>> parser.parse_args([]) 868 | Namespace() 869 | >>> parser.parse_args(['--foo', '1']) 870 | Namespace(foo='1') 871 | 872 | 873 | type 874 | ^^^^ 875 | 876 | By default, ArgumentParser objects read command-line args in as simple strings. 877 | However, quite often the command-line string should instead be interpreted as 878 | another type, like a :class:`float`, :class:`int` or :class:`file`. The 879 | ``type`` keyword argument of :meth:`add_argument` allows any necessary 880 | type-checking and type-conversions to be performed. Many common built-in types 881 | can be used directly as the value of the ``type`` argument:: 882 | 883 | >>> parser = argparse.ArgumentParser() 884 | >>> parser.add_argument('foo', type=int) 885 | >>> parser.add_argument('bar', type=file) 886 | >>> parser.parse_args('2 temp.txt'.split()) 887 | Namespace(bar=, foo=2) 888 | 889 | To ease the use of various types of files, the argparse module provides the 890 | factory FileType which takes the ``mode=`` and ``bufsize=`` arguments of the 891 | ``file`` object. For example, ``FileType('w')`` can be used to create a 892 | writable file:: 893 | 894 | >>> parser = argparse.ArgumentParser() 895 | >>> parser.add_argument('bar', type=argparse.FileType('w')) 896 | >>> parser.parse_args(['out.txt']) 897 | Namespace(bar=) 898 | 899 | ``type=`` can take any callable that takes a single string argument and returns 900 | the type-converted value:: 901 | 902 | >>> def perfect_square(string): 903 | ... value = int(string) 904 | ... sqrt = math.sqrt(value) 905 | ... if sqrt != int(sqrt): 906 | ... msg = "%r is not a perfect square" % string 907 | ... raise argparse.ArgumentTypeError(msg) 908 | ... return value 909 | ... 910 | >>> parser = argparse.ArgumentParser(prog='PROG') 911 | >>> parser.add_argument('foo', type=perfect_square) 912 | >>> parser.parse_args('9'.split()) 913 | Namespace(foo=9) 914 | >>> parser.parse_args('7'.split()) 915 | usage: PROG [-h] foo 916 | PROG: error: argument foo: '7' is not a perfect square 917 | 918 | The choices_ keyword argument may be more convenient for type checkers that 919 | simply check against a range of values:: 920 | 921 | >>> parser = argparse.ArgumentParser(prog='PROG') 922 | >>> parser.add_argument('foo', type=int, choices=xrange(5, 10)) 923 | >>> parser.parse_args('7'.split()) 924 | Namespace(foo=7) 925 | >>> parser.parse_args('11'.split()) 926 | usage: PROG [-h] {5,6,7,8,9} 927 | PROG: error: argument foo: invalid choice: 11 (choose from 5, 6, 7, 8, 9) 928 | 929 | See the choices_ section for more details. 930 | 931 | 932 | choices 933 | ^^^^^^^ 934 | 935 | Some command-line args should be selected from a restricted set of values. 936 | These can be handled by passing a container object as the ``choices`` keyword 937 | argument to :meth:`add_argument`. When the command-line is parsed, arg values 938 | will be checked, and an error message will be displayed if the arg was not one 939 | of the acceptable values:: 940 | 941 | >>> parser = argparse.ArgumentParser(prog='PROG') 942 | >>> parser.add_argument('foo', choices='abc') 943 | >>> parser.parse_args('c'.split()) 944 | Namespace(foo='c') 945 | >>> parser.parse_args('X'.split()) 946 | usage: PROG [-h] {a,b,c} 947 | PROG: error: argument foo: invalid choice: 'X' (choose from 'a', 'b', 'c') 948 | 949 | Note that inclusion in the ``choices`` container is checked after any type_ 950 | conversions have been performed, so the type of the objects in the ``choices`` 951 | container should match the type_ specified:: 952 | 953 | >>> parser = argparse.ArgumentParser(prog='PROG') 954 | >>> parser.add_argument('foo', type=complex, choices=[1, 1j]) 955 | >>> parser.parse_args('1j'.split()) 956 | Namespace(foo=1j) 957 | >>> parser.parse_args('-- -4'.split()) 958 | usage: PROG [-h] {1,1j} 959 | PROG: error: argument foo: invalid choice: (-4+0j) (choose from 1, 1j) 960 | 961 | Any object that supports the ``in`` operator can be passed as the ``choices`` 962 | value, so :class:`dict` objects, :class:`set` objects, custom containers, 963 | etc. are all supported. 964 | 965 | 966 | required 967 | ^^^^^^^^ 968 | 969 | In general, the argparse module assumes that flags like ``-f`` and ``--bar`` 970 | indicate *optional* arguments, which can always be omitted at the command-line. 971 | To make an option *required*, ``True`` can be specified for the ``required=`` 972 | keyword argument to :meth:`add_argument`:: 973 | 974 | >>> parser = argparse.ArgumentParser() 975 | >>> parser.add_argument('--foo', required=True) 976 | >>> parser.parse_args(['--foo', 'BAR']) 977 | Namespace(foo='BAR') 978 | >>> parser.parse_args([]) 979 | usage: argparse.py [-h] [--foo FOO] 980 | argparse.py: error: option --foo is required 981 | 982 | As the example shows, if an option is marked as ``required``, :meth:`parse_args` 983 | will report an error if that option is not present at the command line. 984 | 985 | .. note:: 986 | 987 | Required options are generally considered bad form because users expect 988 | *options* to be *optional*, and thus they should be avoided when possible. 989 | 990 | 991 | help 992 | ^^^^ 993 | 994 | The ``help`` value is a string containing a brief description of the argument. 995 | When a user requests help (usually by using ``-h`` or ``--help`` at the 996 | command-line), these ``help`` descriptions will be displayed with each 997 | argument:: 998 | 999 | >>> parser = argparse.ArgumentParser(prog='frobble') 1000 | >>> parser.add_argument('--foo', action='store_true', 1001 | ... help='foo the bars before frobbling') 1002 | >>> parser.add_argument('bar', nargs='+', 1003 | ... help='one of the bars to be frobbled') 1004 | >>> parser.parse_args('-h'.split()) 1005 | usage: frobble [-h] [--foo] bar [bar ...] 1006 | 1007 | positional arguments: 1008 | bar one of the bars to be frobbled 1009 | 1010 | optional arguments: 1011 | -h, --help show this help message and exit 1012 | --foo foo the bars before frobbling 1013 | 1014 | The ``help`` strings can include various format specifiers to avoid repetition 1015 | of things like the program name or the argument default_. The available 1016 | specifiers include the program name, ``%(prog)s`` and most keyword arguments to 1017 | :meth:`add_argument`, e.g. ``%(default)s``, ``%(type)s``, etc.:: 1018 | 1019 | >>> parser = argparse.ArgumentParser(prog='frobble') 1020 | >>> parser.add_argument('bar', nargs='?', type=int, default=42, 1021 | ... help='the bar to %(prog)s (default: %(default)s)') 1022 | >>> parser.print_help() 1023 | usage: frobble [-h] [bar] 1024 | 1025 | positional arguments: 1026 | bar the bar to frobble (default: 42) 1027 | 1028 | optional arguments: 1029 | -h, --help show this help message and exit 1030 | 1031 | 1032 | metavar 1033 | ^^^^^^^ 1034 | 1035 | When :class:`ArgumentParser` generates help messages, it need some way to refer 1036 | to each expected argument. By default, ArgumentParser objects use the dest_ 1037 | value as the "name" of each object. By default, for positional argument 1038 | actions, the dest_ value is used directly, and for optional argument actions, 1039 | the dest_ value is uppercased. So, a single positional argument with 1040 | ``dest='bar'`` will that argument will be referred to as ``bar``. A single 1041 | optional argument ``--foo`` that should be followed by a single command-line arg 1042 | will be referred to as ``FOO``. An example:: 1043 | 1044 | >>> parser = argparse.ArgumentParser() 1045 | >>> parser.add_argument('--foo') 1046 | >>> parser.add_argument('bar') 1047 | >>> parser.parse_args('X --foo Y'.split()) 1048 | Namespace(bar='X', foo='Y') 1049 | >>> parser.print_help() 1050 | usage: [-h] [--foo FOO] bar 1051 | 1052 | positional arguments: 1053 | bar 1054 | 1055 | optional arguments: 1056 | -h, --help show this help message and exit 1057 | --foo FOO 1058 | 1059 | An alternative name can be specified with ``metavar``:: 1060 | 1061 | >>> parser = argparse.ArgumentParser() 1062 | >>> parser.add_argument('--foo', metavar='YYY') 1063 | >>> parser.add_argument('bar', metavar='XXX') 1064 | >>> parser.parse_args('X --foo Y'.split()) 1065 | Namespace(bar='X', foo='Y') 1066 | >>> parser.print_help() 1067 | usage: [-h] [--foo YYY] XXX 1068 | 1069 | positional arguments: 1070 | XXX 1071 | 1072 | optional arguments: 1073 | -h, --help show this help message and exit 1074 | --foo YYY 1075 | 1076 | Note that ``metavar`` only changes the *displayed* name - the name of the 1077 | attribute on the :meth:`parse_args` object is still determined by the dest_ 1078 | value. 1079 | 1080 | Different values of ``nargs`` may cause the metavar to be used multiple times. 1081 | Providing a tuple to ``metavar`` specifies a different display for each of the 1082 | arguments:: 1083 | 1084 | >>> parser = argparse.ArgumentParser(prog='PROG') 1085 | >>> parser.add_argument('-x', nargs=2) 1086 | >>> parser.add_argument('--foo', nargs=2, metavar=('bar', 'baz')) 1087 | >>> parser.print_help() 1088 | usage: PROG [-h] [-x X X] [--foo bar baz] 1089 | 1090 | optional arguments: 1091 | -h, --help show this help message and exit 1092 | -x X X 1093 | --foo bar baz 1094 | 1095 | 1096 | dest 1097 | ^^^^ 1098 | 1099 | Most :class:`ArgumentParser` actions add some value as an attribute of the 1100 | object returned by :meth:`parse_args`. The name of this attribute is determined 1101 | by the ``dest`` keyword argument of :meth:`add_argument`. For positional 1102 | argument actions, ``dest`` is normally supplied as the first argument to 1103 | :meth:`add_argument`:: 1104 | 1105 | >>> parser = argparse.ArgumentParser() 1106 | >>> parser.add_argument('bar') 1107 | >>> parser.parse_args('XXX'.split()) 1108 | Namespace(bar='XXX') 1109 | 1110 | For optional argument actions, the value of ``dest`` is normally inferred from 1111 | the option strings. :class:`ArgumentParser` generates the value of ``dest`` by 1112 | taking the first long option string and stripping away the initial ``'--'`` 1113 | string. If no long option strings were supplied, ``dest`` will be derived from 1114 | the first short option string by stripping the initial ``'-'`` character. Any 1115 | internal ``'-'`` characters will be converted to ``'_'`` characters to make sure 1116 | the string is a valid attribute name. The examples below illustrate this 1117 | behavior:: 1118 | 1119 | >>> parser = argparse.ArgumentParser() 1120 | >>> parser.add_argument('-f', '--foo-bar', '--foo') 1121 | >>> parser.add_argument('-x', '-y') 1122 | >>> parser.parse_args('-f 1 -x 2'.split()) 1123 | Namespace(foo_bar='1', x='2') 1124 | >>> parser.parse_args('--foo 1 -y 2'.split()) 1125 | Namespace(foo_bar='1', x='2') 1126 | 1127 | ``dest`` allows a custom attribute name to be provided:: 1128 | 1129 | >>> parser = argparse.ArgumentParser() 1130 | >>> parser.add_argument('--foo', dest='bar') 1131 | >>> parser.parse_args('--foo XXX'.split()) 1132 | Namespace(bar='XXX') 1133 | 1134 | 1135 | The parse_args() method 1136 | ----------------------- 1137 | 1138 | .. method:: ArgumentParser.parse_args(args=None, namespace=None) 1139 | 1140 | Convert argument strings to objects and assign them as attributes of the 1141 | namespace. Return the populated namespace. 1142 | 1143 | Previous calls to :meth:`add_argument` determine exactly what objects are 1144 | created and how they are assigned. See the documentation for 1145 | :meth:`add_argument` for details. 1146 | 1147 | By default, the arg strings are taken from :data:`sys.argv`, and a new empty 1148 | :class:`Namespace` object is created for the attributes. 1149 | 1150 | 1151 | Option value syntax 1152 | ^^^^^^^^^^^^^^^^^^^ 1153 | 1154 | The :meth:`parse_args` method supports several ways of specifying the value of 1155 | an option (if it takes one). In the simplest case, the option and its value are 1156 | passed as two separate arguments:: 1157 | 1158 | >>> parser = argparse.ArgumentParser(prog='PROG') 1159 | >>> parser.add_argument('-x') 1160 | >>> parser.add_argument('--foo') 1161 | >>> parser.parse_args('-x X'.split()) 1162 | Namespace(foo=None, x='X') 1163 | >>> parser.parse_args('--foo FOO'.split()) 1164 | Namespace(foo='FOO', x=None) 1165 | 1166 | For long options (options with names longer than a single character), the option 1167 | and value can also be passed as a single command line argument, using ``=`` to 1168 | separate them:: 1169 | 1170 | >>> parser.parse_args('--foo=FOO'.split()) 1171 | Namespace(foo='FOO', x=None) 1172 | 1173 | For short options (options only one character long), the option and its value 1174 | can be concatenated:: 1175 | 1176 | >>> parser.parse_args('-xX'.split()) 1177 | Namespace(foo=None, x='X') 1178 | 1179 | Several short options can be joined together, using only a single ``-`` prefix, 1180 | as long as only the last option (or none of them) requires a value:: 1181 | 1182 | >>> parser = argparse.ArgumentParser(prog='PROG') 1183 | >>> parser.add_argument('-x', action='store_true') 1184 | >>> parser.add_argument('-y', action='store_true') 1185 | >>> parser.add_argument('-z') 1186 | >>> parser.parse_args('-xyzZ'.split()) 1187 | Namespace(x=True, y=True, z='Z') 1188 | 1189 | 1190 | Invalid arguments 1191 | ^^^^^^^^^^^^^^^^^ 1192 | 1193 | While parsing the command-line, ``parse_args`` checks for a variety of errors, 1194 | including ambiguous options, invalid types, invalid options, wrong number of 1195 | positional arguments, etc. When it encounters such an error, it exits and 1196 | prints the error along with a usage message:: 1197 | 1198 | >>> parser = argparse.ArgumentParser(prog='PROG') 1199 | >>> parser.add_argument('--foo', type=int) 1200 | >>> parser.add_argument('bar', nargs='?') 1201 | 1202 | >>> # invalid type 1203 | >>> parser.parse_args(['--foo', 'spam']) 1204 | usage: PROG [-h] [--foo FOO] [bar] 1205 | PROG: error: argument --foo: invalid int value: 'spam' 1206 | 1207 | >>> # invalid option 1208 | >>> parser.parse_args(['--bar']) 1209 | usage: PROG [-h] [--foo FOO] [bar] 1210 | PROG: error: no such option: --bar 1211 | 1212 | >>> # wrong number of arguments 1213 | >>> parser.parse_args(['spam', 'badger']) 1214 | usage: PROG [-h] [--foo FOO] [bar] 1215 | PROG: error: extra arguments found: badger 1216 | 1217 | 1218 | Arguments containing ``"-"`` 1219 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 1220 | 1221 | The ``parse_args`` method attempts to give errors whenever the user has clearly 1222 | made a mistake, but some situations are inherently ambiguous. For example, the 1223 | command-line arg ``'-1'`` could either be an attempt to specify an option or an 1224 | attempt to provide a positional argument. The ``parse_args`` method is cautious 1225 | here: positional arguments may only begin with ``'-'`` if they look like 1226 | negative numbers and there are no options in the parser that look like negative 1227 | numbers:: 1228 | 1229 | >>> parser = argparse.ArgumentParser(prog='PROG') 1230 | >>> parser.add_argument('-x') 1231 | >>> parser.add_argument('foo', nargs='?') 1232 | 1233 | >>> # no negative number options, so -1 is a positional argument 1234 | >>> parser.parse_args(['-x', '-1']) 1235 | Namespace(foo=None, x='-1') 1236 | 1237 | >>> # no negative number options, so -1 and -5 are positional arguments 1238 | >>> parser.parse_args(['-x', '-1', '-5']) 1239 | Namespace(foo='-5', x='-1') 1240 | 1241 | >>> parser = argparse.ArgumentParser(prog='PROG') 1242 | >>> parser.add_argument('-1', dest='one') 1243 | >>> parser.add_argument('foo', nargs='?') 1244 | 1245 | >>> # negative number options present, so -1 is an option 1246 | >>> parser.parse_args(['-1', 'X']) 1247 | Namespace(foo=None, one='X') 1248 | 1249 | >>> # negative number options present, so -2 is an option 1250 | >>> parser.parse_args(['-2']) 1251 | usage: PROG [-h] [-1 ONE] [foo] 1252 | PROG: error: no such option: -2 1253 | 1254 | >>> # negative number options present, so both -1s are options 1255 | >>> parser.parse_args(['-1', '-1']) 1256 | usage: PROG [-h] [-1 ONE] [foo] 1257 | PROG: error: argument -1: expected one argument 1258 | 1259 | If you have positional arguments that must begin with ``'-'`` and don't look 1260 | like negative numbers, you can insert the pseudo-argument ``'--'`` which tells 1261 | ``parse_args`` that everything after that is a positional argument:: 1262 | 1263 | >>> parser.parse_args(['--', '-f']) 1264 | Namespace(foo='-f', one=None) 1265 | 1266 | 1267 | Argument abbreviations 1268 | ^^^^^^^^^^^^^^^^^^^^^^ 1269 | 1270 | The :meth:`parse_args` method allows long options to be abbreviated if the 1271 | abbreviation is unambiguous:: 1272 | 1273 | >>> parser = argparse.ArgumentParser(prog='PROG') 1274 | >>> parser.add_argument('-bacon') 1275 | >>> parser.add_argument('-badger') 1276 | >>> parser.parse_args('-bac MMM'.split()) 1277 | Namespace(bacon='MMM', badger=None) 1278 | >>> parser.parse_args('-bad WOOD'.split()) 1279 | Namespace(bacon=None, badger='WOOD') 1280 | >>> parser.parse_args('-ba BA'.split()) 1281 | usage: PROG [-h] [-bacon BACON] [-badger BADGER] 1282 | PROG: error: ambiguous option: -ba could match -badger, -bacon 1283 | 1284 | An error is produced for arguments that could produce more than one options. 1285 | 1286 | 1287 | Beyond ``sys.argv`` 1288 | ^^^^^^^^^^^^^^^^^^^ 1289 | 1290 | Sometimes it may be useful to have an ArgumentParser parse args other than those 1291 | of :data:`sys.argv`. This can be accomplished by passing a list of strings to 1292 | ``parse_args``. This is useful for testing at the interactive prompt:: 1293 | 1294 | >>> parser = argparse.ArgumentParser() 1295 | >>> parser.add_argument( 1296 | ... 'integers', metavar='int', type=int, choices=xrange(10), 1297 | ... nargs='+', help='an integer in the range 0..9') 1298 | >>> parser.add_argument( 1299 | ... '--sum', dest='accumulate', action='store_const', const=sum, 1300 | ... default=max, help='sum the integers (default: find the max)') 1301 | >>> parser.parse_args(['1', '2', '3', '4']) 1302 | Namespace(accumulate=, integers=[1, 2, 3, 4]) 1303 | >>> parser.parse_args('1 2 3 4 --sum'.split()) 1304 | Namespace(accumulate=, integers=[1, 2, 3, 4]) 1305 | 1306 | 1307 | Custom namespaces 1308 | ^^^^^^^^^^^^^^^^^ 1309 | 1310 | It may also be useful to have an :class:`ArgumentParser` assign attributes to an 1311 | already existing object, rather than the newly-created :class:`Namespace` object 1312 | that is normally used. This can be achieved by specifying the ``namespace=`` 1313 | keyword argument:: 1314 | 1315 | >>> class C(object): 1316 | ... pass 1317 | ... 1318 | >>> c = C() 1319 | >>> parser = argparse.ArgumentParser() 1320 | >>> parser.add_argument('--foo') 1321 | >>> parser.parse_args(args=['--foo', 'BAR'], namespace=c) 1322 | >>> c.foo 1323 | 'BAR' 1324 | 1325 | 1326 | Other utilities 1327 | --------------- 1328 | 1329 | Sub-commands 1330 | ^^^^^^^^^^^^ 1331 | 1332 | .. method:: ArgumentParser.add_subparsers() 1333 | 1334 | Many programs split up their functionality into a number of sub-commands, 1335 | for example, the ``svn`` program can invoke sub-commands like ``svn 1336 | checkout``, ``svn update``, and ``svn commit``. Splitting up functionality 1337 | this way can be a particularly good idea when a program performs several 1338 | different functions which require different kinds of command-line arguments. 1339 | :class:`ArgumentParser` supports the creation of such sub-commands with the 1340 | :meth:`add_subparsers` method. The :meth:`add_subparsers` method is normally 1341 | called with no arguments and returns an special action object. This object 1342 | has a single method, ``add_parser``, which takes a command name and any 1343 | :class:`ArgumentParser` constructor arguments, and returns an 1344 | :class:`ArgumentParser` object that can be modified as usual. 1345 | 1346 | Some example usage:: 1347 | 1348 | >>> # create the top-level parser 1349 | >>> parser = argparse.ArgumentParser(prog='PROG') 1350 | >>> parser.add_argument('--foo', action='store_true', help='foo help') 1351 | >>> subparsers = parser.add_subparsers(help='sub-command help') 1352 | >>> 1353 | >>> # create the parser for the "a" command 1354 | >>> parser_a = subparsers.add_parser('a', help='a help') 1355 | >>> parser_a.add_argument('bar', type=int, help='bar help') 1356 | >>> 1357 | >>> # create the parser for the "b" command 1358 | >>> parser_b = subparsers.add_parser('b', help='b help') 1359 | >>> parser_b.add_argument('--baz', choices='XYZ', help='baz help') 1360 | >>> 1361 | >>> # parse some arg lists 1362 | >>> parser.parse_args(['a', '12']) 1363 | Namespace(bar=12, foo=False) 1364 | >>> parser.parse_args(['--foo', 'b', '--baz', 'Z']) 1365 | Namespace(baz='Z', foo=True) 1366 | 1367 | Note that the object returned by :meth:`parse_args` will only contain 1368 | attributes for the main parser and the subparser that was selected by the 1369 | command line (and not any other subparsers). So in the example above, when 1370 | the ``"a"`` command is specified, only the ``foo`` and ``bar`` attributes are 1371 | present, and when the ``"b"`` command is specified, only the ``foo`` and 1372 | ``baz`` attributes are present. 1373 | 1374 | Similarly, when a help message is requested from a subparser, only the help 1375 | for that particular parser will be printed. The help message will not 1376 | include parent parser or sibling parser messages. (A help message for each 1377 | subparser command, however, can be given by supplying the ``help=`` argument 1378 | to ``add_parser`` as above.) 1379 | 1380 | :: 1381 | 1382 | >>> parser.parse_args(['--help']) 1383 | usage: PROG [-h] [--foo] {a,b} ... 1384 | 1385 | positional arguments: 1386 | {a,b} sub-command help 1387 | a a help 1388 | b b help 1389 | 1390 | optional arguments: 1391 | -h, --help show this help message and exit 1392 | --foo foo help 1393 | 1394 | >>> parser.parse_args(['a', '--help']) 1395 | usage: PROG a [-h] bar 1396 | 1397 | positional arguments: 1398 | bar bar help 1399 | 1400 | optional arguments: 1401 | -h, --help show this help message and exit 1402 | 1403 | >>> parser.parse_args(['b', '--help']) 1404 | usage: PROG b [-h] [--baz {X,Y,Z}] 1405 | 1406 | optional arguments: 1407 | -h, --help show this help message and exit 1408 | --baz {X,Y,Z} baz help 1409 | 1410 | The :meth:`add_subparsers` method also supports ``title`` and ``description`` 1411 | keyword arguments. When either is present, the subparser's commands will 1412 | appear in their own group in the help output. For example:: 1413 | 1414 | >>> parser = argparse.ArgumentParser() 1415 | >>> subparsers = parser.add_subparsers(title='subcommands', 1416 | ... description='valid subcommands', 1417 | ... help='additional help') 1418 | >>> subparsers.add_parser('foo') 1419 | >>> subparsers.add_parser('bar') 1420 | >>> parser.parse_args(['-h']) 1421 | usage: [-h] {foo,bar} ... 1422 | 1423 | optional arguments: 1424 | -h, --help show this help message and exit 1425 | 1426 | subcommands: 1427 | valid subcommands 1428 | 1429 | {foo,bar} additional help 1430 | 1431 | 1432 | One particularly effective way of handling sub-commands is to combine the use 1433 | of the :meth:`add_subparsers` method with calls to :meth:`set_defaults` so 1434 | that each subparser knows which Python function it should execute. For 1435 | example:: 1436 | 1437 | >>> # sub-command functions 1438 | >>> def foo(args): 1439 | ... print args.x * args.y 1440 | ... 1441 | >>> def bar(args): 1442 | ... print '((%s))' % args.z 1443 | ... 1444 | >>> # create the top-level parser 1445 | >>> parser = argparse.ArgumentParser() 1446 | >>> subparsers = parser.add_subparsers() 1447 | >>> 1448 | >>> # create the parser for the "foo" command 1449 | >>> parser_foo = subparsers.add_parser('foo') 1450 | >>> parser_foo.add_argument('-x', type=int, default=1) 1451 | >>> parser_foo.add_argument('y', type=float) 1452 | >>> parser_foo.set_defaults(func=foo) 1453 | >>> 1454 | >>> # create the parser for the "bar" command 1455 | >>> parser_bar = subparsers.add_parser('bar') 1456 | >>> parser_bar.add_argument('z') 1457 | >>> parser_bar.set_defaults(func=bar) 1458 | >>> 1459 | >>> # parse the args and call whatever function was selected 1460 | >>> args = parser.parse_args('foo 1 -x 2'.split()) 1461 | >>> args.func(args) 1462 | 2.0 1463 | >>> 1464 | >>> # parse the args and call whatever function was selected 1465 | >>> args = parser.parse_args('bar XYZYX'.split()) 1466 | >>> args.func(args) 1467 | ((XYZYX)) 1468 | 1469 | This way, you can let :meth:`parse_args` does the job of calling the 1470 | appropriate function after argument parsing is complete. Associating 1471 | functions with actions like this is typically the easiest way to handle the 1472 | different actions for each of your subparsers. However, if it is necessary 1473 | to check the name of the subparser that was invoked, the ``dest`` keyword 1474 | argument to the :meth:`add_subparsers` call will work:: 1475 | 1476 | >>> parser = argparse.ArgumentParser() 1477 | >>> subparsers = parser.add_subparsers(dest='subparser_name') 1478 | >>> subparser1 = subparsers.add_parser('1') 1479 | >>> subparser1.add_argument('-x') 1480 | >>> subparser2 = subparsers.add_parser('2') 1481 | >>> subparser2.add_argument('y') 1482 | >>> parser.parse_args(['2', 'frobble']) 1483 | Namespace(subparser_name='2', y='frobble') 1484 | 1485 | 1486 | FileType objects 1487 | ^^^^^^^^^^^^^^^^ 1488 | 1489 | .. class:: FileType(mode='r', bufsize=None) 1490 | 1491 | The :class:`FileType` factory creates objects that can be passed to the type 1492 | argument of :meth:`ArgumentParser.add_argument`. Arguments that have 1493 | :class:`FileType` objects as their type will open command-line args as files 1494 | with the requested modes and buffer sizes: 1495 | 1496 | >>> parser = argparse.ArgumentParser() 1497 | >>> parser.add_argument('--output', type=argparse.FileType('wb', 0)) 1498 | >>> parser.parse_args(['--output', 'out']) 1499 | Namespace(output=) 1500 | 1501 | FileType objects understand the pseudo-argument ``'-'`` and automatically 1502 | convert this into ``sys.stdin`` for readable :class:`FileType` objects and 1503 | ``sys.stdout`` for writable :class:`FileType` objects: 1504 | 1505 | >>> parser = argparse.ArgumentParser() 1506 | >>> parser.add_argument('infile', type=argparse.FileType('r')) 1507 | >>> parser.parse_args(['-']) 1508 | Namespace(infile=', mode 'r' at 0x...>) 1509 | 1510 | 1511 | Argument groups 1512 | ^^^^^^^^^^^^^^^ 1513 | 1514 | .. method:: ArgumentParser.add_argument_group(title=None, description=None) 1515 | 1516 | By default, :class:`ArgumentParser` groups command-line arguments into 1517 | "positional arguments" and "optional arguments" when displaying help 1518 | messages. When there is a better conceptual grouping of arguments than this 1519 | default one, appropriate groups can be created using the 1520 | :meth:`add_argument_group` method:: 1521 | 1522 | >>> parser = argparse.ArgumentParser(prog='PROG', add_help=False) 1523 | >>> group = parser.add_argument_group('group') 1524 | >>> group.add_argument('--foo', help='foo help') 1525 | >>> group.add_argument('bar', help='bar help') 1526 | >>> parser.print_help() 1527 | usage: PROG [--foo FOO] bar 1528 | 1529 | group: 1530 | bar bar help 1531 | --foo FOO foo help 1532 | 1533 | The :meth:`add_argument_group` method returns an argument group object which 1534 | has an :meth:`~ArgumentParser.add_argument` method just like a regular 1535 | :class:`ArgumentParser`. When an argument is added to the group, the parser 1536 | treats it just like a normal argument, but displays the argument in a 1537 | separate group for help messages. The :meth:`add_argument_group` method 1538 | accepts *title* and *description* arguments which can be used to 1539 | customize this display:: 1540 | 1541 | >>> parser = argparse.ArgumentParser(prog='PROG', add_help=False) 1542 | >>> group1 = parser.add_argument_group('group1', 'group1 description') 1543 | >>> group1.add_argument('foo', help='foo help') 1544 | >>> group2 = parser.add_argument_group('group2', 'group2 description') 1545 | >>> group2.add_argument('--bar', help='bar help') 1546 | >>> parser.print_help() 1547 | usage: PROG [--bar BAR] foo 1548 | 1549 | group1: 1550 | group1 description 1551 | 1552 | foo foo help 1553 | 1554 | group2: 1555 | group2 description 1556 | 1557 | --bar BAR bar help 1558 | 1559 | Note that any arguments not your user defined groups will end up back in the 1560 | usual "positional arguments" and "optional arguments" sections. 1561 | 1562 | 1563 | Mutual exclusion 1564 | ^^^^^^^^^^^^^^^^ 1565 | 1566 | .. method:: add_mutually_exclusive_group(required=False) 1567 | 1568 | Create a mutually exclusive group. argparse will make sure that only one of 1569 | the arguments in the mutually exclusive group was present on the command 1570 | line:: 1571 | 1572 | >>> parser = argparse.ArgumentParser(prog='PROG') 1573 | >>> group = parser.add_mutually_exclusive_group() 1574 | >>> group.add_argument('--foo', action='store_true') 1575 | >>> group.add_argument('--bar', action='store_false') 1576 | >>> parser.parse_args(['--foo']) 1577 | Namespace(bar=True, foo=True) 1578 | >>> parser.parse_args(['--bar']) 1579 | Namespace(bar=False, foo=False) 1580 | >>> parser.parse_args(['--foo', '--bar']) 1581 | usage: PROG [-h] [--foo | --bar] 1582 | PROG: error: argument --bar: not allowed with argument --foo 1583 | 1584 | The :meth:`add_mutually_exclusive_group` method also accepts a *required* 1585 | argument, to indicate that at least one of the mutually exclusive arguments 1586 | is required:: 1587 | 1588 | >>> parser = argparse.ArgumentParser(prog='PROG') 1589 | >>> group = parser.add_mutually_exclusive_group(required=True) 1590 | >>> group.add_argument('--foo', action='store_true') 1591 | >>> group.add_argument('--bar', action='store_false') 1592 | >>> parser.parse_args([]) 1593 | usage: PROG [-h] (--foo | --bar) 1594 | PROG: error: one of the arguments --foo --bar is required 1595 | 1596 | Note that currently mutually exclusive argument groups do not support the 1597 | *title* and *description* arguments of :meth:`add_argument_group`. 1598 | 1599 | 1600 | Parser defaults 1601 | ^^^^^^^^^^^^^^^ 1602 | 1603 | .. method:: ArgumentParser.set_defaults(**kwargs) 1604 | 1605 | Most of the time, the attributes of the object returned by :meth:`parse_args` 1606 | will be fully determined by inspecting the command-line args and the argument 1607 | actions. :meth:`ArgumentParser.set_defaults` allows some additional 1608 | attributes that are determined without any inspection of the command-line to 1609 | be added:: 1610 | 1611 | >>> parser = argparse.ArgumentParser() 1612 | >>> parser.add_argument('foo', type=int) 1613 | >>> parser.set_defaults(bar=42, baz='badger') 1614 | >>> parser.parse_args(['736']) 1615 | Namespace(bar=42, baz='badger', foo=736) 1616 | 1617 | Note that parser-level defaults always override argument-level defaults:: 1618 | 1619 | >>> parser = argparse.ArgumentParser() 1620 | >>> parser.add_argument('--foo', default='bar') 1621 | >>> parser.set_defaults(foo='spam') 1622 | >>> parser.parse_args([]) 1623 | Namespace(foo='spam') 1624 | 1625 | Parser-level defaults can be particularly useful when working with multiple 1626 | parsers. See the :meth:`~ArgumentParser.add_subparsers` method for an 1627 | example of this type. 1628 | 1629 | .. method:: ArgumentParser.get_default(dest) 1630 | 1631 | Get the default value for a namespace attribute, as set by either 1632 | :meth:`~ArgumentParser.add_argument` or by 1633 | :meth:`~ArgumentParser.set_defaults`:: 1634 | 1635 | >>> parser = argparse.ArgumentParser() 1636 | >>> parser.add_argument('--foo', default='badger') 1637 | >>> parser.get_default('foo') 1638 | 'badger' 1639 | 1640 | 1641 | Printing help 1642 | ^^^^^^^^^^^^^ 1643 | 1644 | In most typical applications, :meth:`parse_args` will take care of formatting 1645 | and printing any usage or error messages. However, several formatting methods 1646 | are available: 1647 | 1648 | .. method:: ArgumentParser.print_usage(file=None) 1649 | 1650 | Print a brief description of how the :class:`ArgumentParser` should be 1651 | invoked on the command line. If *file* is ``None``, :data:`sys.stderr` is 1652 | assumed. 1653 | 1654 | .. method:: ArgumentParser.print_help(file=None) 1655 | 1656 | Print a help message, including the program usage and information about the 1657 | arguments registered with the :class:`ArgumentParser`. If *file* is 1658 | ``None``, :data:`sys.stderr` is assumed. 1659 | 1660 | There are also variants of these methods that simply return a string instead of 1661 | printing it: 1662 | 1663 | .. method:: ArgumentParser.format_usage() 1664 | 1665 | Return a string containing a brief description of how the 1666 | :class:`ArgumentParser` should be invoked on the command line. 1667 | 1668 | .. method:: ArgumentParser.format_help() 1669 | 1670 | Return a string containing a help message, including the program usage and 1671 | information about the arguments registered with the :class:`ArgumentParser`. 1672 | 1673 | 1674 | Partial parsing 1675 | ^^^^^^^^^^^^^^^ 1676 | 1677 | .. method:: ArgumentParser.parse_known_args(args=None, namespace=None) 1678 | 1679 | Sometimes a script may only parse a few of the command line arguments, passing 1680 | the remaining arguments on to another script or program. In these cases, the 1681 | :meth:`parse_known_args` method can be useful. It works much like 1682 | :meth:`~ArgumentParser.parse_args` except that it does not produce an error when 1683 | extra arguments are present. Instead, it returns a two item tuple containing 1684 | the populated namespace and the list of remaining argument strings. 1685 | 1686 | :: 1687 | 1688 | >>> parser = argparse.ArgumentParser() 1689 | >>> parser.add_argument('--foo', action='store_true') 1690 | >>> parser.add_argument('bar') 1691 | >>> parser.parse_known_args(['--foo', '--badger', 'BAR', 'spam']) 1692 | (Namespace(bar='BAR', foo=True), ['--badger', 'spam']) 1693 | 1694 | 1695 | Customizing file parsing 1696 | ^^^^^^^^^^^^^^^^^^^^^^^^ 1697 | 1698 | .. method:: ArgumentParser.convert_arg_line_to_args(arg_line) 1699 | 1700 | Arguments that are read from a file (see the *fromfile_prefix_chars* 1701 | keyword argument to the :class:`ArgumentParser` constructor) are read one 1702 | argument per line. :meth:`convert_arg_line_to_args` can be overriden for 1703 | fancier reading. 1704 | 1705 | This method takes a single argument *arg_line* which is a string read from 1706 | the argument file. It returns a list of arguments parsed from this string. 1707 | The method is called once per line read from the argument file, in order. 1708 | 1709 | A useful override of this method is one that treats each space-separated word 1710 | as an argument:: 1711 | 1712 | def convert_arg_line_to_args(self, arg_line): 1713 | for arg in arg_line.split(): 1714 | if not arg.strip(): 1715 | continue 1716 | yield arg 1717 | 1718 | 1719 | Exiting methods 1720 | ^^^^^^^^^^^^^^^ 1721 | 1722 | .. method:: ArgumentParser.exit(status=0, message=None) 1723 | 1724 | This method terminates the program, exiting with the specified *status* 1725 | and, if given, it prints a *message* before that. 1726 | 1727 | .. method:: ArgumentParser.error(message) 1728 | 1729 | This method prints a usage message including the *message* to the 1730 | standard output and terminates the program with a status code of 2. 1731 | 1732 | 1733 | .. _argparse-from-optparse: 1734 | 1735 | Upgrading optparse code 1736 | ----------------------- 1737 | 1738 | Originally, the argparse module had attempted to maintain compatibility with 1739 | optparse. However, optparse was difficult to extend transparently, particularly 1740 | with the changes required to support the new ``nargs=`` specifiers and better 1741 | usage messages. When most everything in optparse had either been copy-pasted 1742 | over or monkey-patched, it no longer seemed practical to try to maintain the 1743 | backwards compatibility. 1744 | 1745 | A partial upgrade path from optparse to argparse: 1746 | 1747 | * Replace all ``add_option()`` calls with :meth:`ArgumentParser.add_argument` calls. 1748 | 1749 | * Replace ``options, args = parser.parse_args()`` with ``args = 1750 | parser.parse_args()`` and add additional :meth:`ArgumentParser.add_argument` calls for the 1751 | positional arguments. 1752 | 1753 | * Replace callback actions and the ``callback_*`` keyword arguments with 1754 | ``type`` or ``action`` arguments. 1755 | 1756 | * Replace string names for ``type`` keyword arguments with the corresponding 1757 | type objects (e.g. int, float, complex, etc). 1758 | 1759 | * Replace :class:`optparse.Values` with :class:`Namespace` and 1760 | :exc:`optparse.OptionError` and :exc:`optparse.OptionValueError` with 1761 | :exc:`ArgumentError`. 1762 | 1763 | * Replace strings with implicit arguments such as ``%default`` or ``%prog`` with 1764 | the standard python syntax to use dictionaries to format strings, that is, 1765 | ``%(default)s`` and ``%(prog)s``. 1766 | 1767 | * Replace the OptionParser constructor ``version`` argument with a call to 1768 | ``parser.add_argument('--version', action='version', version='')`` 1769 | -------------------------------------------------------------------------------- /doc/source/conf.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # 3 | # argparse documentation build configuration file, created by 4 | # sphinx-quickstart on Sun Mar 27 01:27:16 2011. 5 | # 6 | # This file is execfile()d with the current directory set to its containing dir. 7 | # 8 | # Note that not all possible configuration values are present in this 9 | # autogenerated file. 10 | # 11 | # All configuration values have a default; values that are commented out 12 | # serve to show the default. 13 | 14 | import sys, os 15 | 16 | # If extensions (or modules to document with autodoc) are in another directory, 17 | # add these directories to sys.path here. If the directory is relative to the 18 | # documentation root, use os.path.abspath to make it absolute, like shown here. 19 | #sys.path.insert(0, os.path.abspath('.')) 20 | 21 | # -- General configuration ----------------------------------------------------- 22 | 23 | # If your documentation needs a minimal Sphinx version, state it here. 24 | #needs_sphinx = '1.0' 25 | 26 | # Add any Sphinx extension module names here, as strings. They can be extensions 27 | # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. 28 | extensions = [] 29 | 30 | # Add any paths that contain templates here, relative to this directory. 31 | templates_path = ['_templates'] 32 | 33 | # The suffix of source filenames. 34 | source_suffix = '.rst' 35 | 36 | # The encoding of source files. 37 | #source_encoding = 'utf-8-sig' 38 | 39 | # The master toctree document. 40 | master_doc = 'index' 41 | 42 | # General information about the project. 43 | project = u'argparse' 44 | copyright = u'2011, Steven J. Bethard' 45 | 46 | # The version info for the project you're documenting, acts as replacement for 47 | # |version| and |release|, also used in various other places throughout the 48 | # built documents. 49 | # 50 | # The short X.Y version. 51 | version = '1.2' 52 | # The full version, including alpha/beta/rc tags. 53 | release = '1.2' 54 | 55 | # The language for content autogenerated by Sphinx. Refer to documentation 56 | # for a list of supported languages. 57 | #language = None 58 | 59 | # There are two options for replacing |today|: either, you set today to some 60 | # non-false value, then it is used: 61 | #today = '' 62 | # Else, today_fmt is used as the format for a strftime call. 63 | #today_fmt = '%B %d, %Y' 64 | 65 | # List of patterns, relative to source directory, that match files and 66 | # directories to ignore when looking for source files. 67 | exclude_patterns = [] 68 | 69 | # The reST default role (used for this markup: `text`) to use for all documents. 70 | #default_role = None 71 | 72 | # If true, '()' will be appended to :func: etc. cross-reference text. 73 | #add_function_parentheses = True 74 | 75 | # If true, the current module name will be prepended to all description 76 | # unit titles (such as .. function::). 77 | #add_module_names = True 78 | 79 | # If true, sectionauthor and moduleauthor directives will be shown in the 80 | # output. They are ignored by default. 81 | #show_authors = False 82 | 83 | # The name of the Pygments (syntax highlighting) style to use. 84 | pygments_style = 'sphinx' 85 | 86 | # A list of ignored prefixes for module index sorting. 87 | #modindex_common_prefix = [] 88 | 89 | 90 | # -- Options for HTML output --------------------------------------------------- 91 | 92 | # The theme to use for HTML and HTML Help pages. See the documentation for 93 | # a list of builtin themes. 94 | html_theme = 'default' 95 | 96 | # Theme options are theme-specific and customize the look and feel of a theme 97 | # further. For a list of options available for each theme, see the 98 | # documentation. 99 | #html_theme_options = {} 100 | 101 | # Add any paths that contain custom themes here, relative to this directory. 102 | #html_theme_path = [] 103 | 104 | # The name for this set of Sphinx documents. If None, it defaults to 105 | # " v documentation". 106 | #html_title = None 107 | 108 | # A shorter title for the navigation bar. Default is the same as html_title. 109 | #html_short_title = None 110 | 111 | # The name of an image file (relative to this directory) to place at the top 112 | # of the sidebar. 113 | #html_logo = None 114 | 115 | # The name of an image file (within the static path) to use as favicon of the 116 | # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 117 | # pixels large. 118 | #html_favicon = None 119 | 120 | # Add any paths that contain custom static files (such as style sheets) here, 121 | # relative to this directory. They are copied after the builtin static files, 122 | # so a file named "default.css" will overwrite the builtin "default.css". 123 | html_static_path = ['_static'] 124 | 125 | # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, 126 | # using the given strftime format. 127 | #html_last_updated_fmt = '%b %d, %Y' 128 | 129 | # If true, SmartyPants will be used to convert quotes and dashes to 130 | # typographically correct entities. 131 | #html_use_smartypants = True 132 | 133 | # Custom sidebar templates, maps document names to template names. 134 | #html_sidebars = {} 135 | 136 | # Additional templates that should be rendered to pages, maps page names to 137 | # template names. 138 | #html_additional_pages = {} 139 | 140 | # If false, no module index is generated. 141 | #html_domain_indices = True 142 | 143 | # If false, no index is generated. 144 | #html_use_index = True 145 | 146 | # If true, the index is split into individual pages for each letter. 147 | #html_split_index = False 148 | 149 | # If true, links to the reST sources are added to the pages. 150 | #html_show_sourcelink = True 151 | 152 | # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. 153 | #html_show_sphinx = True 154 | 155 | # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. 156 | #html_show_copyright = True 157 | 158 | # If true, an OpenSearch description file will be output, and all pages will 159 | # contain a tag referring to it. The value of this option must be the 160 | # base URL from which the finished HTML is served. 161 | #html_use_opensearch = '' 162 | 163 | # This is the file name suffix for HTML files (e.g. ".xhtml"). 164 | #html_file_suffix = None 165 | 166 | # Output file base name for HTML help builder. 167 | htmlhelp_basename = 'argparsedoc' 168 | 169 | 170 | # -- Options for LaTeX output -------------------------------------------------- 171 | 172 | # The paper size ('letter' or 'a4'). 173 | #latex_paper_size = 'letter' 174 | 175 | # The font size ('10pt', '11pt' or '12pt'). 176 | #latex_font_size = '10pt' 177 | 178 | # Grouping the document tree into LaTeX files. List of tuples 179 | # (source start file, target name, title, author, documentclass [howto/manual]). 180 | latex_documents = [ 181 | ('index', 'argparse.tex', u'argparse Documentation', 182 | u'Steven J. Bethard', 'manual'), 183 | ] 184 | 185 | # The name of an image file (relative to this directory) to place at the top of 186 | # the title page. 187 | #latex_logo = None 188 | 189 | # For "manual" documents, if this is true, then toplevel headings are parts, 190 | # not chapters. 191 | #latex_use_parts = False 192 | 193 | # If true, show page references after internal links. 194 | #latex_show_pagerefs = False 195 | 196 | # If true, show URL addresses after external links. 197 | #latex_show_urls = False 198 | 199 | # Additional stuff for the LaTeX preamble. 200 | #latex_preamble = '' 201 | 202 | # Documents to append as an appendix to all manuals. 203 | #latex_appendices = [] 204 | 205 | # If false, no module index is generated. 206 | #latex_domain_indices = True 207 | 208 | 209 | # -- Options for manual page output -------------------------------------------- 210 | 211 | # One entry per manual page. List of tuples 212 | # (source start file, name, description, authors, manual section). 213 | man_pages = [ 214 | ('index', 'argparse', u'argparse Documentation', 215 | [u'Steven J. Bethard'], 1) 216 | ] 217 | 218 | # -- Options for Texinfo output ------------------------------------------------ 219 | 220 | # Grouping the document tree into Texinfo files. List of tuples 221 | # (source start file, target name, title, author, 222 | # dir menu entry, description, category) 223 | texinfo_documents = [ 224 | ('index', 'argparse', u'argparse Documentation', u'Steven J. Bethard', 225 | 'argparse', 'One line description of project.', 'Miscellaneous'), 226 | ] 227 | 228 | # Documents to append as an appendix to all manuals. 229 | texinfo_appendices = [] 230 | -------------------------------------------------------------------------------- /doc/source/index.rst: -------------------------------------------------------------------------------- 1 | .. argparse documentation master file, created by 2 | sphinx-quickstart on Sun Mar 27 01:27:16 2011. 3 | You can adapt this file completely to your liking, but it should at least 4 | contain the root `toctree` directive. 5 | 6 | Welcome to argparse's documentation! 7 | ==================================== 8 | 9 | Contents: 10 | 11 | .. toctree:: 12 | :maxdepth: 2 13 | 14 | argparse 15 | license 16 | 17 | Indices and tables 18 | ================== 19 | 20 | * :ref:`genindex` 21 | * :ref:`search` 22 | 23 | -------------------------------------------------------------------------------- /doc/source/license.rst: -------------------------------------------------------------------------------- 1 | arparse Copyright and License 2 | ============================= 3 | 4 | .. _license: 5 | 6 | .. literalinclude:: ../../LICENSE.txt 7 | 8 | This is the Python License (from file doc/Python-License.txt): 9 | 10 | .. literalinclude:: Python-License.txt 11 | 12 | -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [bdist_rpm] 2 | release=1 3 | doc_files= 4 | README.txt 5 | LICENSE.txt 6 | PKG-INFO 7 | doc/ 8 | requires=python 9 | build_requires=python 10 | 11 | [bdist_wheel] 12 | universal = 1 13 | 14 | [build_sphinx] 15 | source-dir = doc/ 16 | build-dir = doc/_build 17 | all_files = 1 18 | 19 | [upload_sphinx] 20 | upload-dir = doc/_build/html 21 | 22 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | import sys, os 2 | 3 | from setuptools import setup, find_packages 4 | 5 | import argparse 6 | 7 | long_description = open('README.txt').read() 8 | 9 | 10 | setup_args = dict( 11 | name="argparse", 12 | version=argparse.__version__, 13 | description='Python command-line parsing library', 14 | long_description=long_description, 15 | author="Thomas Waldmann", 16 | author_email="tw@waldmann-edv.de", 17 | url="https://github.com/ThomasWaldmann/argparse/", 18 | license="Python Software Foundation License", 19 | keywords="argparse command line parser parsing", 20 | platforms="any", 21 | classifiers="""\ 22 | Development Status :: 5 - Production/Stable 23 | Environment :: Console 24 | Intended Audience :: Developers 25 | License :: OSI Approved :: Python Software Foundation License 26 | Operating System :: OS Independent 27 | Programming Language :: Python 28 | Programming Language :: Python :: 2 29 | Programming Language :: Python :: 3 30 | Programming Language :: Python :: 2.3 31 | Programming Language :: Python :: 2.4 32 | Programming Language :: Python :: 2.5 33 | Programming Language :: Python :: 2.6 34 | Programming Language :: Python :: 2.7 35 | Programming Language :: Python :: 3.0 36 | Programming Language :: Python :: 3.1 37 | Programming Language :: Python :: 3.2 38 | Programming Language :: Python :: 3.3 39 | Programming Language :: Python :: 3.4 40 | Topic :: Software Development""".splitlines(), 41 | py_modules=['argparse'], 42 | ) 43 | 44 | if __name__ == '__main__': 45 | setup(**setup_args) 46 | 47 | -------------------------------------------------------------------------------- /tox.ini: -------------------------------------------------------------------------------- 1 | [tox] 2 | # py23,24,25 not supported by tox any more 3 | # for these, one can do manual testing like this: 4 | # python2.5 test/test_argparse.py 5 | envlist=py26,py27,pypy,py31,py32,py33,py34 6 | 7 | [testenv] 8 | setenv = 9 | PYTHONHASHSEED = 0 10 | PYTHONPATH = . 11 | commands = python test/test_argparse.py 12 | 13 | --------------------------------------------------------------------------------