| Benjamin Peterson | a39e966 | 2010-03-02 22:05:59 +0000 | [diff] [blame] | 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 <steven.bethard@gmail.com> | 
|  | 7 | .. versionadded:: 2.7 | 
|  | 8 | .. sectionauthor:: Steven Bethard <steven.bethard@gmail.com> | 
|  | 9 |  | 
|  | 10 |  | 
|  | 11 | The :mod:`argparse` module makes it easy to write user friendly command line | 
| Benjamin Peterson | 90c5802 | 2010-03-03 01:55:09 +0000 | [diff] [blame] | 12 | interfaces. The program defines what arguments it requires, and :mod:`argparse` | 
| Georg Brandl | d2decd9 | 2010-03-02 22:17:38 +0000 | [diff] [blame] | 13 | will figure out how to parse those out of :data:`sys.argv`.  The :mod:`argparse` | 
| Benjamin Peterson | 90c5802 | 2010-03-03 01:55:09 +0000 | [diff] [blame] | 14 | module also automatically generates help and usage messages and issues errors | 
|  | 15 | when users give the program invalid arguments. | 
| Benjamin Peterson | a39e966 | 2010-03-02 22:05:59 +0000 | [diff] [blame] | 16 |  | 
|  | 17 | Example | 
|  | 18 | ------- | 
|  | 19 |  | 
| Benjamin Peterson | 90c5802 | 2010-03-03 01:55:09 +0000 | [diff] [blame] | 20 | The following code is a Python program that takes a list of integers and | 
|  | 21 | produces either the sum or the max:: | 
| Benjamin Peterson | a39e966 | 2010-03-02 22:05:59 +0000 | [diff] [blame] | 22 |  | 
|  | 23 | import argparse | 
|  | 24 |  | 
|  | 25 | parser = argparse.ArgumentParser(description='Process some integers.') | 
|  | 26 | parser.add_argument('integers', metavar='N', type=int, nargs='+', | 
|  | 27 | help='an integer for the accumulator') | 
|  | 28 | parser.add_argument('--sum', dest='accumulate', action='store_const', | 
|  | 29 | const=sum, default=max, | 
|  | 30 | help='sum the integers (default: find the max)') | 
|  | 31 |  | 
|  | 32 | args = parser.parse_args() | 
|  | 33 | print args.accumulate(args.integers) | 
|  | 34 |  | 
|  | 35 | Assuming the Python code above is saved into a file called ``prog.py``, it can | 
|  | 36 | be run at the command line and provides useful help messages:: | 
|  | 37 |  | 
|  | 38 | $ prog.py -h | 
|  | 39 | usage: prog.py [-h] [--sum] N [N ...] | 
|  | 40 |  | 
|  | 41 | Process some integers. | 
|  | 42 |  | 
|  | 43 | positional arguments: | 
|  | 44 | N           an integer for the accumulator | 
|  | 45 |  | 
|  | 46 | optional arguments: | 
|  | 47 | -h, --help  show this help message and exit | 
|  | 48 | --sum       sum the integers (default: find the max) | 
|  | 49 |  | 
|  | 50 | When run with the appropriate arguments, it prints either the sum or the max of | 
|  | 51 | the command-line integers:: | 
|  | 52 |  | 
|  | 53 | $ prog.py 1 2 3 4 | 
|  | 54 | 4 | 
|  | 55 |  | 
|  | 56 | $ prog.py 1 2 3 4 --sum | 
|  | 57 | 10 | 
|  | 58 |  | 
|  | 59 | If invalid arguments are passed in, it will issue an error:: | 
|  | 60 |  | 
|  | 61 | $ prog.py a b c | 
|  | 62 | usage: prog.py [-h] [--sum] N [N ...] | 
|  | 63 | prog.py: error: argument N: invalid int value: 'a' | 
|  | 64 |  | 
|  | 65 | The following sections walk you through this example. | 
|  | 66 |  | 
|  | 67 | Creating a parser | 
|  | 68 | ^^^^^^^^^^^^^^^^^ | 
|  | 69 |  | 
| Benjamin Peterson | ac80c15 | 2010-03-03 21:28:25 +0000 | [diff] [blame] | 70 | The first step in using the :mod:`argparse` is creating an | 
| Benjamin Peterson | 90c5802 | 2010-03-03 01:55:09 +0000 | [diff] [blame] | 71 | :class:`ArgumentParser` object:: | 
| Benjamin Peterson | a39e966 | 2010-03-02 22:05:59 +0000 | [diff] [blame] | 72 |  | 
|  | 73 | >>> parser = argparse.ArgumentParser(description='Process some integers.') | 
|  | 74 |  | 
|  | 75 | The :class:`ArgumentParser` object will hold all the information necessary to | 
| Benjamin Peterson | 90c5802 | 2010-03-03 01:55:09 +0000 | [diff] [blame] | 76 | parse the command line into python data types. | 
| Benjamin Peterson | a39e966 | 2010-03-02 22:05:59 +0000 | [diff] [blame] | 77 |  | 
|  | 78 |  | 
|  | 79 | Adding arguments | 
|  | 80 | ^^^^^^^^^^^^^^^^ | 
|  | 81 |  | 
| Benjamin Peterson | 90c5802 | 2010-03-03 01:55:09 +0000 | [diff] [blame] | 82 | Filling an :class:`ArgumentParser` with information about program arguments is | 
|  | 83 | done by making calls to the :meth:`~ArgumentParser.add_argument` method. | 
|  | 84 | Generally, these calls tell the :class:`ArgumentParser` how to take the strings | 
|  | 85 | on the command line and turn them into objects.  This information is stored and | 
|  | 86 | used when :meth:`~ArgumentParser.parse_args` is called. For example:: | 
| Benjamin Peterson | a39e966 | 2010-03-02 22:05:59 +0000 | [diff] [blame] | 87 |  | 
|  | 88 | >>> parser.add_argument('integers', metavar='N', type=int, nargs='+', | 
|  | 89 | ...                     help='an integer for the accumulator') | 
|  | 90 | >>> parser.add_argument('--sum', dest='accumulate', action='store_const', | 
|  | 91 | ...                     const=sum, default=max, | 
|  | 92 | ...                     help='sum the integers (default: find the max)') | 
|  | 93 |  | 
| Benjamin Peterson | 90c5802 | 2010-03-03 01:55:09 +0000 | [diff] [blame] | 94 | Later, calling :meth:`parse_args` will return an object with | 
| Georg Brandl | d2decd9 | 2010-03-02 22:17:38 +0000 | [diff] [blame] | 95 | two attributes, ``integers`` and ``accumulate``.  The ``integers`` attribute | 
|  | 96 | will be a list of one or more ints, and the ``accumulate`` attribute will be | 
|  | 97 | either the :func:`sum` function, if ``--sum`` was specified at the command line, | 
|  | 98 | or the :func:`max` function if it was not. | 
| Benjamin Peterson | a39e966 | 2010-03-02 22:05:59 +0000 | [diff] [blame] | 99 |  | 
|  | 100 | Parsing arguments | 
|  | 101 | ^^^^^^^^^^^^^^^^^ | 
|  | 102 |  | 
| Benjamin Peterson | 90c5802 | 2010-03-03 01:55:09 +0000 | [diff] [blame] | 103 | :class:`ArgumentParser` parses args through the | 
|  | 104 | :meth:`~ArgumentParser.parse_args` method.  This will inspect the command-line, | 
| Georg Brandl | d2decd9 | 2010-03-02 22:17:38 +0000 | [diff] [blame] | 105 | convert each arg to the appropriate type and then invoke the appropriate action. | 
|  | 106 | In most cases, this means a simple namespace object will be built up from | 
|  | 107 | attributes parsed out of the command-line:: | 
| Benjamin Peterson | a39e966 | 2010-03-02 22:05:59 +0000 | [diff] [blame] | 108 |  | 
|  | 109 | >>> parser.parse_args(['--sum', '7', '-1', '42']) | 
|  | 110 | Namespace(accumulate=<built-in function sum>, integers=[7, -1, 42]) | 
|  | 111 |  | 
| Benjamin Peterson | 90c5802 | 2010-03-03 01:55:09 +0000 | [diff] [blame] | 112 | In a script, :meth:`~ArgumentParser.parse_args` will typically be called with no | 
|  | 113 | arguments, and the :class:`ArgumentParser` will automatically determine the | 
|  | 114 | command-line args from :data:`sys.argv`. | 
| Benjamin Peterson | a39e966 | 2010-03-02 22:05:59 +0000 | [diff] [blame] | 115 |  | 
|  | 116 |  | 
|  | 117 | ArgumentParser objects | 
|  | 118 | ---------------------- | 
|  | 119 |  | 
|  | 120 | .. class:: ArgumentParser([description], [epilog], [prog], [usage], [add_help], [argument_default], [parents], [prefix_chars], [conflict_handler], [formatter_class]) | 
|  | 121 |  | 
| Georg Brandl | d2decd9 | 2010-03-02 22:17:38 +0000 | [diff] [blame] | 122 | Create a new :class:`ArgumentParser` object.  Each parameter has its own more | 
| Benjamin Peterson | a39e966 | 2010-03-02 22:05:59 +0000 | [diff] [blame] | 123 | detailed description below, but in short they are: | 
|  | 124 |  | 
|  | 125 | * description_ - Text to display before the argument help. | 
|  | 126 |  | 
|  | 127 | * epilog_ - Text to display after the argument help. | 
|  | 128 |  | 
| Benjamin Peterson | 90c5802 | 2010-03-03 01:55:09 +0000 | [diff] [blame] | 129 | * add_help_ - Add a -h/--help option to the parser. (default: ``True``) | 
| Benjamin Peterson | a39e966 | 2010-03-02 22:05:59 +0000 | [diff] [blame] | 130 |  | 
|  | 131 | * argument_default_ - Set the global default value for arguments. | 
| Benjamin Peterson | 90c5802 | 2010-03-03 01:55:09 +0000 | [diff] [blame] | 132 | (default: ``None``) | 
| Benjamin Peterson | a39e966 | 2010-03-02 22:05:59 +0000 | [diff] [blame] | 133 |  | 
| Benjamin Peterson | 90c5802 | 2010-03-03 01:55:09 +0000 | [diff] [blame] | 134 | * parents_ - A list of :class:`ArgumentParser` objects whose arguments should | 
| Benjamin Peterson | a39e966 | 2010-03-02 22:05:59 +0000 | [diff] [blame] | 135 | also be included. | 
|  | 136 |  | 
|  | 137 | * prefix_chars_ - The set of characters that prefix optional arguments. | 
|  | 138 | (default: '-') | 
|  | 139 |  | 
|  | 140 | * fromfile_prefix_chars_ - The set of characters that prefix files from | 
| Benjamin Peterson | 90c5802 | 2010-03-03 01:55:09 +0000 | [diff] [blame] | 141 | which additional arguments should be read. (default: ``None``) | 
| Benjamin Peterson | a39e966 | 2010-03-02 22:05:59 +0000 | [diff] [blame] | 142 |  | 
|  | 143 | * formatter_class_ - A class for customizing the help output. | 
|  | 144 |  | 
|  | 145 | * conflict_handler_ - Usually unnecessary, defines strategy for resolving | 
|  | 146 | conflicting optionals. | 
|  | 147 |  | 
| Benjamin Peterson | 90c5802 | 2010-03-03 01:55:09 +0000 | [diff] [blame] | 148 | * prog_ - The name of the program (default: | 
|  | 149 | :data:`sys.argv[0]`) | 
| Benjamin Peterson | a39e966 | 2010-03-02 22:05:59 +0000 | [diff] [blame] | 150 |  | 
| Benjamin Peterson | 90c5802 | 2010-03-03 01:55:09 +0000 | [diff] [blame] | 151 | * usage_ - The string describing the program usage (default: generated) | 
| Benjamin Peterson | a39e966 | 2010-03-02 22:05:59 +0000 | [diff] [blame] | 152 |  | 
| Benjamin Peterson | 90c5802 | 2010-03-03 01:55:09 +0000 | [diff] [blame] | 153 | The following sections describe how each of these are used. | 
| Benjamin Peterson | a39e966 | 2010-03-02 22:05:59 +0000 | [diff] [blame] | 154 |  | 
|  | 155 |  | 
|  | 156 | description | 
|  | 157 | ^^^^^^^^^^^ | 
|  | 158 |  | 
| Benjamin Peterson | 90c5802 | 2010-03-03 01:55:09 +0000 | [diff] [blame] | 159 | Most calls to the :class:`ArgumentParser` constructor will use the | 
|  | 160 | ``description=`` keyword argument.  This argument gives a brief description of | 
|  | 161 | what the program does and how it works.  In help messages, the description is | 
|  | 162 | displayed between the command-line usage string and the help messages for the | 
|  | 163 | various arguments:: | 
| Benjamin Peterson | a39e966 | 2010-03-02 22:05:59 +0000 | [diff] [blame] | 164 |  | 
|  | 165 | >>> parser = argparse.ArgumentParser(description='A foo that bars') | 
|  | 166 | >>> parser.print_help() | 
|  | 167 | usage: argparse.py [-h] | 
|  | 168 |  | 
|  | 169 | A foo that bars | 
|  | 170 |  | 
|  | 171 | optional arguments: | 
|  | 172 | -h, --help  show this help message and exit | 
|  | 173 |  | 
|  | 174 | By default, the description will be line-wrapped so that it fits within the | 
| Georg Brandl | d2decd9 | 2010-03-02 22:17:38 +0000 | [diff] [blame] | 175 | given space.  To change this behavior, see the formatter_class_ argument. | 
| Benjamin Peterson | a39e966 | 2010-03-02 22:05:59 +0000 | [diff] [blame] | 176 |  | 
|  | 177 |  | 
|  | 178 | epilog | 
|  | 179 | ^^^^^^ | 
|  | 180 |  | 
|  | 181 | Some programs like to display additional description of the program after the | 
| Georg Brandl | d2decd9 | 2010-03-02 22:17:38 +0000 | [diff] [blame] | 182 | description of the arguments.  Such text can be specified using the ``epilog=`` | 
|  | 183 | argument to :class:`ArgumentParser`:: | 
| Benjamin Peterson | a39e966 | 2010-03-02 22:05:59 +0000 | [diff] [blame] | 184 |  | 
|  | 185 | >>> parser = argparse.ArgumentParser( | 
|  | 186 | ...     description='A foo that bars', | 
|  | 187 | ...     epilog="And that's how you'd foo a bar") | 
|  | 188 | >>> parser.print_help() | 
|  | 189 | usage: argparse.py [-h] | 
|  | 190 |  | 
|  | 191 | A foo that bars | 
|  | 192 |  | 
|  | 193 | optional arguments: | 
|  | 194 | -h, --help  show this help message and exit | 
|  | 195 |  | 
|  | 196 | And that's how you'd foo a bar | 
|  | 197 |  | 
|  | 198 | As with the description_ argument, the ``epilog=`` text is by default | 
|  | 199 | line-wrapped, but this behavior can be adjusted with the formatter_class_ | 
| Benjamin Peterson | 90c5802 | 2010-03-03 01:55:09 +0000 | [diff] [blame] | 200 | argument to :class:`ArgumentParser`. | 
| Benjamin Peterson | a39e966 | 2010-03-02 22:05:59 +0000 | [diff] [blame] | 201 |  | 
|  | 202 |  | 
|  | 203 | add_help | 
|  | 204 | ^^^^^^^^ | 
|  | 205 |  | 
|  | 206 | By default, ArgumentParser objects add a ``-h/--help`` option which simply | 
| Georg Brandl | d2decd9 | 2010-03-02 22:17:38 +0000 | [diff] [blame] | 207 | displays the parser's help message.  For example, consider a file named | 
| Benjamin Peterson | a39e966 | 2010-03-02 22:05:59 +0000 | [diff] [blame] | 208 | ``myprogram.py`` containing the following code:: | 
|  | 209 |  | 
|  | 210 | import argparse | 
|  | 211 | parser = argparse.ArgumentParser() | 
|  | 212 | parser.add_argument('--foo', help='foo help') | 
|  | 213 | args = parser.parse_args() | 
|  | 214 |  | 
|  | 215 | If ``-h`` or ``--help`` is supplied is at the command-line, the ArgumentParser | 
|  | 216 | help will be printed:: | 
|  | 217 |  | 
|  | 218 | $ python myprogram.py --help | 
|  | 219 | usage: myprogram.py [-h] [--foo FOO] | 
|  | 220 |  | 
|  | 221 | optional arguments: | 
|  | 222 | -h, --help  show this help message and exit | 
|  | 223 | --foo FOO   foo help | 
|  | 224 |  | 
|  | 225 | Occasionally, it may be useful to disable the addition of this help option. | 
|  | 226 | This can be achieved by passing ``False`` as the ``add_help=`` argument to | 
| Benjamin Peterson | 90c5802 | 2010-03-03 01:55:09 +0000 | [diff] [blame] | 227 | :class:`ArgumentParser`:: | 
| Benjamin Peterson | a39e966 | 2010-03-02 22:05:59 +0000 | [diff] [blame] | 228 |  | 
|  | 229 | >>> parser = argparse.ArgumentParser(prog='PROG', add_help=False) | 
|  | 230 | >>> parser.add_argument('--foo', help='foo help') | 
|  | 231 | >>> parser.print_help() | 
|  | 232 | usage: PROG [--foo FOO] | 
|  | 233 |  | 
|  | 234 | optional arguments: | 
|  | 235 | --foo FOO  foo help | 
|  | 236 |  | 
|  | 237 |  | 
|  | 238 | prefix_chars | 
|  | 239 | ^^^^^^^^^^^^ | 
|  | 240 |  | 
|  | 241 | Most command-line options will use ``'-'`` as the prefix, e.g. ``-f/--foo``. | 
|  | 242 | Parsers that need to support additional prefix characters, e.g. for options | 
|  | 243 | like ``+f`` or ``/foo``, may specify them using the ``prefix_chars=`` argument | 
|  | 244 | to the ArgumentParser constructor:: | 
|  | 245 |  | 
|  | 246 | >>> parser = argparse.ArgumentParser(prog='PROG', prefix_chars='-+') | 
|  | 247 | >>> parser.add_argument('+f') | 
|  | 248 | >>> parser.add_argument('++bar') | 
|  | 249 | >>> parser.parse_args('+f X ++bar Y'.split()) | 
|  | 250 | Namespace(bar='Y', f='X') | 
|  | 251 |  | 
|  | 252 | The ``prefix_chars=`` argument defaults to ``'-'``. Supplying a set of | 
|  | 253 | characters that does not include ``'-'`` will cause ``-f/--foo`` options to be | 
|  | 254 | disallowed. | 
|  | 255 |  | 
|  | 256 |  | 
|  | 257 | fromfile_prefix_chars | 
|  | 258 | ^^^^^^^^^^^^^^^^^^^^^ | 
|  | 259 |  | 
| Benjamin Peterson | 90c5802 | 2010-03-03 01:55:09 +0000 | [diff] [blame] | 260 | Sometimes, for example when dealing with a particularly long argument lists, it | 
|  | 261 | may make sense to keep the list of arguments in a file rather than typing it out | 
|  | 262 | at the command line.  If the ``fromfile_prefix_chars=`` argument is given to the | 
|  | 263 | :class:`ArgumentParser` constructor, then arguments that start with any of the | 
|  | 264 | specified characters will be treated as files, and will be replaced by the | 
|  | 265 | arguments they contain.  For example:: | 
| Benjamin Peterson | a39e966 | 2010-03-02 22:05:59 +0000 | [diff] [blame] | 266 |  | 
| Benjamin Peterson | 90c5802 | 2010-03-03 01:55:09 +0000 | [diff] [blame] | 267 | >>> with open('args.txt', 'w') as fp: | 
|  | 268 | ...    fp.write('-f\nbar') | 
| Benjamin Peterson | a39e966 | 2010-03-02 22:05:59 +0000 | [diff] [blame] | 269 | >>> parser = argparse.ArgumentParser(fromfile_prefix_chars='@') | 
|  | 270 | >>> parser.add_argument('-f') | 
|  | 271 | >>> parser.parse_args(['-f', 'foo', '@args.txt']) | 
|  | 272 | Namespace(f='bar') | 
|  | 273 |  | 
|  | 274 | Arguments read from a file must by default be one per line (but see also | 
|  | 275 | :meth:`convert_arg_line_to_args`) and are treated as if they were in the same | 
| Georg Brandl | d2decd9 | 2010-03-02 22:17:38 +0000 | [diff] [blame] | 276 | place as the original file referencing argument on the command line.  So in the | 
| Benjamin Peterson | a39e966 | 2010-03-02 22:05:59 +0000 | [diff] [blame] | 277 | example above, the expression ``['-f', 'foo', '@args.txt']`` is considered | 
|  | 278 | equivalent to the expression ``['-f', 'foo', '-f', 'bar']``. | 
|  | 279 |  | 
|  | 280 | The ``fromfile_prefix_chars=`` argument defaults to ``None``, meaning that | 
|  | 281 | arguments will never be treated as file references. | 
|  | 282 |  | 
|  | 283 | argument_default | 
|  | 284 | ^^^^^^^^^^^^^^^^ | 
|  | 285 |  | 
|  | 286 | Generally, argument defaults are specified either by passing a default to | 
|  | 287 | :meth:`add_argument` or by calling the :meth:`set_defaults` methods with a | 
| Georg Brandl | d2decd9 | 2010-03-02 22:17:38 +0000 | [diff] [blame] | 288 | specific set of name-value pairs.  Sometimes however, it may be useful to | 
|  | 289 | specify a single parser-wide default for arguments.  This can be accomplished by | 
| Benjamin Peterson | 90c5802 | 2010-03-03 01:55:09 +0000 | [diff] [blame] | 290 | passing the ``argument_default=`` keyword argument to :class:`ArgumentParser`. | 
|  | 291 | For example, to globally suppress attribute creation on :meth:`parse_args` | 
|  | 292 | calls, we supply ``argument_default=SUPPRESS``:: | 
| Benjamin Peterson | a39e966 | 2010-03-02 22:05:59 +0000 | [diff] [blame] | 293 |  | 
|  | 294 | >>> parser = argparse.ArgumentParser(argument_default=argparse.SUPPRESS) | 
|  | 295 | >>> parser.add_argument('--foo') | 
|  | 296 | >>> parser.add_argument('bar', nargs='?') | 
|  | 297 | >>> parser.parse_args(['--foo', '1', 'BAR']) | 
|  | 298 | Namespace(bar='BAR', foo='1') | 
|  | 299 | >>> parser.parse_args([]) | 
|  | 300 | Namespace() | 
|  | 301 |  | 
|  | 302 |  | 
|  | 303 | parents | 
|  | 304 | ^^^^^^^ | 
|  | 305 |  | 
|  | 306 | Sometimes, several parsers share a common set of arguments. Rather than | 
| Benjamin Peterson | 90c5802 | 2010-03-03 01:55:09 +0000 | [diff] [blame] | 307 | repeating the definitions of these arguments, a single parser with all the | 
|  | 308 | shared arguments and passed to ``parents=`` argument to :class:`ArgumentParser` | 
|  | 309 | can be used.  The ``parents=`` argument takes a list of :class:`ArgumentParser` | 
|  | 310 | objects, collects all the positional and optional actions from them, and adds | 
|  | 311 | these actions to the :class:`ArgumentParser` object being constructed:: | 
| Benjamin Peterson | a39e966 | 2010-03-02 22:05:59 +0000 | [diff] [blame] | 312 |  | 
|  | 313 | >>> parent_parser = argparse.ArgumentParser(add_help=False) | 
|  | 314 | >>> parent_parser.add_argument('--parent', type=int) | 
|  | 315 |  | 
|  | 316 | >>> foo_parser = argparse.ArgumentParser(parents=[parent_parser]) | 
|  | 317 | >>> foo_parser.add_argument('foo') | 
|  | 318 | >>> foo_parser.parse_args(['--parent', '2', 'XXX']) | 
|  | 319 | Namespace(foo='XXX', parent=2) | 
|  | 320 |  | 
|  | 321 | >>> bar_parser = argparse.ArgumentParser(parents=[parent_parser]) | 
|  | 322 | >>> bar_parser.add_argument('--bar') | 
|  | 323 | >>> bar_parser.parse_args(['--bar', 'YYY']) | 
|  | 324 | Namespace(bar='YYY', parent=None) | 
|  | 325 |  | 
| Georg Brandl | d2decd9 | 2010-03-02 22:17:38 +0000 | [diff] [blame] | 326 | Note that most parent parsers will specify ``add_help=False``.  Otherwise, the | 
| Benjamin Peterson | 90c5802 | 2010-03-03 01:55:09 +0000 | [diff] [blame] | 327 | :class:`ArgumentParser` will see two ``-h/--help`` options (one in the parent | 
|  | 328 | and one in the child) and raise an error. | 
| Benjamin Peterson | a39e966 | 2010-03-02 22:05:59 +0000 | [diff] [blame] | 329 |  | 
|  | 330 |  | 
|  | 331 | formatter_class | 
|  | 332 | ^^^^^^^^^^^^^^^ | 
|  | 333 |  | 
| Benjamin Peterson | 90c5802 | 2010-03-03 01:55:09 +0000 | [diff] [blame] | 334 | :class:`ArgumentParser` objects allow the help formatting to be customized by | 
|  | 335 | specifying an alternate formatting class.  Currently, there are three such | 
|  | 336 | classes: :class:`argparse.RawDescriptionHelpFormatter`, | 
| Georg Brandl | d2decd9 | 2010-03-02 22:17:38 +0000 | [diff] [blame] | 337 | :class:`argparse.RawTextHelpFormatter` and | 
|  | 338 | :class:`argparse.ArgumentDefaultsHelpFormatter`.  The first two allow more | 
|  | 339 | control over how textual descriptions are displayed, while the last | 
|  | 340 | automatically adds information about argument default values. | 
| Benjamin Peterson | a39e966 | 2010-03-02 22:05:59 +0000 | [diff] [blame] | 341 |  | 
| Benjamin Peterson | 90c5802 | 2010-03-03 01:55:09 +0000 | [diff] [blame] | 342 | By default, :class:`ArgumentParser` objects line-wrap the description_ and | 
|  | 343 | epilog_ texts in command-line help messages:: | 
| Benjamin Peterson | a39e966 | 2010-03-02 22:05:59 +0000 | [diff] [blame] | 344 |  | 
|  | 345 | >>> parser = argparse.ArgumentParser( | 
|  | 346 | ...     prog='PROG', | 
|  | 347 | ...     description='''this description | 
|  | 348 | ...         was indented weird | 
|  | 349 | ...             but that is okay''', | 
|  | 350 | ...     epilog=''' | 
|  | 351 | ...             likewise for this epilog whose whitespace will | 
|  | 352 | ...         be cleaned up and whose words will be wrapped | 
|  | 353 | ...         across a couple lines''') | 
|  | 354 | >>> parser.print_help() | 
|  | 355 | usage: PROG [-h] | 
|  | 356 |  | 
|  | 357 | this description was indented weird but that is okay | 
|  | 358 |  | 
|  | 359 | optional arguments: | 
|  | 360 | -h, --help  show this help message and exit | 
|  | 361 |  | 
|  | 362 | likewise for this epilog whose whitespace will be cleaned up and whose words | 
|  | 363 | will be wrapped across a couple lines | 
|  | 364 |  | 
| Benjamin Peterson | 90c5802 | 2010-03-03 01:55:09 +0000 | [diff] [blame] | 365 | Passing :class:`argparse.RawDescriptionHelpFormatter` as ``formatter_class=`` | 
| Benjamin Peterson | c516d19 | 2010-03-03 02:04:24 +0000 | [diff] [blame] | 366 | indicates that description_ and epilog_ are already correctly formatted and | 
| Benjamin Peterson | 90c5802 | 2010-03-03 01:55:09 +0000 | [diff] [blame] | 367 | should not be line-wrapped:: | 
| Benjamin Peterson | a39e966 | 2010-03-02 22:05:59 +0000 | [diff] [blame] | 368 |  | 
|  | 369 | >>> parser = argparse.ArgumentParser( | 
|  | 370 | ...     prog='PROG', | 
|  | 371 | ...     formatter_class=argparse.RawDescriptionHelpFormatter, | 
|  | 372 | ...     description=textwrap.dedent('''\ | 
|  | 373 | ...         Please do not mess up this text! | 
|  | 374 | ...         -------------------------------- | 
|  | 375 | ...             I have indented it | 
|  | 376 | ...             exactly the way | 
|  | 377 | ...             I want it | 
|  | 378 | ...         ''')) | 
|  | 379 | >>> parser.print_help() | 
|  | 380 | usage: PROG [-h] | 
|  | 381 |  | 
|  | 382 | Please do not mess up this text! | 
|  | 383 | -------------------------------- | 
|  | 384 | I have indented it | 
|  | 385 | exactly the way | 
|  | 386 | I want it | 
|  | 387 |  | 
|  | 388 | optional arguments: | 
|  | 389 | -h, --help  show this help message and exit | 
|  | 390 |  | 
| Benjamin Peterson | 90c5802 | 2010-03-03 01:55:09 +0000 | [diff] [blame] | 391 | :class:`RawTextHelpFormatter` maintains whitespace for all sorts of help text | 
|  | 392 | including argument descriptions. | 
| Benjamin Peterson | a39e966 | 2010-03-02 22:05:59 +0000 | [diff] [blame] | 393 |  | 
| Benjamin Peterson | 90c5802 | 2010-03-03 01:55:09 +0000 | [diff] [blame] | 394 | The other formatter class available, :class:`ArgumentDefaultsHelpFormatter`, | 
| Georg Brandl | d2decd9 | 2010-03-02 22:17:38 +0000 | [diff] [blame] | 395 | will add information about the default value of each of the arguments:: | 
| Benjamin Peterson | a39e966 | 2010-03-02 22:05:59 +0000 | [diff] [blame] | 396 |  | 
|  | 397 | >>> parser = argparse.ArgumentParser( | 
|  | 398 | ...     prog='PROG', | 
|  | 399 | ...     formatter_class=argparse.ArgumentDefaultsHelpFormatter) | 
|  | 400 | >>> parser.add_argument('--foo', type=int, default=42, help='FOO!') | 
|  | 401 | >>> parser.add_argument('bar', nargs='*', default=[1, 2, 3], help='BAR!') | 
|  | 402 | >>> parser.print_help() | 
|  | 403 | usage: PROG [-h] [--foo FOO] [bar [bar ...]] | 
|  | 404 |  | 
|  | 405 | positional arguments: | 
|  | 406 | bar         BAR! (default: [1, 2, 3]) | 
|  | 407 |  | 
|  | 408 | optional arguments: | 
|  | 409 | -h, --help  show this help message and exit | 
|  | 410 | --foo FOO   FOO! (default: 42) | 
|  | 411 |  | 
|  | 412 |  | 
|  | 413 | conflict_handler | 
|  | 414 | ^^^^^^^^^^^^^^^^ | 
|  | 415 |  | 
| Benjamin Peterson | 90c5802 | 2010-03-03 01:55:09 +0000 | [diff] [blame] | 416 | :class:`ArgumentParser` objects do not allow two actions with the same option | 
|  | 417 | string.  By default, :class:`ArgumentParser` objects raises an exception if an | 
|  | 418 | attempt is made to create an argument with an option string that is already in | 
|  | 419 | use:: | 
| Benjamin Peterson | a39e966 | 2010-03-02 22:05:59 +0000 | [diff] [blame] | 420 |  | 
|  | 421 | >>> parser = argparse.ArgumentParser(prog='PROG') | 
|  | 422 | >>> parser.add_argument('-f', '--foo', help='old foo help') | 
|  | 423 | >>> parser.add_argument('--foo', help='new foo help') | 
|  | 424 | Traceback (most recent call last): | 
|  | 425 | .. | 
|  | 426 | ArgumentError: argument --foo: conflicting option string(s): --foo | 
|  | 427 |  | 
|  | 428 | Sometimes (e.g. when using parents_) it may be useful to simply override any | 
| Georg Brandl | d2decd9 | 2010-03-02 22:17:38 +0000 | [diff] [blame] | 429 | older arguments with the same option string.  To get this behavior, the value | 
| Benjamin Peterson | a39e966 | 2010-03-02 22:05:59 +0000 | [diff] [blame] | 430 | ``'resolve'`` can be supplied to the ``conflict_handler=`` argument of | 
| Benjamin Peterson | 90c5802 | 2010-03-03 01:55:09 +0000 | [diff] [blame] | 431 | :class:`ArgumentParser`:: | 
| Benjamin Peterson | a39e966 | 2010-03-02 22:05:59 +0000 | [diff] [blame] | 432 |  | 
|  | 433 | >>> parser = argparse.ArgumentParser(prog='PROG', conflict_handler='resolve') | 
|  | 434 | >>> parser.add_argument('-f', '--foo', help='old foo help') | 
|  | 435 | >>> parser.add_argument('--foo', help='new foo help') | 
|  | 436 | >>> parser.print_help() | 
|  | 437 | usage: PROG [-h] [-f FOO] [--foo FOO] | 
|  | 438 |  | 
|  | 439 | optional arguments: | 
|  | 440 | -h, --help  show this help message and exit | 
|  | 441 | -f FOO      old foo help | 
|  | 442 | --foo FOO   new foo help | 
|  | 443 |  | 
| Benjamin Peterson | 90c5802 | 2010-03-03 01:55:09 +0000 | [diff] [blame] | 444 | Note that :class:`ArgumentParser` objects only remove an action if all of its | 
|  | 445 | option strings are overridden.  So, in the example above, the old ``-f/--foo`` | 
|  | 446 | action is retained as the ``-f`` action, because only the ``--foo`` option | 
|  | 447 | string was overridden. | 
| Benjamin Peterson | a39e966 | 2010-03-02 22:05:59 +0000 | [diff] [blame] | 448 |  | 
|  | 449 |  | 
|  | 450 | prog | 
|  | 451 | ^^^^ | 
|  | 452 |  | 
| Benjamin Peterson | 90c5802 | 2010-03-03 01:55:09 +0000 | [diff] [blame] | 453 | By default, :class:`ArgumentParser` objects uses ``sys.argv[0]`` to determine | 
|  | 454 | how to display the name of the program in help messages.  This default is almost | 
| Ezio Melotti | 019551f | 2010-05-19 00:32:52 +0000 | [diff] [blame] | 455 | always desirable because it will make the help messages match how the program was | 
| Benjamin Peterson | 90c5802 | 2010-03-03 01:55:09 +0000 | [diff] [blame] | 456 | invoked on the command line.  For example, consider a file named | 
|  | 457 | ``myprogram.py`` with the following code:: | 
| Benjamin Peterson | a39e966 | 2010-03-02 22:05:59 +0000 | [diff] [blame] | 458 |  | 
|  | 459 | import argparse | 
|  | 460 | parser = argparse.ArgumentParser() | 
|  | 461 | parser.add_argument('--foo', help='foo help') | 
|  | 462 | args = parser.parse_args() | 
|  | 463 |  | 
|  | 464 | The help for this program will display ``myprogram.py`` as the program name | 
|  | 465 | (regardless of where the program was invoked from):: | 
|  | 466 |  | 
|  | 467 | $ python myprogram.py --help | 
|  | 468 | usage: myprogram.py [-h] [--foo FOO] | 
|  | 469 |  | 
|  | 470 | optional arguments: | 
|  | 471 | -h, --help  show this help message and exit | 
|  | 472 | --foo FOO   foo help | 
|  | 473 | $ cd .. | 
|  | 474 | $ python subdir\myprogram.py --help | 
|  | 475 | usage: myprogram.py [-h] [--foo FOO] | 
|  | 476 |  | 
|  | 477 | optional arguments: | 
|  | 478 | -h, --help  show this help message and exit | 
|  | 479 | --foo FOO   foo help | 
|  | 480 |  | 
|  | 481 | To change this default behavior, another value can be supplied using the | 
| Benjamin Peterson | 90c5802 | 2010-03-03 01:55:09 +0000 | [diff] [blame] | 482 | ``prog=`` argument to :class:`ArgumentParser`:: | 
| Benjamin Peterson | a39e966 | 2010-03-02 22:05:59 +0000 | [diff] [blame] | 483 |  | 
|  | 484 | >>> parser = argparse.ArgumentParser(prog='myprogram') | 
|  | 485 | >>> parser.print_help() | 
|  | 486 | usage: myprogram [-h] | 
|  | 487 |  | 
|  | 488 | optional arguments: | 
|  | 489 | -h, --help  show this help message and exit | 
|  | 490 |  | 
|  | 491 | Note that the program name, whether determined from ``sys.argv[0]`` or from the | 
|  | 492 | ``prog=`` argument, is available to help messages using the ``%(prog)s`` format | 
|  | 493 | specifier. | 
|  | 494 |  | 
|  | 495 | :: | 
|  | 496 |  | 
|  | 497 | >>> parser = argparse.ArgumentParser(prog='myprogram') | 
|  | 498 | >>> parser.add_argument('--foo', help='foo of the %(prog)s program') | 
|  | 499 | >>> parser.print_help() | 
|  | 500 | usage: myprogram [-h] [--foo FOO] | 
|  | 501 |  | 
|  | 502 | optional arguments: | 
|  | 503 | -h, --help  show this help message and exit | 
|  | 504 | --foo FOO   foo of the myprogram program | 
|  | 505 |  | 
|  | 506 |  | 
|  | 507 | usage | 
|  | 508 | ^^^^^ | 
|  | 509 |  | 
| Benjamin Peterson | 90c5802 | 2010-03-03 01:55:09 +0000 | [diff] [blame] | 510 | By default, :class:`ArgumentParser` calculates the usage message from the | 
| Benjamin Peterson | a39e966 | 2010-03-02 22:05:59 +0000 | [diff] [blame] | 511 | arguments it contains:: | 
|  | 512 |  | 
|  | 513 | >>> parser = argparse.ArgumentParser(prog='PROG') | 
|  | 514 | >>> parser.add_argument('--foo', nargs='?', help='foo help') | 
|  | 515 | >>> parser.add_argument('bar', nargs='+', help='bar help') | 
|  | 516 | >>> parser.print_help() | 
|  | 517 | usage: PROG [-h] [--foo [FOO]] bar [bar ...] | 
|  | 518 |  | 
|  | 519 | positional arguments: | 
|  | 520 | bar          bar help | 
|  | 521 |  | 
|  | 522 | optional arguments: | 
|  | 523 | -h, --help   show this help message and exit | 
|  | 524 | --foo [FOO]  foo help | 
|  | 525 |  | 
| Benjamin Peterson | 90c5802 | 2010-03-03 01:55:09 +0000 | [diff] [blame] | 526 | The default message can be overridden with the ``usage=`` keyword argument:: | 
| Benjamin Peterson | a39e966 | 2010-03-02 22:05:59 +0000 | [diff] [blame] | 527 |  | 
|  | 528 | >>> parser = argparse.ArgumentParser(prog='PROG', usage='%(prog)s [options]') | 
|  | 529 | >>> parser.add_argument('--foo', nargs='?', help='foo help') | 
|  | 530 | >>> parser.add_argument('bar', nargs='+', help='bar help') | 
|  | 531 | >>> parser.print_help() | 
|  | 532 | usage: PROG [options] | 
|  | 533 |  | 
|  | 534 | positional arguments: | 
|  | 535 | bar          bar help | 
|  | 536 |  | 
|  | 537 | optional arguments: | 
|  | 538 | -h, --help   show this help message and exit | 
|  | 539 | --foo [FOO]  foo help | 
|  | 540 |  | 
| Benjamin Peterson | 90c5802 | 2010-03-03 01:55:09 +0000 | [diff] [blame] | 541 | The ``%(prog)s`` format specifier is available to fill in the program name in | 
|  | 542 | your usage messages. | 
| Benjamin Peterson | a39e966 | 2010-03-02 22:05:59 +0000 | [diff] [blame] | 543 |  | 
|  | 544 |  | 
|  | 545 | The add_argument() method | 
|  | 546 | ------------------------- | 
|  | 547 |  | 
| Benjamin Peterson | 90c5802 | 2010-03-03 01:55:09 +0000 | [diff] [blame] | 548 | .. method:: ArgumentParser.add_argument(name or flags..., [action], [nargs], [const], [default], [type], [choices], [required], [help], [metavar], [dest]) | 
| Benjamin Peterson | a39e966 | 2010-03-02 22:05:59 +0000 | [diff] [blame] | 549 |  | 
| Georg Brandl | d2decd9 | 2010-03-02 22:17:38 +0000 | [diff] [blame] | 550 | Define how a single command line argument should be parsed.  Each parameter | 
| Benjamin Peterson | a39e966 | 2010-03-02 22:05:59 +0000 | [diff] [blame] | 551 | has its own more detailed description below, but in short they are: | 
|  | 552 |  | 
|  | 553 | * `name or flags`_ - Either a name or a list of option strings, e.g. ``foo`` | 
|  | 554 | or ``-f, --foo`` | 
|  | 555 |  | 
|  | 556 | * action_ - The basic type of action to be taken when this argument is | 
|  | 557 | encountered at the command-line. | 
|  | 558 |  | 
|  | 559 | * nargs_ - The number of command-line arguments that should be consumed. | 
|  | 560 |  | 
|  | 561 | * const_ - A constant value required by some action_ and nargs_ selections. | 
|  | 562 |  | 
|  | 563 | * default_ - The value produced if the argument is absent from the | 
|  | 564 | command-line. | 
|  | 565 |  | 
|  | 566 | * type_ - The type to which the command-line arg should be converted. | 
|  | 567 |  | 
|  | 568 | * choices_ - A container of the allowable values for the argument. | 
|  | 569 |  | 
|  | 570 | * required_ - Whether or not the command-line option may be omitted | 
|  | 571 | (optionals only). | 
|  | 572 |  | 
|  | 573 | * help_ - A brief description of what the argument does. | 
|  | 574 |  | 
|  | 575 | * metavar_ - A name for the argument in usage messages. | 
|  | 576 |  | 
|  | 577 | * dest_ - The name of the attribute to be added to the object returned by | 
|  | 578 | :meth:`parse_args`. | 
|  | 579 |  | 
| Benjamin Peterson | 90c5802 | 2010-03-03 01:55:09 +0000 | [diff] [blame] | 580 | The following sections describe how each of these are used. | 
| Benjamin Peterson | a39e966 | 2010-03-02 22:05:59 +0000 | [diff] [blame] | 581 |  | 
|  | 582 | name or flags | 
|  | 583 | ^^^^^^^^^^^^^ | 
|  | 584 |  | 
| Benjamin Peterson | 90c5802 | 2010-03-03 01:55:09 +0000 | [diff] [blame] | 585 | The :meth:`add_argument` method must know whether an optional argument, like | 
|  | 586 | ``-f`` or ``--foo``, or a positional argument, like a list of filenames, is | 
|  | 587 | expected.  The first arguments passed to :meth:`add_argument` must therefore be | 
|  | 588 | either a series of flags, or a simple argument name.  For example, an optional | 
|  | 589 | argument could be created like:: | 
| Benjamin Peterson | a39e966 | 2010-03-02 22:05:59 +0000 | [diff] [blame] | 590 |  | 
|  | 591 | >>> parser.add_argument('-f', '--foo') | 
|  | 592 |  | 
|  | 593 | while a positional argument could be created like:: | 
|  | 594 |  | 
|  | 595 | >>> parser.add_argument('bar') | 
|  | 596 |  | 
|  | 597 | When :meth:`parse_args` is called, optional arguments will be identified by the | 
|  | 598 | ``-`` prefix, and the remaining arguments will be assumed to be positional:: | 
|  | 599 |  | 
|  | 600 | >>> parser = argparse.ArgumentParser(prog='PROG') | 
|  | 601 | >>> parser.add_argument('-f', '--foo') | 
|  | 602 | >>> parser.add_argument('bar') | 
|  | 603 | >>> parser.parse_args(['BAR']) | 
|  | 604 | Namespace(bar='BAR', foo=None) | 
|  | 605 | >>> parser.parse_args(['BAR', '--foo', 'FOO']) | 
|  | 606 | Namespace(bar='BAR', foo='FOO') | 
|  | 607 | >>> parser.parse_args(['--foo', 'FOO']) | 
|  | 608 | usage: PROG [-h] [-f FOO] bar | 
|  | 609 | PROG: error: too few arguments | 
|  | 610 |  | 
|  | 611 | action | 
|  | 612 | ^^^^^^ | 
|  | 613 |  | 
| Georg Brandl | d2decd9 | 2010-03-02 22:17:38 +0000 | [diff] [blame] | 614 | :class:`ArgumentParser` objects associate command-line args with actions.  These | 
| Benjamin Peterson | a39e966 | 2010-03-02 22:05:59 +0000 | [diff] [blame] | 615 | actions can do just about anything with the command-line args associated with | 
|  | 616 | them, though most actions simply add an attribute to the object returned by | 
| Benjamin Peterson | 90c5802 | 2010-03-03 01:55:09 +0000 | [diff] [blame] | 617 | :meth:`parse_args`.  The ``action`` keyword argument specifies how the | 
|  | 618 | command-line args should be handled. The supported actions are: | 
| Benjamin Peterson | a39e966 | 2010-03-02 22:05:59 +0000 | [diff] [blame] | 619 |  | 
| Georg Brandl | d2decd9 | 2010-03-02 22:17:38 +0000 | [diff] [blame] | 620 | * ``'store'`` - This just stores the argument's value.  This is the default | 
| Benjamin Peterson | a39e966 | 2010-03-02 22:05:59 +0000 | [diff] [blame] | 621 | action. For example:: | 
|  | 622 |  | 
|  | 623 | >>> parser = argparse.ArgumentParser() | 
|  | 624 | >>> parser.add_argument('--foo') | 
|  | 625 | >>> parser.parse_args('--foo 1'.split()) | 
|  | 626 | Namespace(foo='1') | 
|  | 627 |  | 
|  | 628 | * ``'store_const'`` - This stores the value specified by the const_ keyword | 
| Benjamin Peterson | 90c5802 | 2010-03-03 01:55:09 +0000 | [diff] [blame] | 629 | argument.  (Note that the const_ keyword argument defaults to the rather | 
|  | 630 | unhelpful ``None``.)  The ``'store_const'`` action is most commonly used with | 
|  | 631 | optional arguments that specify some sort of flag.  For example:: | 
| Benjamin Peterson | a39e966 | 2010-03-02 22:05:59 +0000 | [diff] [blame] | 632 |  | 
|  | 633 | >>> parser = argparse.ArgumentParser() | 
|  | 634 | >>> parser.add_argument('--foo', action='store_const', const=42) | 
|  | 635 | >>> parser.parse_args('--foo'.split()) | 
|  | 636 | Namespace(foo=42) | 
|  | 637 |  | 
|  | 638 | * ``'store_true'`` and ``'store_false'`` - These store the values ``True`` and | 
| Benjamin Peterson | 90c5802 | 2010-03-03 01:55:09 +0000 | [diff] [blame] | 639 | ``False`` respectively.  These are special cases of ``'store_const'``.  For | 
|  | 640 | example:: | 
| Benjamin Peterson | a39e966 | 2010-03-02 22:05:59 +0000 | [diff] [blame] | 641 |  | 
|  | 642 | >>> parser = argparse.ArgumentParser() | 
|  | 643 | >>> parser.add_argument('--foo', action='store_true') | 
|  | 644 | >>> parser.add_argument('--bar', action='store_false') | 
|  | 645 | >>> parser.parse_args('--foo --bar'.split()) | 
|  | 646 | Namespace(bar=False, foo=True) | 
|  | 647 |  | 
|  | 648 | * ``'append'`` - This stores a list, and appends each argument value to the | 
| Benjamin Peterson | 90c5802 | 2010-03-03 01:55:09 +0000 | [diff] [blame] | 649 | list.  This is useful to allow an option to be specified multiple times. | 
|  | 650 | Example usage:: | 
| Benjamin Peterson | a39e966 | 2010-03-02 22:05:59 +0000 | [diff] [blame] | 651 |  | 
|  | 652 | >>> parser = argparse.ArgumentParser() | 
|  | 653 | >>> parser.add_argument('--foo', action='append') | 
|  | 654 | >>> parser.parse_args('--foo 1 --foo 2'.split()) | 
|  | 655 | Namespace(foo=['1', '2']) | 
|  | 656 |  | 
|  | 657 | * ``'append_const'`` - This stores a list, and appends the value specified by | 
| Benjamin Peterson | 90c5802 | 2010-03-03 01:55:09 +0000 | [diff] [blame] | 658 | the const_ keyword argument to the list.  (Note that the const_ keyword | 
|  | 659 | argument defaults to ``None``.)  The ``'append_const'`` action is typically | 
|  | 660 | useful when multiple arguments need to store constants to the same list. For | 
|  | 661 | example:: | 
| Benjamin Peterson | a39e966 | 2010-03-02 22:05:59 +0000 | [diff] [blame] | 662 |  | 
|  | 663 | >>> parser = argparse.ArgumentParser() | 
|  | 664 | >>> parser.add_argument('--str', dest='types', action='append_const', const=str) | 
|  | 665 | >>> parser.add_argument('--int', dest='types', action='append_const', const=int) | 
|  | 666 | >>> parser.parse_args('--str --int'.split()) | 
|  | 667 | Namespace(types=[<type 'str'>, <type 'int'>]) | 
|  | 668 |  | 
|  | 669 | * ``'version'`` - This expects a ``version=`` keyword argument in the | 
|  | 670 | :meth:`add_argument` call, and prints version information and exits when | 
|  | 671 | invoked. | 
|  | 672 |  | 
|  | 673 | >>> import argparse | 
|  | 674 | >>> parser = argparse.ArgumentParser(prog='PROG') | 
| Steven Bethard | 74bd9cf | 2010-05-24 02:38:00 +0000 | [diff] [blame^] | 675 | >>> parser.add_argument('--version', action='version', version='%(prog)s 2.0') | 
|  | 676 | >>> parser.parse_args(['--version']) | 
| Benjamin Peterson | a39e966 | 2010-03-02 22:05:59 +0000 | [diff] [blame] | 677 | PROG 2.0 | 
|  | 678 |  | 
|  | 679 | You can also specify an arbitrary action by passing an object that implements | 
| Benjamin Peterson | 90c5802 | 2010-03-03 01:55:09 +0000 | [diff] [blame] | 680 | the Action API.  The easiest way to do this is to extend | 
|  | 681 | :class:`argparse.Action`, supplying an appropriate ``__call__`` method.  The | 
|  | 682 | ``__call__`` method should accept four parameters: | 
| Benjamin Peterson | a39e966 | 2010-03-02 22:05:59 +0000 | [diff] [blame] | 683 |  | 
|  | 684 | * ``parser`` - The ArgumentParser object which contains this action. | 
|  | 685 |  | 
|  | 686 | * ``namespace`` - The namespace object that will be returned by | 
| Georg Brandl | d2decd9 | 2010-03-02 22:17:38 +0000 | [diff] [blame] | 687 | :meth:`parse_args`.  Most actions add an attribute to this object. | 
| Benjamin Peterson | a39e966 | 2010-03-02 22:05:59 +0000 | [diff] [blame] | 688 |  | 
|  | 689 | * ``values`` - The associated command-line args, with any type-conversions | 
|  | 690 | applied.  (Type-conversions are specified with the type_ keyword argument to | 
|  | 691 | :meth:`add_argument`. | 
|  | 692 |  | 
|  | 693 | * ``option_string`` - The option string that was used to invoke this action. | 
|  | 694 | The ``option_string`` argument is optional, and will be absent if the action | 
|  | 695 | is associated with a positional argument. | 
|  | 696 |  | 
| Benjamin Peterson | 90c5802 | 2010-03-03 01:55:09 +0000 | [diff] [blame] | 697 | An example of a custom action:: | 
| Benjamin Peterson | a39e966 | 2010-03-02 22:05:59 +0000 | [diff] [blame] | 698 |  | 
|  | 699 | >>> class FooAction(argparse.Action): | 
|  | 700 | ...     def __call__(self, parser, namespace, values, option_string=None): | 
|  | 701 | ...     print '%r %r %r' % (namespace, values, option_string) | 
|  | 702 | ...     setattr(namespace, self.dest, values) | 
|  | 703 | ... | 
|  | 704 | >>> parser = argparse.ArgumentParser() | 
|  | 705 | >>> parser.add_argument('--foo', action=FooAction) | 
|  | 706 | >>> parser.add_argument('bar', action=FooAction) | 
|  | 707 | >>> args = parser.parse_args('1 --foo 2'.split()) | 
|  | 708 | Namespace(bar=None, foo=None) '1' None | 
|  | 709 | Namespace(bar='1', foo=None) '2' '--foo' | 
|  | 710 | >>> args | 
|  | 711 | Namespace(bar='1', foo='2') | 
|  | 712 |  | 
|  | 713 |  | 
|  | 714 | nargs | 
|  | 715 | ^^^^^ | 
|  | 716 |  | 
|  | 717 | ArgumentParser objects usually associate a single command-line argument with a | 
| Benjamin Peterson | 90c5802 | 2010-03-03 01:55:09 +0000 | [diff] [blame] | 718 | single action to be taken.  The ``nargs`` keyword argument associates a | 
|  | 719 | different number of command-line arguments with a single action..  The supported | 
|  | 720 | values are: | 
| Benjamin Peterson | a39e966 | 2010-03-02 22:05:59 +0000 | [diff] [blame] | 721 |  | 
| Georg Brandl | d2decd9 | 2010-03-02 22:17:38 +0000 | [diff] [blame] | 722 | * N (an integer).  N args from the command-line will be gathered together into a | 
|  | 723 | list.  For example:: | 
| Benjamin Peterson | a39e966 | 2010-03-02 22:05:59 +0000 | [diff] [blame] | 724 |  | 
|  | 725 | >>> parser = argparse.ArgumentParser() | 
|  | 726 | >>> parser.add_argument('--foo', nargs=2) | 
|  | 727 | >>> parser.add_argument('bar', nargs=1) | 
|  | 728 | >>> parser.parse_args('c --foo a b'.split()) | 
|  | 729 | Namespace(bar=['c'], foo=['a', 'b']) | 
|  | 730 |  | 
|  | 731 | Note that ``nargs=1`` produces a list of one item.  This is different from | 
|  | 732 | the default, in which the item is produced by itself. | 
|  | 733 |  | 
|  | 734 | * ``'?'``. One arg will be consumed from the command-line if possible, and | 
|  | 735 | produced as a single item.  If no command-line arg is present, the value from | 
|  | 736 | default_ will be produced.  Note that for optional arguments, there is an | 
|  | 737 | additional case - the option string is present but not followed by a | 
|  | 738 | command-line arg.  In this case the value from const_ will be produced.  Some | 
|  | 739 | examples to illustrate this:: | 
|  | 740 |  | 
| Georg Brandl | d2decd9 | 2010-03-02 22:17:38 +0000 | [diff] [blame] | 741 | >>> parser = argparse.ArgumentParser() | 
|  | 742 | >>> parser.add_argument('--foo', nargs='?', const='c', default='d') | 
|  | 743 | >>> parser.add_argument('bar', nargs='?', default='d') | 
|  | 744 | >>> parser.parse_args('XX --foo YY'.split()) | 
|  | 745 | Namespace(bar='XX', foo='YY') | 
|  | 746 | >>> parser.parse_args('XX --foo'.split()) | 
|  | 747 | Namespace(bar='XX', foo='c') | 
|  | 748 | >>> parser.parse_args(''.split()) | 
|  | 749 | Namespace(bar='d', foo='d') | 
| Benjamin Peterson | a39e966 | 2010-03-02 22:05:59 +0000 | [diff] [blame] | 750 |  | 
| Georg Brandl | d2decd9 | 2010-03-02 22:17:38 +0000 | [diff] [blame] | 751 | One of the more common uses of ``nargs='?'`` is to allow optional input and | 
|  | 752 | output files:: | 
| Benjamin Peterson | a39e966 | 2010-03-02 22:05:59 +0000 | [diff] [blame] | 753 |  | 
| Georg Brandl | d2decd9 | 2010-03-02 22:17:38 +0000 | [diff] [blame] | 754 | >>> parser = argparse.ArgumentParser() | 
|  | 755 | >>> parser.add_argument('infile', nargs='?', type=argparse.FileType('r'), default=sys.stdin) | 
|  | 756 | >>> parser.add_argument('outfile', nargs='?', type=argparse.FileType('w'), default=sys.stdout) | 
|  | 757 | >>> parser.parse_args(['input.txt', 'output.txt']) | 
|  | 758 | Namespace(infile=<open file 'input.txt', mode 'r' at 0x...>, outfile=<open file 'output.txt', mode 'w' at 0x...>) | 
|  | 759 | >>> parser.parse_args([]) | 
|  | 760 | Namespace(infile=<open file '<stdin>', mode 'r' at 0x...>, outfile=<open file '<stdout>', mode 'w' at 0x...>) | 
| Benjamin Peterson | a39e966 | 2010-03-02 22:05:59 +0000 | [diff] [blame] | 761 |  | 
| Georg Brandl | d2decd9 | 2010-03-02 22:17:38 +0000 | [diff] [blame] | 762 | * ``'*'``.  All command-line args present are gathered into a list.  Note that | 
|  | 763 | it generally doesn't make much sense to have more than one positional argument | 
|  | 764 | with ``nargs='*'``, but multiple optional arguments with ``nargs='*'`` is | 
|  | 765 | possible.  For example:: | 
| Benjamin Peterson | a39e966 | 2010-03-02 22:05:59 +0000 | [diff] [blame] | 766 |  | 
| Georg Brandl | d2decd9 | 2010-03-02 22:17:38 +0000 | [diff] [blame] | 767 | >>> parser = argparse.ArgumentParser() | 
|  | 768 | >>> parser.add_argument('--foo', nargs='*') | 
|  | 769 | >>> parser.add_argument('--bar', nargs='*') | 
|  | 770 | >>> parser.add_argument('baz', nargs='*') | 
|  | 771 | >>> parser.parse_args('a b --foo x y --bar 1 2'.split()) | 
|  | 772 | Namespace(bar=['1', '2'], baz=['a', 'b'], foo=['x', 'y']) | 
| Benjamin Peterson | a39e966 | 2010-03-02 22:05:59 +0000 | [diff] [blame] | 773 |  | 
|  | 774 | * ``'+'``. Just like ``'*'``, all command-line args present are gathered into a | 
|  | 775 | list.  Additionally, an error message will be generated if there wasn't at | 
|  | 776 | least one command-line arg present.  For example:: | 
|  | 777 |  | 
| Georg Brandl | d2decd9 | 2010-03-02 22:17:38 +0000 | [diff] [blame] | 778 | >>> parser = argparse.ArgumentParser(prog='PROG') | 
|  | 779 | >>> parser.add_argument('foo', nargs='+') | 
|  | 780 | >>> parser.parse_args('a b'.split()) | 
|  | 781 | Namespace(foo=['a', 'b']) | 
|  | 782 | >>> parser.parse_args(''.split()) | 
|  | 783 | usage: PROG [-h] foo [foo ...] | 
|  | 784 | PROG: error: too few arguments | 
| Benjamin Peterson | a39e966 | 2010-03-02 22:05:59 +0000 | [diff] [blame] | 785 |  | 
|  | 786 | If the ``nargs`` keyword argument is not provided, the number of args consumed | 
| Georg Brandl | d2decd9 | 2010-03-02 22:17:38 +0000 | [diff] [blame] | 787 | is determined by the action_.  Generally this means a single command-line arg | 
| Benjamin Peterson | a39e966 | 2010-03-02 22:05:59 +0000 | [diff] [blame] | 788 | will be consumed and a single item (not a list) will be produced. | 
|  | 789 |  | 
|  | 790 |  | 
|  | 791 | const | 
|  | 792 | ^^^^^ | 
|  | 793 |  | 
|  | 794 | The ``const`` argument of :meth:`add_argument` is used to hold constant values | 
|  | 795 | that are not read from the command line but are required for the various | 
|  | 796 | ArgumentParser actions.  The two most common uses of it are: | 
|  | 797 |  | 
|  | 798 | * When :meth:`add_argument` is called with ``action='store_const'`` or | 
|  | 799 | ``action='append_const'``.  These actions add the ``const`` value to one of | 
|  | 800 | the attributes of the object returned by :meth:`parse_args`.  See the action_ | 
|  | 801 | description for examples. | 
|  | 802 |  | 
|  | 803 | * When :meth:`add_argument` is called with option strings (like ``-f`` or | 
| Georg Brandl | d2decd9 | 2010-03-02 22:17:38 +0000 | [diff] [blame] | 804 | ``--foo``) and ``nargs='?'``.  This creates an optional argument that can be | 
| Benjamin Peterson | a39e966 | 2010-03-02 22:05:59 +0000 | [diff] [blame] | 805 | followed by zero or one command-line args.  When parsing the command-line, if | 
|  | 806 | the option string is encountered with no command-line arg following it, the | 
|  | 807 | value of ``const`` will be assumed instead. See the nargs_ description for | 
|  | 808 | examples. | 
|  | 809 |  | 
|  | 810 | The ``const`` keyword argument defaults to ``None``. | 
|  | 811 |  | 
|  | 812 |  | 
|  | 813 | default | 
|  | 814 | ^^^^^^^ | 
|  | 815 |  | 
|  | 816 | All optional arguments and some positional arguments may be omitted at the | 
|  | 817 | command-line.  The ``default`` keyword argument of :meth:`add_argument`, whose | 
|  | 818 | value defaults to ``None``, specifies what value should be used if the | 
|  | 819 | command-line arg is not present.  For optional arguments, the ``default`` value | 
|  | 820 | is used when the option string was not present at the command line:: | 
|  | 821 |  | 
|  | 822 | >>> parser = argparse.ArgumentParser() | 
|  | 823 | >>> parser.add_argument('--foo', default=42) | 
|  | 824 | >>> parser.parse_args('--foo 2'.split()) | 
|  | 825 | Namespace(foo='2') | 
|  | 826 | >>> parser.parse_args(''.split()) | 
|  | 827 | Namespace(foo=42) | 
|  | 828 |  | 
|  | 829 | For positional arguments with nargs_ ``='?'`` or ``'*'``, the ``default`` value | 
|  | 830 | is used when no command-line arg was present:: | 
|  | 831 |  | 
|  | 832 | >>> parser = argparse.ArgumentParser() | 
|  | 833 | >>> parser.add_argument('foo', nargs='?', default=42) | 
|  | 834 | >>> parser.parse_args('a'.split()) | 
|  | 835 | Namespace(foo='a') | 
|  | 836 | >>> parser.parse_args(''.split()) | 
|  | 837 | Namespace(foo=42) | 
|  | 838 |  | 
|  | 839 |  | 
| Benjamin Peterson | 90c5802 | 2010-03-03 01:55:09 +0000 | [diff] [blame] | 840 | Providing ``default=argparse.SUPPRESS`` causes no attribute to be added if the | 
|  | 841 | command-line argument was not present.:: | 
| Benjamin Peterson | a39e966 | 2010-03-02 22:05:59 +0000 | [diff] [blame] | 842 |  | 
|  | 843 | >>> parser = argparse.ArgumentParser() | 
|  | 844 | >>> parser.add_argument('--foo', default=argparse.SUPPRESS) | 
|  | 845 | >>> parser.parse_args([]) | 
|  | 846 | Namespace() | 
|  | 847 | >>> parser.parse_args(['--foo', '1']) | 
|  | 848 | Namespace(foo='1') | 
|  | 849 |  | 
|  | 850 |  | 
|  | 851 | type | 
|  | 852 | ^^^^ | 
|  | 853 |  | 
|  | 854 | By default, ArgumentParser objects read command-line args in as simple strings. | 
|  | 855 | However, quite often the command-line string should instead be interpreted as | 
| Benjamin Peterson | 90c5802 | 2010-03-03 01:55:09 +0000 | [diff] [blame] | 856 | another type, like a :class:`float`, :class:`int` or :class:`file`.  The | 
|  | 857 | ``type`` keyword argument of :meth:`add_argument` allows any necessary | 
| Georg Brandl | 21e99f4 | 2010-03-07 15:23:59 +0000 | [diff] [blame] | 858 | type-checking and type-conversions to be performed.  Many common built-in types | 
| Benjamin Peterson | 90c5802 | 2010-03-03 01:55:09 +0000 | [diff] [blame] | 859 | can be used directly as the value of the ``type`` argument:: | 
| Benjamin Peterson | a39e966 | 2010-03-02 22:05:59 +0000 | [diff] [blame] | 860 |  | 
|  | 861 | >>> parser = argparse.ArgumentParser() | 
|  | 862 | >>> parser.add_argument('foo', type=int) | 
|  | 863 | >>> parser.add_argument('bar', type=file) | 
|  | 864 | >>> parser.parse_args('2 temp.txt'.split()) | 
|  | 865 | Namespace(bar=<open file 'temp.txt', mode 'r' at 0x...>, foo=2) | 
|  | 866 |  | 
|  | 867 | To ease the use of various types of files, the argparse module provides the | 
|  | 868 | factory FileType which takes the ``mode=`` and ``bufsize=`` arguments of the | 
| Georg Brandl | d2decd9 | 2010-03-02 22:17:38 +0000 | [diff] [blame] | 869 | ``file`` object.  For example, ``FileType('w')`` can be used to create a | 
| Benjamin Peterson | a39e966 | 2010-03-02 22:05:59 +0000 | [diff] [blame] | 870 | writable file:: | 
|  | 871 |  | 
|  | 872 | >>> parser = argparse.ArgumentParser() | 
|  | 873 | >>> parser.add_argument('bar', type=argparse.FileType('w')) | 
|  | 874 | >>> parser.parse_args(['out.txt']) | 
|  | 875 | Namespace(bar=<open file 'out.txt', mode 'w' at 0x...>) | 
|  | 876 |  | 
| Benjamin Peterson | 90c5802 | 2010-03-03 01:55:09 +0000 | [diff] [blame] | 877 | ``type=`` can take any callable that takes a single string argument and returns | 
|  | 878 | the type-converted value:: | 
| Benjamin Peterson | a39e966 | 2010-03-02 22:05:59 +0000 | [diff] [blame] | 879 |  | 
|  | 880 | >>> def perfect_square(string): | 
|  | 881 | ...     value = int(string) | 
|  | 882 | ...     sqrt = math.sqrt(value) | 
|  | 883 | ...     if sqrt != int(sqrt): | 
|  | 884 | ...         msg = "%r is not a perfect square" % string | 
|  | 885 | ...         raise argparse.ArgumentTypeError(msg) | 
|  | 886 | ...     return value | 
|  | 887 | ... | 
|  | 888 | >>> parser = argparse.ArgumentParser(prog='PROG') | 
|  | 889 | >>> parser.add_argument('foo', type=perfect_square) | 
|  | 890 | >>> parser.parse_args('9'.split()) | 
|  | 891 | Namespace(foo=9) | 
|  | 892 | >>> parser.parse_args('7'.split()) | 
|  | 893 | usage: PROG [-h] foo | 
|  | 894 | PROG: error: argument foo: '7' is not a perfect square | 
|  | 895 |  | 
| Benjamin Peterson | 90c5802 | 2010-03-03 01:55:09 +0000 | [diff] [blame] | 896 | The choices_ keyword argument may be more convenient for type checkers that | 
|  | 897 | simply check against a range of values:: | 
| Benjamin Peterson | a39e966 | 2010-03-02 22:05:59 +0000 | [diff] [blame] | 898 |  | 
|  | 899 | >>> parser = argparse.ArgumentParser(prog='PROG') | 
|  | 900 | >>> parser.add_argument('foo', type=int, choices=xrange(5, 10)) | 
|  | 901 | >>> parser.parse_args('7'.split()) | 
|  | 902 | Namespace(foo=7) | 
|  | 903 | >>> parser.parse_args('11'.split()) | 
|  | 904 | usage: PROG [-h] {5,6,7,8,9} | 
|  | 905 | PROG: error: argument foo: invalid choice: 11 (choose from 5, 6, 7, 8, 9) | 
|  | 906 |  | 
|  | 907 | See the choices_ section for more details. | 
|  | 908 |  | 
|  | 909 |  | 
|  | 910 | choices | 
|  | 911 | ^^^^^^^ | 
|  | 912 |  | 
|  | 913 | Some command-line args should be selected from a restricted set of values. | 
| Benjamin Peterson | 90c5802 | 2010-03-03 01:55:09 +0000 | [diff] [blame] | 914 | These can be handled by passing a container object as the ``choices`` keyword | 
|  | 915 | argument to :meth:`add_argument`.  When the command-line is parsed, arg values | 
|  | 916 | will be checked, and an error message will be displayed if the arg was not one | 
|  | 917 | of the acceptable values:: | 
| Benjamin Peterson | a39e966 | 2010-03-02 22:05:59 +0000 | [diff] [blame] | 918 |  | 
|  | 919 | >>> parser = argparse.ArgumentParser(prog='PROG') | 
|  | 920 | >>> parser.add_argument('foo', choices='abc') | 
|  | 921 | >>> parser.parse_args('c'.split()) | 
|  | 922 | Namespace(foo='c') | 
|  | 923 | >>> parser.parse_args('X'.split()) | 
|  | 924 | usage: PROG [-h] {a,b,c} | 
|  | 925 | PROG: error: argument foo: invalid choice: 'X' (choose from 'a', 'b', 'c') | 
|  | 926 |  | 
|  | 927 | Note that inclusion in the ``choices`` container is checked after any type_ | 
|  | 928 | conversions have been performed, so the type of the objects in the ``choices`` | 
|  | 929 | container should match the type_ specified:: | 
|  | 930 |  | 
|  | 931 | >>> parser = argparse.ArgumentParser(prog='PROG') | 
|  | 932 | >>> parser.add_argument('foo', type=complex, choices=[1, 1j]) | 
|  | 933 | >>> parser.parse_args('1j'.split()) | 
|  | 934 | Namespace(foo=1j) | 
|  | 935 | >>> parser.parse_args('-- -4'.split()) | 
|  | 936 | usage: PROG [-h] {1,1j} | 
|  | 937 | PROG: error: argument foo: invalid choice: (-4+0j) (choose from 1, 1j) | 
|  | 938 |  | 
|  | 939 | Any object that supports the ``in`` operator can be passed as the ``choices`` | 
| Georg Brandl | d2decd9 | 2010-03-02 22:17:38 +0000 | [diff] [blame] | 940 | value, so :class:`dict` objects, :class:`set` objects, custom containers, | 
|  | 941 | etc. are all supported. | 
| Benjamin Peterson | a39e966 | 2010-03-02 22:05:59 +0000 | [diff] [blame] | 942 |  | 
|  | 943 |  | 
|  | 944 | required | 
|  | 945 | ^^^^^^^^ | 
|  | 946 |  | 
|  | 947 | In general, the argparse module assumes that flags like ``-f`` and ``--bar`` | 
|  | 948 | indicate *optional* arguments, which can always be omitted at the command-line. | 
| Benjamin Peterson | 90c5802 | 2010-03-03 01:55:09 +0000 | [diff] [blame] | 949 | To make an option *required*, ``True`` can be specified for the ``required=`` | 
|  | 950 | keyword argument to :meth:`add_argument`:: | 
| Benjamin Peterson | a39e966 | 2010-03-02 22:05:59 +0000 | [diff] [blame] | 951 |  | 
|  | 952 | >>> parser = argparse.ArgumentParser() | 
|  | 953 | >>> parser.add_argument('--foo', required=True) | 
|  | 954 | >>> parser.parse_args(['--foo', 'BAR']) | 
|  | 955 | Namespace(foo='BAR') | 
|  | 956 | >>> parser.parse_args([]) | 
|  | 957 | usage: argparse.py [-h] [--foo FOO] | 
|  | 958 | argparse.py: error: option --foo is required | 
|  | 959 |  | 
|  | 960 | As the example shows, if an option is marked as ``required``, :meth:`parse_args` | 
|  | 961 | will report an error if that option is not present at the command line. | 
|  | 962 |  | 
| Benjamin Peterson | 90c5802 | 2010-03-03 01:55:09 +0000 | [diff] [blame] | 963 | .. note:: | 
|  | 964 |  | 
|  | 965 | Required options are generally considered bad form because users expect | 
|  | 966 | *options* to be *optional*, and thus they should be avoided when possible. | 
| Benjamin Peterson | a39e966 | 2010-03-02 22:05:59 +0000 | [diff] [blame] | 967 |  | 
|  | 968 |  | 
|  | 969 | help | 
|  | 970 | ^^^^ | 
|  | 971 |  | 
| Benjamin Peterson | 90c5802 | 2010-03-03 01:55:09 +0000 | [diff] [blame] | 972 | The ``help`` value is a string containing a brief description of the argument. | 
|  | 973 | When a user requests help (usually by using ``-h`` or ``--help`` at the | 
|  | 974 | command-line), these ``help`` descriptions will be displayed with each | 
| Georg Brandl | d2decd9 | 2010-03-02 22:17:38 +0000 | [diff] [blame] | 975 | argument:: | 
| Benjamin Peterson | a39e966 | 2010-03-02 22:05:59 +0000 | [diff] [blame] | 976 |  | 
|  | 977 | >>> parser = argparse.ArgumentParser(prog='frobble') | 
|  | 978 | >>> parser.add_argument('--foo', action='store_true', | 
|  | 979 | ...         help='foo the bars before frobbling') | 
|  | 980 | >>> parser.add_argument('bar', nargs='+', | 
|  | 981 | ...         help='one of the bars to be frobbled') | 
|  | 982 | >>> parser.parse_args('-h'.split()) | 
|  | 983 | usage: frobble [-h] [--foo] bar [bar ...] | 
|  | 984 |  | 
|  | 985 | positional arguments: | 
|  | 986 | bar     one of the bars to be frobbled | 
|  | 987 |  | 
|  | 988 | optional arguments: | 
|  | 989 | -h, --help  show this help message and exit | 
|  | 990 | --foo   foo the bars before frobbling | 
|  | 991 |  | 
|  | 992 | The ``help`` strings can include various format specifiers to avoid repetition | 
|  | 993 | of things like the program name or the argument default_.  The available | 
|  | 994 | specifiers include the program name, ``%(prog)s`` and most keyword arguments to | 
|  | 995 | :meth:`add_argument`, e.g. ``%(default)s``, ``%(type)s``, etc.:: | 
|  | 996 |  | 
|  | 997 | >>> parser = argparse.ArgumentParser(prog='frobble') | 
|  | 998 | >>> parser.add_argument('bar', nargs='?', type=int, default=42, | 
|  | 999 | ...         help='the bar to %(prog)s (default: %(default)s)') | 
|  | 1000 | >>> parser.print_help() | 
|  | 1001 | usage: frobble [-h] [bar] | 
|  | 1002 |  | 
|  | 1003 | positional arguments: | 
|  | 1004 | bar     the bar to frobble (default: 42) | 
|  | 1005 |  | 
|  | 1006 | optional arguments: | 
|  | 1007 | -h, --help  show this help message and exit | 
|  | 1008 |  | 
|  | 1009 |  | 
|  | 1010 | metavar | 
|  | 1011 | ^^^^^^^ | 
|  | 1012 |  | 
| Benjamin Peterson | 90c5802 | 2010-03-03 01:55:09 +0000 | [diff] [blame] | 1013 | When :class:`ArgumentParser` generates help messages, it need some way to refer | 
| Georg Brandl | d2decd9 | 2010-03-02 22:17:38 +0000 | [diff] [blame] | 1014 | to each expected argument.  By default, ArgumentParser objects use the dest_ | 
| Benjamin Peterson | a39e966 | 2010-03-02 22:05:59 +0000 | [diff] [blame] | 1015 | value as the "name" of each object.  By default, for positional argument | 
|  | 1016 | actions, the dest_ value is used directly, and for optional argument actions, | 
| Benjamin Peterson | 90c5802 | 2010-03-03 01:55:09 +0000 | [diff] [blame] | 1017 | the dest_ value is uppercased.  So, a single positional argument with | 
|  | 1018 | ``dest='bar'`` will that argument will be referred to as ``bar``. A single | 
|  | 1019 | optional argument ``--foo`` that should be followed by a single command-line arg | 
|  | 1020 | will be referred to as ``FOO``.  An example:: | 
| Benjamin Peterson | a39e966 | 2010-03-02 22:05:59 +0000 | [diff] [blame] | 1021 |  | 
|  | 1022 | >>> parser = argparse.ArgumentParser() | 
|  | 1023 | >>> parser.add_argument('--foo') | 
|  | 1024 | >>> parser.add_argument('bar') | 
|  | 1025 | >>> parser.parse_args('X --foo Y'.split()) | 
|  | 1026 | Namespace(bar='X', foo='Y') | 
|  | 1027 | >>> parser.print_help() | 
|  | 1028 | usage:  [-h] [--foo FOO] bar | 
|  | 1029 |  | 
|  | 1030 | positional arguments: | 
|  | 1031 | bar | 
|  | 1032 |  | 
|  | 1033 | optional arguments: | 
|  | 1034 | -h, --help  show this help message and exit | 
|  | 1035 | --foo FOO | 
|  | 1036 |  | 
| Benjamin Peterson | 90c5802 | 2010-03-03 01:55:09 +0000 | [diff] [blame] | 1037 | An alternative name can be specified with ``metavar``:: | 
| Benjamin Peterson | a39e966 | 2010-03-02 22:05:59 +0000 | [diff] [blame] | 1038 |  | 
|  | 1039 | >>> parser = argparse.ArgumentParser() | 
|  | 1040 | >>> parser.add_argument('--foo', metavar='YYY') | 
|  | 1041 | >>> parser.add_argument('bar', metavar='XXX') | 
|  | 1042 | >>> parser.parse_args('X --foo Y'.split()) | 
|  | 1043 | Namespace(bar='X', foo='Y') | 
|  | 1044 | >>> parser.print_help() | 
|  | 1045 | usage:  [-h] [--foo YYY] XXX | 
|  | 1046 |  | 
|  | 1047 | positional arguments: | 
|  | 1048 | XXX | 
|  | 1049 |  | 
|  | 1050 | optional arguments: | 
|  | 1051 | -h, --help  show this help message and exit | 
|  | 1052 | --foo YYY | 
|  | 1053 |  | 
|  | 1054 | Note that ``metavar`` only changes the *displayed* name - the name of the | 
|  | 1055 | attribute on the :meth:`parse_args` object is still determined by the dest_ | 
|  | 1056 | value. | 
|  | 1057 |  | 
|  | 1058 | Different values of ``nargs`` may cause the metavar to be used multiple times. | 
| Benjamin Peterson | 90c5802 | 2010-03-03 01:55:09 +0000 | [diff] [blame] | 1059 | Providing a tuple to ``metavar`` specifies a different display for each of the | 
|  | 1060 | arguments:: | 
| Benjamin Peterson | a39e966 | 2010-03-02 22:05:59 +0000 | [diff] [blame] | 1061 |  | 
|  | 1062 | >>> parser = argparse.ArgumentParser(prog='PROG') | 
|  | 1063 | >>> parser.add_argument('-x', nargs=2) | 
|  | 1064 | >>> parser.add_argument('--foo', nargs=2, metavar=('bar', 'baz')) | 
|  | 1065 | >>> parser.print_help() | 
|  | 1066 | usage: PROG [-h] [-x X X] [--foo bar baz] | 
|  | 1067 |  | 
|  | 1068 | optional arguments: | 
|  | 1069 | -h, --help     show this help message and exit | 
|  | 1070 | -x X X | 
|  | 1071 | --foo bar baz | 
|  | 1072 |  | 
|  | 1073 |  | 
|  | 1074 | dest | 
|  | 1075 | ^^^^ | 
|  | 1076 |  | 
| Benjamin Peterson | 90c5802 | 2010-03-03 01:55:09 +0000 | [diff] [blame] | 1077 | Most :class:`ArgumentParser` actions add some value as an attribute of the | 
|  | 1078 | object returned by :meth:`parse_args`.  The name of this attribute is determined | 
|  | 1079 | by the ``dest`` keyword argument of :meth:`add_argument`.  For positional | 
|  | 1080 | argument actions, ``dest`` is normally supplied as the first argument to | 
| Benjamin Peterson | a39e966 | 2010-03-02 22:05:59 +0000 | [diff] [blame] | 1081 | :meth:`add_argument`:: | 
|  | 1082 |  | 
|  | 1083 | >>> parser = argparse.ArgumentParser() | 
|  | 1084 | >>> parser.add_argument('bar') | 
|  | 1085 | >>> parser.parse_args('XXX'.split()) | 
|  | 1086 | Namespace(bar='XXX') | 
|  | 1087 |  | 
|  | 1088 | For optional argument actions, the value of ``dest`` is normally inferred from | 
| Benjamin Peterson | 90c5802 | 2010-03-03 01:55:09 +0000 | [diff] [blame] | 1089 | the option strings.  :class:`ArgumentParser` generates the value of ``dest`` by | 
| Benjamin Peterson | a39e966 | 2010-03-02 22:05:59 +0000 | [diff] [blame] | 1090 | taking the first long option string and stripping away the initial ``'--'`` | 
|  | 1091 | string.  If no long option strings were supplied, ``dest`` will be derived from | 
|  | 1092 | the first short option string by stripping the initial ``'-'`` character.  Any | 
| Georg Brandl | d2decd9 | 2010-03-02 22:17:38 +0000 | [diff] [blame] | 1093 | internal ``'-'`` characters will be converted to ``'_'`` characters to make sure | 
|  | 1094 | the string is a valid attribute name.  The examples below illustrate this | 
| Benjamin Peterson | a39e966 | 2010-03-02 22:05:59 +0000 | [diff] [blame] | 1095 | behavior:: | 
|  | 1096 |  | 
|  | 1097 | >>> parser = argparse.ArgumentParser() | 
|  | 1098 | >>> parser.add_argument('-f', '--foo-bar', '--foo') | 
|  | 1099 | >>> parser.add_argument('-x', '-y') | 
|  | 1100 | >>> parser.parse_args('-f 1 -x 2'.split()) | 
|  | 1101 | Namespace(foo_bar='1', x='2') | 
|  | 1102 | >>> parser.parse_args('--foo 1 -y 2'.split()) | 
|  | 1103 | Namespace(foo_bar='1', x='2') | 
|  | 1104 |  | 
| Benjamin Peterson | 90c5802 | 2010-03-03 01:55:09 +0000 | [diff] [blame] | 1105 | ``dest`` allows a custom attribute name to be provided:: | 
| Benjamin Peterson | a39e966 | 2010-03-02 22:05:59 +0000 | [diff] [blame] | 1106 |  | 
|  | 1107 | >>> parser = argparse.ArgumentParser() | 
|  | 1108 | >>> parser.add_argument('--foo', dest='bar') | 
|  | 1109 | >>> parser.parse_args('--foo XXX'.split()) | 
|  | 1110 | Namespace(bar='XXX') | 
|  | 1111 |  | 
|  | 1112 |  | 
|  | 1113 | The parse_args() method | 
|  | 1114 | ----------------------- | 
|  | 1115 |  | 
| Benjamin Peterson | 90c5802 | 2010-03-03 01:55:09 +0000 | [diff] [blame] | 1116 | .. method:: ArgumentParser.parse_args([args], [namespace]) | 
| Benjamin Peterson | a39e966 | 2010-03-02 22:05:59 +0000 | [diff] [blame] | 1117 |  | 
| Benjamin Peterson | 90c5802 | 2010-03-03 01:55:09 +0000 | [diff] [blame] | 1118 | Convert argument strings to objects and assign them as attributes of the | 
| Georg Brandl | d2decd9 | 2010-03-02 22:17:38 +0000 | [diff] [blame] | 1119 | namespace.  Return the populated namespace. | 
| Benjamin Peterson | a39e966 | 2010-03-02 22:05:59 +0000 | [diff] [blame] | 1120 |  | 
|  | 1121 | Previous calls to :meth:`add_argument` determine exactly what objects are | 
|  | 1122 | created and how they are assigned. See the documentation for | 
|  | 1123 | :meth:`add_argument` for details. | 
|  | 1124 |  | 
| Georg Brandl | d2decd9 | 2010-03-02 22:17:38 +0000 | [diff] [blame] | 1125 | By default, the arg strings are taken from :data:`sys.argv`, and a new empty | 
| Benjamin Peterson | 90c5802 | 2010-03-03 01:55:09 +0000 | [diff] [blame] | 1126 | :class:`Namespace` object is created for the attributes. | 
| Benjamin Peterson | a39e966 | 2010-03-02 22:05:59 +0000 | [diff] [blame] | 1127 |  | 
|  | 1128 | Option value syntax | 
|  | 1129 | ^^^^^^^^^^^^^^^^^^^ | 
|  | 1130 |  | 
|  | 1131 | The :meth:`parse_args` method supports several ways of specifying the value of | 
| Georg Brandl | d2decd9 | 2010-03-02 22:17:38 +0000 | [diff] [blame] | 1132 | an option (if it takes one).  In the simplest case, the option and its value are | 
| Benjamin Peterson | a39e966 | 2010-03-02 22:05:59 +0000 | [diff] [blame] | 1133 | passed as two separate arguments:: | 
|  | 1134 |  | 
|  | 1135 | >>> parser = argparse.ArgumentParser(prog='PROG') | 
|  | 1136 | >>> parser.add_argument('-x') | 
|  | 1137 | >>> parser.add_argument('--foo') | 
|  | 1138 | >>> parser.parse_args('-x X'.split()) | 
|  | 1139 | Namespace(foo=None, x='X') | 
|  | 1140 | >>> parser.parse_args('--foo FOO'.split()) | 
|  | 1141 | Namespace(foo='FOO', x=None) | 
|  | 1142 |  | 
| Benjamin Peterson | 90c5802 | 2010-03-03 01:55:09 +0000 | [diff] [blame] | 1143 | For long options (options with names longer than a single character), the option | 
|  | 1144 | and value can also be passed as a single command line argument, using ``=`` to | 
| Georg Brandl | d2decd9 | 2010-03-02 22:17:38 +0000 | [diff] [blame] | 1145 | separate them:: | 
| Benjamin Peterson | a39e966 | 2010-03-02 22:05:59 +0000 | [diff] [blame] | 1146 |  | 
|  | 1147 | >>> parser.parse_args('--foo=FOO'.split()) | 
|  | 1148 | Namespace(foo='FOO', x=None) | 
|  | 1149 |  | 
| Benjamin Peterson | 90c5802 | 2010-03-03 01:55:09 +0000 | [diff] [blame] | 1150 | For short options (options only one character long), the option and its value | 
|  | 1151 | can be concatenated:: | 
| Benjamin Peterson | a39e966 | 2010-03-02 22:05:59 +0000 | [diff] [blame] | 1152 |  | 
|  | 1153 | >>> parser.parse_args('-xX'.split()) | 
|  | 1154 | Namespace(foo=None, x='X') | 
|  | 1155 |  | 
| Benjamin Peterson | 90c5802 | 2010-03-03 01:55:09 +0000 | [diff] [blame] | 1156 | Several short options can be joined together, using only a single ``-`` prefix, | 
|  | 1157 | as long as only the last option (or none of them) requires a value:: | 
| Benjamin Peterson | a39e966 | 2010-03-02 22:05:59 +0000 | [diff] [blame] | 1158 |  | 
|  | 1159 | >>> parser = argparse.ArgumentParser(prog='PROG') | 
|  | 1160 | >>> parser.add_argument('-x', action='store_true') | 
|  | 1161 | >>> parser.add_argument('-y', action='store_true') | 
|  | 1162 | >>> parser.add_argument('-z') | 
|  | 1163 | >>> parser.parse_args('-xyzZ'.split()) | 
|  | 1164 | Namespace(x=True, y=True, z='Z') | 
|  | 1165 |  | 
|  | 1166 |  | 
|  | 1167 | Invalid arguments | 
|  | 1168 | ^^^^^^^^^^^^^^^^^ | 
|  | 1169 |  | 
|  | 1170 | While parsing the command-line, ``parse_args`` checks for a variety of errors, | 
|  | 1171 | including ambiguous options, invalid types, invalid options, wrong number of | 
| Georg Brandl | d2decd9 | 2010-03-02 22:17:38 +0000 | [diff] [blame] | 1172 | positional arguments, etc.  When it encounters such an error, it exits and | 
| Benjamin Peterson | a39e966 | 2010-03-02 22:05:59 +0000 | [diff] [blame] | 1173 | prints the error along with a usage message:: | 
|  | 1174 |  | 
|  | 1175 | >>> parser = argparse.ArgumentParser(prog='PROG') | 
|  | 1176 | >>> parser.add_argument('--foo', type=int) | 
|  | 1177 | >>> parser.add_argument('bar', nargs='?') | 
|  | 1178 |  | 
|  | 1179 | >>> # invalid type | 
|  | 1180 | >>> parser.parse_args(['--foo', 'spam']) | 
|  | 1181 | usage: PROG [-h] [--foo FOO] [bar] | 
|  | 1182 | PROG: error: argument --foo: invalid int value: 'spam' | 
|  | 1183 |  | 
|  | 1184 | >>> # invalid option | 
|  | 1185 | >>> parser.parse_args(['--bar']) | 
|  | 1186 | usage: PROG [-h] [--foo FOO] [bar] | 
|  | 1187 | PROG: error: no such option: --bar | 
|  | 1188 |  | 
|  | 1189 | >>> # wrong number of arguments | 
|  | 1190 | >>> parser.parse_args(['spam', 'badger']) | 
|  | 1191 | usage: PROG [-h] [--foo FOO] [bar] | 
|  | 1192 | PROG: error: extra arguments found: badger | 
|  | 1193 |  | 
|  | 1194 |  | 
|  | 1195 | Arguments containing ``"-"`` | 
|  | 1196 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | 
|  | 1197 |  | 
|  | 1198 | The ``parse_args`` method attempts to give errors whenever the user has clearly | 
| Georg Brandl | d2decd9 | 2010-03-02 22:17:38 +0000 | [diff] [blame] | 1199 | made a mistake, but some situations are inherently ambiguous.  For example, the | 
| Benjamin Peterson | a39e966 | 2010-03-02 22:05:59 +0000 | [diff] [blame] | 1200 | command-line arg ``'-1'`` could either be an attempt to specify an option or an | 
| Georg Brandl | d2decd9 | 2010-03-02 22:17:38 +0000 | [diff] [blame] | 1201 | attempt to provide a positional argument.  The ``parse_args`` method is cautious | 
| Benjamin Peterson | a39e966 | 2010-03-02 22:05:59 +0000 | [diff] [blame] | 1202 | here: positional arguments may only begin with ``'-'`` if they look like | 
|  | 1203 | negative numbers and there are no options in the parser that look like negative | 
|  | 1204 | numbers:: | 
|  | 1205 |  | 
|  | 1206 | >>> parser = argparse.ArgumentParser(prog='PROG') | 
|  | 1207 | >>> parser.add_argument('-x') | 
|  | 1208 | >>> parser.add_argument('foo', nargs='?') | 
|  | 1209 |  | 
|  | 1210 | >>> # no negative number options, so -1 is a positional argument | 
|  | 1211 | >>> parser.parse_args(['-x', '-1']) | 
|  | 1212 | Namespace(foo=None, x='-1') | 
|  | 1213 |  | 
|  | 1214 | >>> # no negative number options, so -1 and -5 are positional arguments | 
|  | 1215 | >>> parser.parse_args(['-x', '-1', '-5']) | 
|  | 1216 | Namespace(foo='-5', x='-1') | 
|  | 1217 |  | 
|  | 1218 | >>> parser = argparse.ArgumentParser(prog='PROG') | 
|  | 1219 | >>> parser.add_argument('-1', dest='one') | 
|  | 1220 | >>> parser.add_argument('foo', nargs='?') | 
|  | 1221 |  | 
|  | 1222 | >>> # negative number options present, so -1 is an option | 
|  | 1223 | >>> parser.parse_args(['-1', 'X']) | 
|  | 1224 | Namespace(foo=None, one='X') | 
|  | 1225 |  | 
|  | 1226 | >>> # negative number options present, so -2 is an option | 
|  | 1227 | >>> parser.parse_args(['-2']) | 
|  | 1228 | usage: PROG [-h] [-1 ONE] [foo] | 
|  | 1229 | PROG: error: no such option: -2 | 
|  | 1230 |  | 
|  | 1231 | >>> # negative number options present, so both -1s are options | 
|  | 1232 | >>> parser.parse_args(['-1', '-1']) | 
|  | 1233 | usage: PROG [-h] [-1 ONE] [foo] | 
|  | 1234 | PROG: error: argument -1: expected one argument | 
|  | 1235 |  | 
|  | 1236 | If you have positional arguments that must begin with ``'-'`` and don't look | 
|  | 1237 | like negative numbers, you can insert the pseudo-argument ``'--'`` which tells | 
|  | 1238 | ``parse_args`` that everything after that is a positional argument:: | 
|  | 1239 |  | 
|  | 1240 | >>> parser.parse_args(['--', '-f']) | 
|  | 1241 | Namespace(foo='-f', one=None) | 
|  | 1242 |  | 
|  | 1243 |  | 
|  | 1244 | Argument abbreviations | 
|  | 1245 | ^^^^^^^^^^^^^^^^^^^^^^ | 
|  | 1246 |  | 
| Benjamin Peterson | 90c5802 | 2010-03-03 01:55:09 +0000 | [diff] [blame] | 1247 | The :meth:`parse_args` method allows long options to be abbreviated if the | 
| Benjamin Peterson | a39e966 | 2010-03-02 22:05:59 +0000 | [diff] [blame] | 1248 | abbreviation is unambiguous:: | 
|  | 1249 |  | 
|  | 1250 | >>> parser = argparse.ArgumentParser(prog='PROG') | 
|  | 1251 | >>> parser.add_argument('-bacon') | 
|  | 1252 | >>> parser.add_argument('-badger') | 
|  | 1253 | >>> parser.parse_args('-bac MMM'.split()) | 
|  | 1254 | Namespace(bacon='MMM', badger=None) | 
|  | 1255 | >>> parser.parse_args('-bad WOOD'.split()) | 
|  | 1256 | Namespace(bacon=None, badger='WOOD') | 
|  | 1257 | >>> parser.parse_args('-ba BA'.split()) | 
|  | 1258 | usage: PROG [-h] [-bacon BACON] [-badger BADGER] | 
|  | 1259 | PROG: error: ambiguous option: -ba could match -badger, -bacon | 
|  | 1260 |  | 
| Benjamin Peterson | 90c5802 | 2010-03-03 01:55:09 +0000 | [diff] [blame] | 1261 | An error is produced for arguments that could produce more than one options. | 
| Benjamin Peterson | a39e966 | 2010-03-02 22:05:59 +0000 | [diff] [blame] | 1262 |  | 
|  | 1263 |  | 
|  | 1264 | Beyond ``sys.argv`` | 
|  | 1265 | ^^^^^^^^^^^^^^^^^^^ | 
|  | 1266 |  | 
| Georg Brandl | d2decd9 | 2010-03-02 22:17:38 +0000 | [diff] [blame] | 1267 | Sometimes it may be useful to have an ArgumentParser parse args other than those | 
|  | 1268 | of :data:`sys.argv`.  This can be accomplished by passing a list of strings to | 
| Benjamin Peterson | 90c5802 | 2010-03-03 01:55:09 +0000 | [diff] [blame] | 1269 | ``parse_args``.  This is useful for testing at the interactive prompt:: | 
| Benjamin Peterson | a39e966 | 2010-03-02 22:05:59 +0000 | [diff] [blame] | 1270 |  | 
|  | 1271 | >>> parser = argparse.ArgumentParser() | 
|  | 1272 | >>> parser.add_argument( | 
|  | 1273 | ...     'integers', metavar='int', type=int, choices=xrange(10), | 
|  | 1274 | ...  nargs='+', help='an integer in the range 0..9') | 
|  | 1275 | >>> parser.add_argument( | 
|  | 1276 | ...     '--sum', dest='accumulate', action='store_const', const=sum, | 
|  | 1277 | ...   default=max, help='sum the integers (default: find the max)') | 
|  | 1278 | >>> parser.parse_args(['1', '2', '3', '4']) | 
|  | 1279 | Namespace(accumulate=<built-in function max>, integers=[1, 2, 3, 4]) | 
|  | 1280 | >>> parser.parse_args('1 2 3 4 --sum'.split()) | 
|  | 1281 | Namespace(accumulate=<built-in function sum>, integers=[1, 2, 3, 4]) | 
|  | 1282 |  | 
|  | 1283 |  | 
|  | 1284 | Custom namespaces | 
|  | 1285 | ^^^^^^^^^^^^^^^^^ | 
|  | 1286 |  | 
| Benjamin Peterson | 90c5802 | 2010-03-03 01:55:09 +0000 | [diff] [blame] | 1287 | It may also be useful to have an :class:`ArgumentParser` assign attributes to an | 
|  | 1288 | already existing object, rather than the newly-created :class:`Namespace` object | 
|  | 1289 | that is normally used.  This can be achieved by specifying the ``namespace=`` | 
|  | 1290 | keyword argument:: | 
| Benjamin Peterson | a39e966 | 2010-03-02 22:05:59 +0000 | [diff] [blame] | 1291 |  | 
|  | 1292 | >>> class C(object): | 
|  | 1293 | ...     pass | 
|  | 1294 | ... | 
|  | 1295 | >>> c = C() | 
|  | 1296 | >>> parser = argparse.ArgumentParser() | 
|  | 1297 | >>> parser.add_argument('--foo') | 
|  | 1298 | >>> parser.parse_args(args=['--foo', 'BAR'], namespace=c) | 
|  | 1299 | >>> c.foo | 
|  | 1300 | 'BAR' | 
|  | 1301 |  | 
|  | 1302 |  | 
|  | 1303 | Other utilities | 
|  | 1304 | --------------- | 
|  | 1305 |  | 
|  | 1306 | Sub-commands | 
|  | 1307 | ^^^^^^^^^^^^ | 
|  | 1308 |  | 
| Benjamin Peterson | 90c5802 | 2010-03-03 01:55:09 +0000 | [diff] [blame] | 1309 | .. method:: ArgumentParser.add_subparsers() | 
| Benjamin Peterson | a39e966 | 2010-03-02 22:05:59 +0000 | [diff] [blame] | 1310 |  | 
| Benjamin Peterson | 90c5802 | 2010-03-03 01:55:09 +0000 | [diff] [blame] | 1311 | Many programs split up their functionality into a number of sub-commands, | 
| Georg Brandl | d2decd9 | 2010-03-02 22:17:38 +0000 | [diff] [blame] | 1312 | for example, the ``svn`` program can invoke sub-commands like ``svn | 
| Benjamin Peterson | 90c5802 | 2010-03-03 01:55:09 +0000 | [diff] [blame] | 1313 | checkout``, ``svn update``, and ``svn commit``.  Splitting up functionality | 
| Georg Brandl | d2decd9 | 2010-03-02 22:17:38 +0000 | [diff] [blame] | 1314 | this way can be a particularly good idea when a program performs several | 
|  | 1315 | different functions which require different kinds of command-line arguments. | 
| Benjamin Peterson | 90c5802 | 2010-03-03 01:55:09 +0000 | [diff] [blame] | 1316 | :class:`ArgumentParser` supports the creation of such sub-commands with the | 
| Georg Brandl | d2decd9 | 2010-03-02 22:17:38 +0000 | [diff] [blame] | 1317 | :meth:`add_subparsers` method.  The :meth:`add_subparsers` method is normally | 
|  | 1318 | called with no arguments and returns an special action object.  This object | 
|  | 1319 | has a single method, ``add_parser``, which takes a command name and any | 
| Benjamin Peterson | 90c5802 | 2010-03-03 01:55:09 +0000 | [diff] [blame] | 1320 | :class:`ArgumentParser` constructor arguments, and returns an | 
|  | 1321 | :class:`ArgumentParser` object that can be modified as usual. | 
| Benjamin Peterson | a39e966 | 2010-03-02 22:05:59 +0000 | [diff] [blame] | 1322 |  | 
|  | 1323 | Some example usage:: | 
|  | 1324 |  | 
|  | 1325 | >>> # create the top-level parser | 
|  | 1326 | >>> parser = argparse.ArgumentParser(prog='PROG') | 
|  | 1327 | >>> parser.add_argument('--foo', action='store_true', help='foo help') | 
|  | 1328 | >>> subparsers = parser.add_subparsers(help='sub-command help') | 
|  | 1329 | >>> | 
|  | 1330 | >>> # create the parser for the "a" command | 
|  | 1331 | >>> parser_a = subparsers.add_parser('a', help='a help') | 
|  | 1332 | >>> parser_a.add_argument('bar', type=int, help='bar help') | 
|  | 1333 | >>> | 
|  | 1334 | >>> # create the parser for the "b" command | 
|  | 1335 | >>> parser_b = subparsers.add_parser('b', help='b help') | 
|  | 1336 | >>> parser_b.add_argument('--baz', choices='XYZ', help='baz help') | 
|  | 1337 | >>> | 
|  | 1338 | >>> # parse some arg lists | 
|  | 1339 | >>> parser.parse_args(['a', '12']) | 
|  | 1340 | Namespace(bar=12, foo=False) | 
|  | 1341 | >>> parser.parse_args(['--foo', 'b', '--baz', 'Z']) | 
|  | 1342 | Namespace(baz='Z', foo=True) | 
|  | 1343 |  | 
|  | 1344 | Note that the object returned by :meth:`parse_args` will only contain | 
|  | 1345 | attributes for the main parser and the subparser that was selected by the | 
|  | 1346 | command line (and not any other subparsers).  So in the example above, when | 
| Georg Brandl | d2decd9 | 2010-03-02 22:17:38 +0000 | [diff] [blame] | 1347 | the ``"a"`` command is specified, only the ``foo`` and ``bar`` attributes are | 
|  | 1348 | present, and when the ``"b"`` command is specified, only the ``foo`` and | 
| Benjamin Peterson | a39e966 | 2010-03-02 22:05:59 +0000 | [diff] [blame] | 1349 | ``baz`` attributes are present. | 
|  | 1350 |  | 
|  | 1351 | Similarly, when a help message is requested from a subparser, only the help | 
| Georg Brandl | d2decd9 | 2010-03-02 22:17:38 +0000 | [diff] [blame] | 1352 | for that particular parser will be printed.  The help message will not | 
| Benjamin Peterson | 90c5802 | 2010-03-03 01:55:09 +0000 | [diff] [blame] | 1353 | include parent parser or sibling parser messages.  (A help message for each | 
|  | 1354 | subparser command, however, can be given by supplying the ``help=`` argument | 
|  | 1355 | to ``add_parser`` as above.) | 
| Benjamin Peterson | a39e966 | 2010-03-02 22:05:59 +0000 | [diff] [blame] | 1356 |  | 
|  | 1357 | :: | 
|  | 1358 |  | 
|  | 1359 | >>> parser.parse_args(['--help']) | 
|  | 1360 | usage: PROG [-h] [--foo] {a,b} ... | 
|  | 1361 |  | 
|  | 1362 | positional arguments: | 
|  | 1363 | {a,b}   sub-command help | 
|  | 1364 | a     a help | 
|  | 1365 | b     b help | 
|  | 1366 |  | 
|  | 1367 | optional arguments: | 
|  | 1368 | -h, --help  show this help message and exit | 
|  | 1369 | --foo   foo help | 
|  | 1370 |  | 
|  | 1371 | >>> parser.parse_args(['a', '--help']) | 
|  | 1372 | usage: PROG a [-h] bar | 
|  | 1373 |  | 
|  | 1374 | positional arguments: | 
|  | 1375 | bar     bar help | 
|  | 1376 |  | 
|  | 1377 | optional arguments: | 
|  | 1378 | -h, --help  show this help message and exit | 
|  | 1379 |  | 
|  | 1380 | >>> parser.parse_args(['b', '--help']) | 
|  | 1381 | usage: PROG b [-h] [--baz {X,Y,Z}] | 
|  | 1382 |  | 
|  | 1383 | optional arguments: | 
|  | 1384 | -h, --help     show this help message and exit | 
|  | 1385 | --baz {X,Y,Z}  baz help | 
|  | 1386 |  | 
| Georg Brandl | d2decd9 | 2010-03-02 22:17:38 +0000 | [diff] [blame] | 1387 | The :meth:`add_subparsers` method also supports ``title`` and ``description`` | 
|  | 1388 | keyword arguments.  When either is present, the subparser's commands will | 
|  | 1389 | appear in their own group in the help output.  For example:: | 
| Benjamin Peterson | a39e966 | 2010-03-02 22:05:59 +0000 | [diff] [blame] | 1390 |  | 
|  | 1391 | >>> parser = argparse.ArgumentParser() | 
|  | 1392 | >>> subparsers = parser.add_subparsers(title='subcommands', | 
|  | 1393 | ...                                    description='valid subcommands', | 
|  | 1394 | ...                                    help='additional help') | 
|  | 1395 | >>> subparsers.add_parser('foo') | 
|  | 1396 | >>> subparsers.add_parser('bar') | 
|  | 1397 | >>> parser.parse_args(['-h']) | 
|  | 1398 | usage:  [-h] {foo,bar} ... | 
|  | 1399 |  | 
|  | 1400 | optional arguments: | 
|  | 1401 | -h, --help  show this help message and exit | 
|  | 1402 |  | 
|  | 1403 | subcommands: | 
|  | 1404 | valid subcommands | 
|  | 1405 |  | 
|  | 1406 | {foo,bar}   additional help | 
|  | 1407 |  | 
|  | 1408 |  | 
| Georg Brandl | d2decd9 | 2010-03-02 22:17:38 +0000 | [diff] [blame] | 1409 | One particularly effective way of handling sub-commands is to combine the use | 
|  | 1410 | of the :meth:`add_subparsers` method with calls to :meth:`set_defaults` so | 
|  | 1411 | that each subparser knows which Python function it should execute.  For | 
| Benjamin Peterson | a39e966 | 2010-03-02 22:05:59 +0000 | [diff] [blame] | 1412 | example:: | 
|  | 1413 |  | 
|  | 1414 | >>> # sub-command functions | 
|  | 1415 | >>> def foo(args): | 
|  | 1416 | ...     print args.x * args.y | 
|  | 1417 | ... | 
|  | 1418 | >>> def bar(args): | 
|  | 1419 | ...     print '((%s))' % args.z | 
|  | 1420 | ... | 
|  | 1421 | >>> # create the top-level parser | 
|  | 1422 | >>> parser = argparse.ArgumentParser() | 
|  | 1423 | >>> subparsers = parser.add_subparsers() | 
|  | 1424 | >>> | 
|  | 1425 | >>> # create the parser for the "foo" command | 
|  | 1426 | >>> parser_foo = subparsers.add_parser('foo') | 
|  | 1427 | >>> parser_foo.add_argument('-x', type=int, default=1) | 
|  | 1428 | >>> parser_foo.add_argument('y', type=float) | 
|  | 1429 | >>> parser_foo.set_defaults(func=foo) | 
|  | 1430 | >>> | 
|  | 1431 | >>> # create the parser for the "bar" command | 
|  | 1432 | >>> parser_bar = subparsers.add_parser('bar') | 
|  | 1433 | >>> parser_bar.add_argument('z') | 
|  | 1434 | >>> parser_bar.set_defaults(func=bar) | 
|  | 1435 | >>> | 
|  | 1436 | >>> # parse the args and call whatever function was selected | 
|  | 1437 | >>> args = parser.parse_args('foo 1 -x 2'.split()) | 
|  | 1438 | >>> args.func(args) | 
|  | 1439 | 2.0 | 
|  | 1440 | >>> | 
|  | 1441 | >>> # parse the args and call whatever function was selected | 
|  | 1442 | >>> args = parser.parse_args('bar XYZYX'.split()) | 
|  | 1443 | >>> args.func(args) | 
|  | 1444 | ((XYZYX)) | 
|  | 1445 |  | 
| Benjamin Peterson | 90c5802 | 2010-03-03 01:55:09 +0000 | [diff] [blame] | 1446 | This way, you can let :meth:`parse_args` does the job of calling the | 
|  | 1447 | appropriate function after argument parsing is complete.  Associating | 
|  | 1448 | functions with actions like this is typically the easiest way to handle the | 
|  | 1449 | different actions for each of your subparsers.  However, if it is necessary | 
|  | 1450 | to check the name of the subparser that was invoked, the ``dest`` keyword | 
|  | 1451 | argument to the :meth:`add_subparsers` call will work:: | 
| Benjamin Peterson | a39e966 | 2010-03-02 22:05:59 +0000 | [diff] [blame] | 1452 |  | 
|  | 1453 | >>> parser = argparse.ArgumentParser() | 
|  | 1454 | >>> subparsers = parser.add_subparsers(dest='subparser_name') | 
|  | 1455 | >>> subparser1 = subparsers.add_parser('1') | 
|  | 1456 | >>> subparser1.add_argument('-x') | 
|  | 1457 | >>> subparser2 = subparsers.add_parser('2') | 
|  | 1458 | >>> subparser2.add_argument('y') | 
|  | 1459 | >>> parser.parse_args(['2', 'frobble']) | 
|  | 1460 | Namespace(subparser_name='2', y='frobble') | 
|  | 1461 |  | 
|  | 1462 |  | 
|  | 1463 | FileType objects | 
|  | 1464 | ^^^^^^^^^^^^^^^^ | 
|  | 1465 |  | 
|  | 1466 | .. class:: FileType(mode='r', bufsize=None) | 
|  | 1467 |  | 
|  | 1468 | The :class:`FileType` factory creates objects that can be passed to the type | 
| Benjamin Peterson | 90c5802 | 2010-03-03 01:55:09 +0000 | [diff] [blame] | 1469 | argument of :meth:`ArgumentParser.add_argument`.  Arguments that have | 
|  | 1470 | :class:`FileType` objects as their type will open command-line args as files | 
|  | 1471 | with the requested modes and buffer sizes: | 
| Benjamin Peterson | a39e966 | 2010-03-02 22:05:59 +0000 | [diff] [blame] | 1472 |  | 
|  | 1473 | >>> parser = argparse.ArgumentParser() | 
|  | 1474 | >>> parser.add_argument('--output', type=argparse.FileType('wb', 0)) | 
|  | 1475 | >>> parser.parse_args(['--output', 'out']) | 
|  | 1476 | Namespace(output=<open file 'out', mode 'wb' at 0x...>) | 
|  | 1477 |  | 
|  | 1478 | FileType objects understand the pseudo-argument ``'-'`` and automatically | 
|  | 1479 | convert this into ``sys.stdin`` for readable :class:`FileType` objects and | 
|  | 1480 | ``sys.stdout`` for writable :class:`FileType` objects: | 
|  | 1481 |  | 
|  | 1482 | >>> parser = argparse.ArgumentParser() | 
|  | 1483 | >>> parser.add_argument('infile', type=argparse.FileType('r')) | 
|  | 1484 | >>> parser.parse_args(['-']) | 
|  | 1485 | Namespace(infile=<open file '<stdin>', mode 'r' at 0x...>) | 
|  | 1486 |  | 
|  | 1487 |  | 
|  | 1488 | Argument groups | 
|  | 1489 | ^^^^^^^^^^^^^^^ | 
|  | 1490 |  | 
| Benjamin Peterson | 90c5802 | 2010-03-03 01:55:09 +0000 | [diff] [blame] | 1491 | .. method:: ArgumentParser.add_argument_group([title], [description]) | 
| Benjamin Peterson | a39e966 | 2010-03-02 22:05:59 +0000 | [diff] [blame] | 1492 |  | 
| Benjamin Peterson | 90c5802 | 2010-03-03 01:55:09 +0000 | [diff] [blame] | 1493 | By default, :class:`ArgumentParser` groups command-line arguments into | 
| Benjamin Peterson | a39e966 | 2010-03-02 22:05:59 +0000 | [diff] [blame] | 1494 | "positional arguments" and "optional arguments" when displaying help | 
|  | 1495 | messages. When there is a better conceptual grouping of arguments than this | 
|  | 1496 | default one, appropriate groups can be created using the | 
|  | 1497 | :meth:`add_argument_group` method:: | 
|  | 1498 |  | 
|  | 1499 | >>> parser = argparse.ArgumentParser(prog='PROG', add_help=False) | 
|  | 1500 | >>> group = parser.add_argument_group('group') | 
|  | 1501 | >>> group.add_argument('--foo', help='foo help') | 
|  | 1502 | >>> group.add_argument('bar', help='bar help') | 
|  | 1503 | >>> parser.print_help() | 
|  | 1504 | usage: PROG [--foo FOO] bar | 
|  | 1505 |  | 
|  | 1506 | group: | 
|  | 1507 | bar    bar help | 
|  | 1508 | --foo FOO  foo help | 
|  | 1509 |  | 
|  | 1510 | The :meth:`add_argument_group` method returns an argument group object which | 
| Benjamin Peterson | 90c5802 | 2010-03-03 01:55:09 +0000 | [diff] [blame] | 1511 | has an :meth:`~ArgumentParser.add_argument` method just like a regular | 
|  | 1512 | :class:`ArgumentParser`.  When an argument is added to the group, the parser | 
|  | 1513 | treats it just like a normal argument, but displays the argument in a | 
|  | 1514 | separate group for help messages.  The :meth:`add_argument_group` method | 
|  | 1515 | accepts ``title`` and ``description`` arguments which can be used to | 
|  | 1516 | customize this display:: | 
| Benjamin Peterson | a39e966 | 2010-03-02 22:05:59 +0000 | [diff] [blame] | 1517 |  | 
|  | 1518 | >>> parser = argparse.ArgumentParser(prog='PROG', add_help=False) | 
|  | 1519 | >>> group1 = parser.add_argument_group('group1', 'group1 description') | 
|  | 1520 | >>> group1.add_argument('foo', help='foo help') | 
|  | 1521 | >>> group2 = parser.add_argument_group('group2', 'group2 description') | 
|  | 1522 | >>> group2.add_argument('--bar', help='bar help') | 
|  | 1523 | >>> parser.print_help() | 
|  | 1524 | usage: PROG [--bar BAR] foo | 
|  | 1525 |  | 
|  | 1526 | group1: | 
|  | 1527 | group1 description | 
|  | 1528 |  | 
|  | 1529 | foo    foo help | 
|  | 1530 |  | 
|  | 1531 | group2: | 
|  | 1532 | group2 description | 
|  | 1533 |  | 
|  | 1534 | --bar BAR  bar help | 
|  | 1535 |  | 
| Benjamin Peterson | 90c5802 | 2010-03-03 01:55:09 +0000 | [diff] [blame] | 1536 | Note that any arguments not your user defined groups will end up back in the | 
|  | 1537 | usual "positional arguments" and "optional arguments" sections. | 
| Benjamin Peterson | a39e966 | 2010-03-02 22:05:59 +0000 | [diff] [blame] | 1538 |  | 
|  | 1539 |  | 
|  | 1540 | Mutual exclusion | 
|  | 1541 | ^^^^^^^^^^^^^^^^ | 
|  | 1542 |  | 
|  | 1543 | .. method:: add_mutually_exclusive_group([required=False]) | 
|  | 1544 |  | 
| Benjamin Peterson | 90c5802 | 2010-03-03 01:55:09 +0000 | [diff] [blame] | 1545 | Create a mutually exclusive group. argparse will make sure that only one of | 
| Benjamin Peterson | a39e966 | 2010-03-02 22:05:59 +0000 | [diff] [blame] | 1546 | the arguments in the mutually exclusive group was present on the command | 
|  | 1547 | line:: | 
|  | 1548 |  | 
|  | 1549 | >>> parser = argparse.ArgumentParser(prog='PROG') | 
|  | 1550 | >>> group = parser.add_mutually_exclusive_group() | 
|  | 1551 | >>> group.add_argument('--foo', action='store_true') | 
|  | 1552 | >>> group.add_argument('--bar', action='store_false') | 
|  | 1553 | >>> parser.parse_args(['--foo']) | 
|  | 1554 | Namespace(bar=True, foo=True) | 
|  | 1555 | >>> parser.parse_args(['--bar']) | 
|  | 1556 | Namespace(bar=False, foo=False) | 
|  | 1557 | >>> parser.parse_args(['--foo', '--bar']) | 
|  | 1558 | usage: PROG [-h] [--foo | --bar] | 
|  | 1559 | PROG: error: argument --bar: not allowed with argument --foo | 
|  | 1560 |  | 
|  | 1561 | The :meth:`add_mutually_exclusive_group` method also accepts a ``required`` | 
|  | 1562 | argument, to indicate that at least one of the mutually exclusive arguments | 
|  | 1563 | is required:: | 
|  | 1564 |  | 
|  | 1565 | >>> parser = argparse.ArgumentParser(prog='PROG') | 
|  | 1566 | >>> group = parser.add_mutually_exclusive_group(required=True) | 
|  | 1567 | >>> group.add_argument('--foo', action='store_true') | 
|  | 1568 | >>> group.add_argument('--bar', action='store_false') | 
|  | 1569 | >>> parser.parse_args([]) | 
|  | 1570 | usage: PROG [-h] (--foo | --bar) | 
|  | 1571 | PROG: error: one of the arguments --foo --bar is required | 
|  | 1572 |  | 
|  | 1573 | Note that currently mutually exclusive argument groups do not support the | 
| Benjamin Peterson | 90c5802 | 2010-03-03 01:55:09 +0000 | [diff] [blame] | 1574 | ``title`` and ``description`` arguments of :meth:`add_argument_group`. | 
| Benjamin Peterson | a39e966 | 2010-03-02 22:05:59 +0000 | [diff] [blame] | 1575 |  | 
|  | 1576 |  | 
|  | 1577 | Parser defaults | 
|  | 1578 | ^^^^^^^^^^^^^^^ | 
|  | 1579 |  | 
| Benjamin Peterson | 90c5802 | 2010-03-03 01:55:09 +0000 | [diff] [blame] | 1580 | .. method:: ArgumentParser.set_defaults(**kwargs) | 
| Benjamin Peterson | a39e966 | 2010-03-02 22:05:59 +0000 | [diff] [blame] | 1581 |  | 
| Georg Brandl | d2decd9 | 2010-03-02 22:17:38 +0000 | [diff] [blame] | 1582 | Most of the time, the attributes of the object returned by :meth:`parse_args` | 
|  | 1583 | will be fully determined by inspecting the command-line args and the argument | 
| Benjamin Peterson | c516d19 | 2010-03-03 02:04:24 +0000 | [diff] [blame] | 1584 | actions.  :meth:`ArgumentParser.set_defaults` allows some additional | 
|  | 1585 | attributes that are determined without any inspection of the command-line to | 
|  | 1586 | be added:: | 
| Benjamin Peterson | a39e966 | 2010-03-02 22:05:59 +0000 | [diff] [blame] | 1587 |  | 
|  | 1588 | >>> parser = argparse.ArgumentParser() | 
|  | 1589 | >>> parser.add_argument('foo', type=int) | 
|  | 1590 | >>> parser.set_defaults(bar=42, baz='badger') | 
|  | 1591 | >>> parser.parse_args(['736']) | 
|  | 1592 | Namespace(bar=42, baz='badger', foo=736) | 
|  | 1593 |  | 
| Benjamin Peterson | 90c5802 | 2010-03-03 01:55:09 +0000 | [diff] [blame] | 1594 | Note that parser-level defaults always override argument-level defaults:: | 
| Benjamin Peterson | a39e966 | 2010-03-02 22:05:59 +0000 | [diff] [blame] | 1595 |  | 
|  | 1596 | >>> parser = argparse.ArgumentParser() | 
|  | 1597 | >>> parser.add_argument('--foo', default='bar') | 
|  | 1598 | >>> parser.set_defaults(foo='spam') | 
|  | 1599 | >>> parser.parse_args([]) | 
|  | 1600 | Namespace(foo='spam') | 
|  | 1601 |  | 
| Benjamin Peterson | 90c5802 | 2010-03-03 01:55:09 +0000 | [diff] [blame] | 1602 | Parser-level defaults can be particularly useful when working with multiple | 
|  | 1603 | parsers.  See the :meth:`~ArgumentParser.add_subparsers` method for an | 
|  | 1604 | example of this type. | 
| Benjamin Peterson | a39e966 | 2010-03-02 22:05:59 +0000 | [diff] [blame] | 1605 |  | 
| Benjamin Peterson | 90c5802 | 2010-03-03 01:55:09 +0000 | [diff] [blame] | 1606 | .. method:: ArgumentParser.get_default(dest) | 
| Benjamin Peterson | a39e966 | 2010-03-02 22:05:59 +0000 | [diff] [blame] | 1607 |  | 
|  | 1608 | Get the default value for a namespace attribute, as set by either | 
| Benjamin Peterson | 90c5802 | 2010-03-03 01:55:09 +0000 | [diff] [blame] | 1609 | :meth:`~ArgumentParser.add_argument` or by | 
|  | 1610 | :meth:`~ArgumentParser.set_defaults`:: | 
| Benjamin Peterson | a39e966 | 2010-03-02 22:05:59 +0000 | [diff] [blame] | 1611 |  | 
|  | 1612 | >>> parser = argparse.ArgumentParser() | 
|  | 1613 | >>> parser.add_argument('--foo', default='badger') | 
|  | 1614 | >>> parser.get_default('foo') | 
|  | 1615 | 'badger' | 
|  | 1616 |  | 
|  | 1617 |  | 
|  | 1618 | Printing help | 
|  | 1619 | ^^^^^^^^^^^^^ | 
|  | 1620 |  | 
|  | 1621 | In most typical applications, :meth:`parse_args` will take care of formatting | 
| Benjamin Peterson | 90c5802 | 2010-03-03 01:55:09 +0000 | [diff] [blame] | 1622 | and printing any usage or error messages.  However, several formatting methods | 
|  | 1623 | are available: | 
| Benjamin Peterson | a39e966 | 2010-03-02 22:05:59 +0000 | [diff] [blame] | 1624 |  | 
| Benjamin Peterson | 90c5802 | 2010-03-03 01:55:09 +0000 | [diff] [blame] | 1625 | .. method:: ArgumentParser.print_usage([file]): | 
| Benjamin Peterson | a39e966 | 2010-03-02 22:05:59 +0000 | [diff] [blame] | 1626 |  | 
|  | 1627 | Print a brief description of how the :class:`ArgumentParser` should be | 
|  | 1628 | invoked on the command line.  If ``file`` is not present, ``sys.stderr`` is | 
|  | 1629 | assumed. | 
|  | 1630 |  | 
| Benjamin Peterson | 90c5802 | 2010-03-03 01:55:09 +0000 | [diff] [blame] | 1631 | .. method:: ArgumentParser.print_help([file]): | 
| Benjamin Peterson | a39e966 | 2010-03-02 22:05:59 +0000 | [diff] [blame] | 1632 |  | 
|  | 1633 | Print a help message, including the program usage and information about the | 
| Georg Brandl | d2decd9 | 2010-03-02 22:17:38 +0000 | [diff] [blame] | 1634 | arguments registered with the :class:`ArgumentParser`.  If ``file`` is not | 
| Benjamin Peterson | a39e966 | 2010-03-02 22:05:59 +0000 | [diff] [blame] | 1635 | present, ``sys.stderr`` is assumed. | 
|  | 1636 |  | 
|  | 1637 | There are also variants of these methods that simply return a string instead of | 
|  | 1638 | printing it: | 
|  | 1639 |  | 
| Benjamin Peterson | 90c5802 | 2010-03-03 01:55:09 +0000 | [diff] [blame] | 1640 | .. method:: ArgumentParser.format_usage(): | 
| Benjamin Peterson | a39e966 | 2010-03-02 22:05:59 +0000 | [diff] [blame] | 1641 |  | 
|  | 1642 | Return a string containing a brief description of how the | 
|  | 1643 | :class:`ArgumentParser` should be invoked on the command line. | 
|  | 1644 |  | 
| Benjamin Peterson | 90c5802 | 2010-03-03 01:55:09 +0000 | [diff] [blame] | 1645 | .. method:: ArgumentParser.format_help(): | 
| Benjamin Peterson | a39e966 | 2010-03-02 22:05:59 +0000 | [diff] [blame] | 1646 |  | 
|  | 1647 | Return a string containing a help message, including the program usage and | 
|  | 1648 | information about the arguments registered with the :class:`ArgumentParser`. | 
|  | 1649 |  | 
|  | 1650 |  | 
|  | 1651 |  | 
|  | 1652 | Partial parsing | 
|  | 1653 | ^^^^^^^^^^^^^^^ | 
|  | 1654 |  | 
| Benjamin Peterson | 90c5802 | 2010-03-03 01:55:09 +0000 | [diff] [blame] | 1655 | .. method:: ArgumentParser.parse_known_args([args], [namespace]) | 
| Benjamin Peterson | a39e966 | 2010-03-02 22:05:59 +0000 | [diff] [blame] | 1656 |  | 
|  | 1657 | Sometimes a script may only parse a few of the command line arguments, passing | 
|  | 1658 | the remaining arguments on to another script or program. In these cases, the | 
| Georg Brandl | d2decd9 | 2010-03-02 22:17:38 +0000 | [diff] [blame] | 1659 | :meth:`parse_known_args` method can be useful.  It works much like | 
| Benjamin Peterson | 90c5802 | 2010-03-03 01:55:09 +0000 | [diff] [blame] | 1660 | :meth:`~ArgumentParser.parse_args` except that it does not produce an error when | 
|  | 1661 | extra arguments are present.  Instead, it returns a two item tuple containing | 
|  | 1662 | the populated namespace and the list of remaining argument strings. | 
| Benjamin Peterson | a39e966 | 2010-03-02 22:05:59 +0000 | [diff] [blame] | 1663 |  | 
|  | 1664 | :: | 
|  | 1665 |  | 
|  | 1666 | >>> parser = argparse.ArgumentParser() | 
|  | 1667 | >>> parser.add_argument('--foo', action='store_true') | 
|  | 1668 | >>> parser.add_argument('bar') | 
|  | 1669 | >>> parser.parse_known_args(['--foo', '--badger', 'BAR', 'spam']) | 
|  | 1670 | (Namespace(bar='BAR', foo=True), ['--badger', 'spam']) | 
|  | 1671 |  | 
|  | 1672 |  | 
|  | 1673 | Customizing file parsing | 
|  | 1674 | ^^^^^^^^^^^^^^^^^^^^^^^^ | 
|  | 1675 |  | 
| Benjamin Peterson | 90c5802 | 2010-03-03 01:55:09 +0000 | [diff] [blame] | 1676 | .. method:: ArgumentParser.convert_arg_line_to_args(arg_line) | 
| Benjamin Peterson | a39e966 | 2010-03-02 22:05:59 +0000 | [diff] [blame] | 1677 |  | 
|  | 1678 | Arguments that are read from a file (see the ``fromfile_prefix_chars`` | 
|  | 1679 | keyword argument to the :class:`ArgumentParser` constructor) are read one | 
| Benjamin Peterson | 90c5802 | 2010-03-03 01:55:09 +0000 | [diff] [blame] | 1680 | argument per line. :meth:`convert_arg_line_to_args` can be overriden for | 
|  | 1681 | fancier reading. | 
| Benjamin Peterson | a39e966 | 2010-03-02 22:05:59 +0000 | [diff] [blame] | 1682 |  | 
|  | 1683 | This method takes a single argument ``arg_line`` which is a string read from | 
|  | 1684 | the argument file.  It returns a list of arguments parsed from this string. | 
|  | 1685 | The method is called once per line read from the argument file, in order. | 
|  | 1686 |  | 
| Georg Brandl | d2decd9 | 2010-03-02 22:17:38 +0000 | [diff] [blame] | 1687 | A useful override of this method is one that treats each space-separated word | 
|  | 1688 | as an argument:: | 
| Benjamin Peterson | a39e966 | 2010-03-02 22:05:59 +0000 | [diff] [blame] | 1689 |  | 
|  | 1690 | def convert_arg_line_to_args(self, arg_line): | 
|  | 1691 | for arg in arg_line.split(): | 
|  | 1692 | if not arg.strip(): | 
|  | 1693 | continue | 
|  | 1694 | yield arg | 
|  | 1695 |  | 
|  | 1696 |  | 
|  | 1697 | Upgrading optparse code | 
|  | 1698 | ----------------------- | 
|  | 1699 |  | 
|  | 1700 | Originally, the argparse module had attempted to maintain compatibility with | 
| Georg Brandl | d2decd9 | 2010-03-02 22:17:38 +0000 | [diff] [blame] | 1701 | optparse.  However, optparse was difficult to extend transparently, particularly | 
|  | 1702 | with the changes required to support the new ``nargs=`` specifiers and better | 
| Georg Brandl | 404bd7f | 2010-04-25 10:16:00 +0000 | [diff] [blame] | 1703 | usage messages.  When most everything in optparse had either been copy-pasted | 
| Georg Brandl | d2decd9 | 2010-03-02 22:17:38 +0000 | [diff] [blame] | 1704 | over or monkey-patched, it no longer seemed practical to try to maintain the | 
|  | 1705 | backwards compatibility. | 
| Benjamin Peterson | a39e966 | 2010-03-02 22:05:59 +0000 | [diff] [blame] | 1706 |  | 
|  | 1707 | A partial upgrade path from optparse to argparse: | 
|  | 1708 |  | 
| Benjamin Peterson | 90c5802 | 2010-03-03 01:55:09 +0000 | [diff] [blame] | 1709 | * Replace all ``add_option()`` calls with :meth:`ArgumentParser.add_argument` calls. | 
| Benjamin Peterson | a39e966 | 2010-03-02 22:05:59 +0000 | [diff] [blame] | 1710 |  | 
| Georg Brandl | d2decd9 | 2010-03-02 22:17:38 +0000 | [diff] [blame] | 1711 | * Replace ``options, args = parser.parse_args()`` with ``args = | 
| Benjamin Peterson | 90c5802 | 2010-03-03 01:55:09 +0000 | [diff] [blame] | 1712 | parser.parse_args()`` and add additional :meth:`ArgumentParser.add_argument` calls for the | 
| Georg Brandl | d2decd9 | 2010-03-02 22:17:38 +0000 | [diff] [blame] | 1713 | positional arguments. | 
| Benjamin Peterson | a39e966 | 2010-03-02 22:05:59 +0000 | [diff] [blame] | 1714 |  | 
|  | 1715 | * Replace callback actions and the ``callback_*`` keyword arguments with | 
|  | 1716 | ``type`` or ``action`` arguments. | 
|  | 1717 |  | 
|  | 1718 | * Replace string names for ``type`` keyword arguments with the corresponding | 
|  | 1719 | type objects (e.g. int, float, complex, etc). | 
|  | 1720 |  | 
| Benjamin Peterson | 90c5802 | 2010-03-03 01:55:09 +0000 | [diff] [blame] | 1721 | * Replace :class:`optparse.Values` with :class:`Namespace` and | 
|  | 1722 | :exc:`optparse.OptionError` and :exc:`optparse.OptionValueError` with | 
|  | 1723 | :exc:`ArgumentError`. | 
| Benjamin Peterson | a39e966 | 2010-03-02 22:05:59 +0000 | [diff] [blame] | 1724 |  | 
| Georg Brandl | d2decd9 | 2010-03-02 22:17:38 +0000 | [diff] [blame] | 1725 | * Replace strings with implicit arguments such as ``%default`` or ``%prog`` with | 
|  | 1726 | the standard python syntax to use dictionaries to format strings, that is, | 
|  | 1727 | ``%(default)s`` and ``%(prog)s``. | 
| Steven Bethard | 74bd9cf | 2010-05-24 02:38:00 +0000 | [diff] [blame^] | 1728 |  | 
|  | 1729 | * Replace the OptionParser constructor ``version`` argument with a call to | 
|  | 1730 | ``parser.add_argument('--version', action='version', version='<the version>')`` |