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