blob: f3962e0ee1362b5ce17be8b4709d3f3cbf8da52c [file] [log] [blame]
Benjamin Petersona39e9662010-03-02 22:05:59 +00001: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
11The :mod:`argparse` module makes it easy to write user friendly command line
Benjamin Peterson90c58022010-03-03 01:55:09 +000012interfaces. The program defines what arguments it requires, and :mod:`argparse`
Georg Brandld2decd92010-03-02 22:17:38 +000013will figure out how to parse those out of :data:`sys.argv`. The :mod:`argparse`
Benjamin Peterson90c58022010-03-03 01:55:09 +000014module also automatically generates help and usage messages and issues errors
15when users give the program invalid arguments.
Benjamin Petersona39e9662010-03-02 22:05:59 +000016
17Example
18-------
19
Benjamin Peterson90c58022010-03-03 01:55:09 +000020The following code is a Python program that takes a list of integers and
21produces either the sum or the max::
Benjamin Petersona39e9662010-03-02 22:05:59 +000022
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
35Assuming the Python code above is saved into a file called ``prog.py``, it can
36be 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
50When run with the appropriate arguments, it prints either the sum or the max of
51the 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
59If 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
65The following sections walk you through this example.
66
67Creating a parser
68^^^^^^^^^^^^^^^^^
69
Benjamin Peterson90c58022010-03-03 01:55:09 +000070Mose uses of the :mod:`argparse` module will start out by creating an
71:class:`ArgumentParser` object::
Benjamin Petersona39e9662010-03-02 22:05:59 +000072
73 >>> parser = argparse.ArgumentParser(description='Process some integers.')
74
75The :class:`ArgumentParser` object will hold all the information necessary to
Benjamin Peterson90c58022010-03-03 01:55:09 +000076parse the command line into python data types.
Benjamin Petersona39e9662010-03-02 22:05:59 +000077
78
79Adding arguments
80^^^^^^^^^^^^^^^^
81
Benjamin Peterson90c58022010-03-03 01:55:09 +000082Filling an :class:`ArgumentParser` with information about program arguments is
83done by making calls to the :meth:`~ArgumentParser.add_argument` method.
84Generally, these calls tell the :class:`ArgumentParser` how to take the strings
85on the command line and turn them into objects. This information is stored and
86used when :meth:`~ArgumentParser.parse_args` is called. For example::
Benjamin Petersona39e9662010-03-02 22:05:59 +000087
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 Peterson90c58022010-03-03 01:55:09 +000094Later, calling :meth:`parse_args` will return an object with
Georg Brandld2decd92010-03-02 22:17:38 +000095two attributes, ``integers`` and ``accumulate``. The ``integers`` attribute
96will be a list of one or more ints, and the ``accumulate`` attribute will be
97either the :func:`sum` function, if ``--sum`` was specified at the command line,
98or the :func:`max` function if it was not.
Benjamin Petersona39e9662010-03-02 22:05:59 +000099
100Parsing arguments
101^^^^^^^^^^^^^^^^^
102
Benjamin Peterson90c58022010-03-03 01:55:09 +0000103:class:`ArgumentParser` parses args through the
104:meth:`~ArgumentParser.parse_args` method. This will inspect the command-line,
Georg Brandld2decd92010-03-02 22:17:38 +0000105convert each arg to the appropriate type and then invoke the appropriate action.
106In most cases, this means a simple namespace object will be built up from
107attributes parsed out of the command-line::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000108
109 >>> parser.parse_args(['--sum', '7', '-1', '42'])
110 Namespace(accumulate=<built-in function sum>, integers=[7, -1, 42])
111
Benjamin Peterson90c58022010-03-03 01:55:09 +0000112In a script, :meth:`~ArgumentParser.parse_args` will typically be called with no
113arguments, and the :class:`ArgumentParser` will automatically determine the
114command-line args from :data:`sys.argv`.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000115
116
117ArgumentParser objects
118----------------------
119
120.. class:: ArgumentParser([description], [epilog], [prog], [usage], [add_help], [argument_default], [parents], [prefix_chars], [conflict_handler], [formatter_class])
121
Georg Brandld2decd92010-03-02 22:17:38 +0000122 Create a new :class:`ArgumentParser` object. Each parameter has its own more
Benjamin Petersona39e9662010-03-02 22:05:59 +0000123 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 Peterson90c58022010-03-03 01:55:09 +0000129 * add_help_ - Add a -h/--help option to the parser. (default: ``True``)
Benjamin Petersona39e9662010-03-02 22:05:59 +0000130
131 * argument_default_ - Set the global default value for arguments.
Benjamin Peterson90c58022010-03-03 01:55:09 +0000132 (default: ``None``)
Benjamin Petersona39e9662010-03-02 22:05:59 +0000133
Benjamin Peterson90c58022010-03-03 01:55:09 +0000134 * parents_ - A list of :class:`ArgumentParser` objects whose arguments should
Benjamin Petersona39e9662010-03-02 22:05:59 +0000135 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 Peterson90c58022010-03-03 01:55:09 +0000141 which additional arguments should be read. (default: ``None``)
Benjamin Petersona39e9662010-03-02 22:05:59 +0000142
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 Peterson90c58022010-03-03 01:55:09 +0000148 * prog_ - The name of the program (default:
149 :data:`sys.argv[0]`)
Benjamin Petersona39e9662010-03-02 22:05:59 +0000150
Benjamin Peterson90c58022010-03-03 01:55:09 +0000151 * usage_ - The string describing the program usage (default: generated)
Benjamin Petersona39e9662010-03-02 22:05:59 +0000152
Benjamin Peterson90c58022010-03-03 01:55:09 +0000153The following sections describe how each of these are used.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000154
155
156description
157^^^^^^^^^^^
158
Benjamin Peterson90c58022010-03-03 01:55:09 +0000159Most calls to the :class:`ArgumentParser` constructor will use the
160``description=`` keyword argument. This argument gives a brief description of
161what the program does and how it works. In help messages, the description is
162displayed between the command-line usage string and the help messages for the
163various arguments::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000164
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
174By default, the description will be line-wrapped so that it fits within the
Georg Brandld2decd92010-03-02 22:17:38 +0000175given space. To change this behavior, see the formatter_class_ argument.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000176
177
178epilog
179^^^^^^
180
181Some programs like to display additional description of the program after the
Georg Brandld2decd92010-03-02 22:17:38 +0000182description of the arguments. Such text can be specified using the ``epilog=``
183argument to :class:`ArgumentParser`::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000184
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
198As with the description_ argument, the ``epilog=`` text is by default
199line-wrapped, but this behavior can be adjusted with the formatter_class_
Benjamin Peterson90c58022010-03-03 01:55:09 +0000200argument to :class:`ArgumentParser`.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000201
202
203add_help
204^^^^^^^^
205
206By default, ArgumentParser objects add a ``-h/--help`` option which simply
Georg Brandld2decd92010-03-02 22:17:38 +0000207displays the parser's help message. For example, consider a file named
Benjamin Petersona39e9662010-03-02 22:05:59 +0000208``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
215If ``-h`` or ``--help`` is supplied is at the command-line, the ArgumentParser
216help 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
225Occasionally, it may be useful to disable the addition of this help option.
226This can be achieved by passing ``False`` as the ``add_help=`` argument to
Benjamin Peterson90c58022010-03-03 01:55:09 +0000227:class:`ArgumentParser`::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000228
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
238prefix_chars
239^^^^^^^^^^^^
240
241Most command-line options will use ``'-'`` as the prefix, e.g. ``-f/--foo``.
242Parsers that need to support additional prefix characters, e.g. for options
243like ``+f`` or ``/foo``, may specify them using the ``prefix_chars=`` argument
244to 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
252The ``prefix_chars=`` argument defaults to ``'-'``. Supplying a set of
253characters that does not include ``'-'`` will cause ``-f/--foo`` options to be
254disallowed.
255
256
257fromfile_prefix_chars
258^^^^^^^^^^^^^^^^^^^^^
259
Benjamin Peterson90c58022010-03-03 01:55:09 +0000260Sometimes, for example when dealing with a particularly long argument lists, it
261may make sense to keep the list of arguments in a file rather than typing it out
262at 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
264specified characters will be treated as files, and will be replaced by the
265arguments they contain. For example::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000266
Benjamin Peterson90c58022010-03-03 01:55:09 +0000267 >>> with open('args.txt', 'w') as fp:
268 ... fp.write('-f\nbar')
Benjamin Petersona39e9662010-03-02 22:05:59 +0000269 >>> parser = argparse.ArgumentParser(fromfile_prefix_chars='@')
270 >>> parser.add_argument('-f')
271 >>> parser.parse_args(['-f', 'foo', '@args.txt'])
272 Namespace(f='bar')
273
274Arguments 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 Brandld2decd92010-03-02 22:17:38 +0000276place as the original file referencing argument on the command line. So in the
Benjamin Petersona39e9662010-03-02 22:05:59 +0000277example above, the expression ``['-f', 'foo', '@args.txt']`` is considered
278equivalent to the expression ``['-f', 'foo', '-f', 'bar']``.
279
280The ``fromfile_prefix_chars=`` argument defaults to ``None``, meaning that
281arguments will never be treated as file references.
282
283argument_default
284^^^^^^^^^^^^^^^^
285
286Generally, 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 Brandld2decd92010-03-02 22:17:38 +0000288specific set of name-value pairs. Sometimes however, it may be useful to
289specify a single parser-wide default for arguments. This can be accomplished by
Benjamin Peterson90c58022010-03-03 01:55:09 +0000290passing the ``argument_default=`` keyword argument to :class:`ArgumentParser`.
291For example, to globally suppress attribute creation on :meth:`parse_args`
292calls, we supply ``argument_default=SUPPRESS``::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000293
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
303parents
304^^^^^^^
305
306Sometimes, several parsers share a common set of arguments. Rather than
Benjamin Peterson90c58022010-03-03 01:55:09 +0000307repeating the definitions of these arguments, a single parser with all the
308shared arguments and passed to ``parents=`` argument to :class:`ArgumentParser`
309can be used. The ``parents=`` argument takes a list of :class:`ArgumentParser`
310objects, collects all the positional and optional actions from them, and adds
311these actions to the :class:`ArgumentParser` object being constructed::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000312
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 Brandld2decd92010-03-02 22:17:38 +0000326Note that most parent parsers will specify ``add_help=False``. Otherwise, the
Benjamin Peterson90c58022010-03-03 01:55:09 +0000327:class:`ArgumentParser` will see two ``-h/--help`` options (one in the parent
328and one in the child) and raise an error.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000329
330
331formatter_class
332^^^^^^^^^^^^^^^
333
Benjamin Peterson90c58022010-03-03 01:55:09 +0000334:class:`ArgumentParser` objects allow the help formatting to be customized by
335specifying an alternate formatting class. Currently, there are three such
336classes: :class:`argparse.RawDescriptionHelpFormatter`,
Georg Brandld2decd92010-03-02 22:17:38 +0000337:class:`argparse.RawTextHelpFormatter` and
338:class:`argparse.ArgumentDefaultsHelpFormatter`. The first two allow more
339control over how textual descriptions are displayed, while the last
340automatically adds information about argument default values.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000341
Benjamin Peterson90c58022010-03-03 01:55:09 +0000342By default, :class:`ArgumentParser` objects line-wrap the description_ and
343epilog_ texts in command-line help messages::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000344
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 Peterson90c58022010-03-03 01:55:09 +0000365Passing :class:`argparse.RawDescriptionHelpFormatter` as ``formatter_class=``
Benjamin Petersonc516d192010-03-03 02:04:24 +0000366indicates that description_ and epilog_ are already correctly formatted and
Benjamin Peterson90c58022010-03-03 01:55:09 +0000367should not be line-wrapped::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000368
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 Peterson90c58022010-03-03 01:55:09 +0000391:class:`RawTextHelpFormatter` maintains whitespace for all sorts of help text
392including argument descriptions.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000393
Benjamin Peterson90c58022010-03-03 01:55:09 +0000394The other formatter class available, :class:`ArgumentDefaultsHelpFormatter`,
Georg Brandld2decd92010-03-02 22:17:38 +0000395will add information about the default value of each of the arguments::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000396
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
413conflict_handler
414^^^^^^^^^^^^^^^^
415
Benjamin Peterson90c58022010-03-03 01:55:09 +0000416:class:`ArgumentParser` objects do not allow two actions with the same option
417string. By default, :class:`ArgumentParser` objects raises an exception if an
418attempt is made to create an argument with an option string that is already in
419use::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000420
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
428Sometimes (e.g. when using parents_) it may be useful to simply override any
Georg Brandld2decd92010-03-02 22:17:38 +0000429older arguments with the same option string. To get this behavior, the value
Benjamin Petersona39e9662010-03-02 22:05:59 +0000430``'resolve'`` can be supplied to the ``conflict_handler=`` argument of
Benjamin Peterson90c58022010-03-03 01:55:09 +0000431:class:`ArgumentParser`::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000432
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 Peterson90c58022010-03-03 01:55:09 +0000444Note that :class:`ArgumentParser` objects only remove an action if all of its
445option strings are overridden. So, in the example above, the old ``-f/--foo``
446action is retained as the ``-f`` action, because only the ``--foo`` option
447string was overridden.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000448
449
450prog
451^^^^
452
Benjamin Peterson90c58022010-03-03 01:55:09 +0000453By default, :class:`ArgumentParser` objects uses ``sys.argv[0]`` to determine
454how to display the name of the program in help messages. This default is almost
455always desirable because it will make the help messages match how the pgoram was
456invoked on the command line. For example, consider a file named
457``myprogram.py`` with the following code::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000458
459 import argparse
460 parser = argparse.ArgumentParser()
461 parser.add_argument('--foo', help='foo help')
462 args = parser.parse_args()
463
464The 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
481To change this default behavior, another value can be supplied using the
Benjamin Peterson90c58022010-03-03 01:55:09 +0000482``prog=`` argument to :class:`ArgumentParser`::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000483
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
491Note 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
493specifier.
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
507usage
508^^^^^
509
Benjamin Peterson90c58022010-03-03 01:55:09 +0000510By default, :class:`ArgumentParser` calculates the usage message from the
Benjamin Petersona39e9662010-03-02 22:05:59 +0000511arguments 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 Peterson90c58022010-03-03 01:55:09 +0000526The default message can be overridden with the ``usage=`` keyword argument::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000527
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 Peterson90c58022010-03-03 01:55:09 +0000541The ``%(prog)s`` format specifier is available to fill in the program name in
542your usage messages.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000543
544
545The add_argument() method
546-------------------------
547
Benjamin Peterson90c58022010-03-03 01:55:09 +0000548.. method:: ArgumentParser.add_argument(name or flags..., [action], [nargs], [const], [default], [type], [choices], [required], [help], [metavar], [dest])
Benjamin Petersona39e9662010-03-02 22:05:59 +0000549
Georg Brandld2decd92010-03-02 22:17:38 +0000550 Define how a single command line argument should be parsed. Each parameter
Benjamin Petersona39e9662010-03-02 22:05:59 +0000551 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 Peterson90c58022010-03-03 01:55:09 +0000580The following sections describe how each of these are used.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000581
582name or flags
583^^^^^^^^^^^^^
584
Benjamin Peterson90c58022010-03-03 01:55:09 +0000585The :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
587expected. The first arguments passed to :meth:`add_argument` must therefore be
588either a series of flags, or a simple argument name. For example, an optional
589argument could be created like::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000590
591 >>> parser.add_argument('-f', '--foo')
592
593while a positional argument could be created like::
594
595 >>> parser.add_argument('bar')
596
597When :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
611action
612^^^^^^
613
Georg Brandld2decd92010-03-02 22:17:38 +0000614:class:`ArgumentParser` objects associate command-line args with actions. These
Benjamin Petersona39e9662010-03-02 22:05:59 +0000615actions can do just about anything with the command-line args associated with
616them, though most actions simply add an attribute to the object returned by
Benjamin Peterson90c58022010-03-03 01:55:09 +0000617:meth:`parse_args`. The ``action`` keyword argument specifies how the
618command-line args should be handled. The supported actions are:
Benjamin Petersona39e9662010-03-02 22:05:59 +0000619
Georg Brandld2decd92010-03-02 22:17:38 +0000620* ``'store'`` - This just stores the argument's value. This is the default
Benjamin Petersona39e9662010-03-02 22:05:59 +0000621 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 Peterson90c58022010-03-03 01:55:09 +0000629 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 Petersona39e9662010-03-02 22:05:59 +0000632
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 Peterson90c58022010-03-03 01:55:09 +0000639 ``False`` respectively. These are special cases of ``'store_const'``. For
640 example::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000641
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 Peterson90c58022010-03-03 01:55:09 +0000649 list. This is useful to allow an option to be specified multiple times.
650 Example usage::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000651
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 Peterson90c58022010-03-03 01:55:09 +0000658 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 Petersona39e9662010-03-02 22:05:59 +0000662
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')
675 >>> parser.add_argument('-v', '--version', action='version', version='%(prog)s 2.0')
676 >>> parser.parse_args(['-v'])
677 PROG 2.0
678
679You can also specify an arbitrary action by passing an object that implements
Benjamin Peterson90c58022010-03-03 01:55:09 +0000680the 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 Petersona39e9662010-03-02 22:05:59 +0000683
684* ``parser`` - The ArgumentParser object which contains this action.
685
686* ``namespace`` - The namespace object that will be returned by
Georg Brandld2decd92010-03-02 22:17:38 +0000687 :meth:`parse_args`. Most actions add an attribute to this object.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000688
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 Peterson90c58022010-03-03 01:55:09 +0000697An example of a custom action::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000698
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
714nargs
715^^^^^
716
717ArgumentParser objects usually associate a single command-line argument with a
Benjamin Peterson90c58022010-03-03 01:55:09 +0000718single action to be taken. The ``nargs`` keyword argument associates a
719different number of command-line arguments with a single action.. The supported
720values are:
Benjamin Petersona39e9662010-03-02 22:05:59 +0000721
Georg Brandld2decd92010-03-02 22:17:38 +0000722* N (an integer). N args from the command-line will be gathered together into a
723 list. For example::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000724
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 Brandld2decd92010-03-02 22:17:38 +0000741 >>> 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 Petersona39e9662010-03-02 22:05:59 +0000750
Georg Brandld2decd92010-03-02 22:17:38 +0000751 One of the more common uses of ``nargs='?'`` is to allow optional input and
752 output files::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000753
Georg Brandld2decd92010-03-02 22:17:38 +0000754 >>> 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 Petersona39e9662010-03-02 22:05:59 +0000761
Georg Brandld2decd92010-03-02 22:17:38 +0000762* ``'*'``. 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 Petersona39e9662010-03-02 22:05:59 +0000766
Georg Brandld2decd92010-03-02 22:17:38 +0000767 >>> 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 Petersona39e9662010-03-02 22:05:59 +0000773
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 Brandld2decd92010-03-02 22:17:38 +0000778 >>> 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 Petersona39e9662010-03-02 22:05:59 +0000785
786If the ``nargs`` keyword argument is not provided, the number of args consumed
Georg Brandld2decd92010-03-02 22:17:38 +0000787is determined by the action_. Generally this means a single command-line arg
Benjamin Petersona39e9662010-03-02 22:05:59 +0000788will be consumed and a single item (not a list) will be produced.
789
790
791const
792^^^^^
793
794The ``const`` argument of :meth:`add_argument` is used to hold constant values
795that are not read from the command line but are required for the various
796ArgumentParser 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 Brandld2decd92010-03-02 22:17:38 +0000804 ``--foo``) and ``nargs='?'``. This creates an optional argument that can be
Benjamin Petersona39e9662010-03-02 22:05:59 +0000805 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
810The ``const`` keyword argument defaults to ``None``.
811
812
813default
814^^^^^^^
815
816All optional arguments and some positional arguments may be omitted at the
817command-line. The ``default`` keyword argument of :meth:`add_argument`, whose
818value defaults to ``None``, specifies what value should be used if the
819command-line arg is not present. For optional arguments, the ``default`` value
820is 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
829For positional arguments with nargs_ ``='?'`` or ``'*'``, the ``default`` value
830is 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 Peterson90c58022010-03-03 01:55:09 +0000840Providing ``default=argparse.SUPPRESS`` causes no attribute to be added if the
841command-line argument was not present.::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000842
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
851type
852^^^^
853
854By default, ArgumentParser objects read command-line args in as simple strings.
855However, quite often the command-line string should instead be interpreted as
Benjamin Peterson90c58022010-03-03 01:55:09 +0000856another type, like a :class:`float`, :class:`int` or :class:`file`. The
857``type`` keyword argument of :meth:`add_argument` allows any necessary
858type-checking and type-conversions to be performed. Many common builtin types
859can be used directly as the value of the ``type`` argument::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000860
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
867To ease the use of various types of files, the argparse module provides the
868factory FileType which takes the ``mode=`` and ``bufsize=`` arguments of the
Georg Brandld2decd92010-03-02 22:17:38 +0000869``file`` object. For example, ``FileType('w')`` can be used to create a
Benjamin Petersona39e9662010-03-02 22:05:59 +0000870writable 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 Peterson90c58022010-03-03 01:55:09 +0000877``type=`` can take any callable that takes a single string argument and returns
878the type-converted value::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000879
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 Peterson90c58022010-03-03 01:55:09 +0000896The choices_ keyword argument may be more convenient for type checkers that
897simply check against a range of values::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000898
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
907See the choices_ section for more details.
908
909
910choices
911^^^^^^^
912
913Some command-line args should be selected from a restricted set of values.
Benjamin Peterson90c58022010-03-03 01:55:09 +0000914These can be handled by passing a container object as the ``choices`` keyword
915argument to :meth:`add_argument`. When the command-line is parsed, arg values
916will be checked, and an error message will be displayed if the arg was not one
917of the acceptable values::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000918
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
927Note that inclusion in the ``choices`` container is checked after any type_
928conversions have been performed, so the type of the objects in the ``choices``
929container 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
939Any object that supports the ``in`` operator can be passed as the ``choices``
Georg Brandld2decd92010-03-02 22:17:38 +0000940value, so :class:`dict` objects, :class:`set` objects, custom containers,
941etc. are all supported.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000942
943
944required
945^^^^^^^^
946
947In general, the argparse module assumes that flags like ``-f`` and ``--bar``
948indicate *optional* arguments, which can always be omitted at the command-line.
Benjamin Peterson90c58022010-03-03 01:55:09 +0000949To make an option *required*, ``True`` can be specified for the ``required=``
950keyword argument to :meth:`add_argument`::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000951
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
960As the example shows, if an option is marked as ``required``, :meth:`parse_args`
961will report an error if that option is not present at the command line.
962
Benjamin Peterson90c58022010-03-03 01:55:09 +0000963.. 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 Petersona39e9662010-03-02 22:05:59 +0000967
968
969help
970^^^^
971
Benjamin Peterson90c58022010-03-03 01:55:09 +0000972The ``help`` value is a string containing a brief description of the argument.
973When a user requests help (usually by using ``-h`` or ``--help`` at the
974command-line), these ``help`` descriptions will be displayed with each
Georg Brandld2decd92010-03-02 22:17:38 +0000975argument::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000976
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
992The ``help`` strings can include various format specifiers to avoid repetition
993of things like the program name or the argument default_. The available
994specifiers 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
1010metavar
1011^^^^^^^
1012
Benjamin Peterson90c58022010-03-03 01:55:09 +00001013When :class:`ArgumentParser` generates help messages, it need some way to refer
Georg Brandld2decd92010-03-02 22:17:38 +00001014to each expected argument. By default, ArgumentParser objects use the dest_
Benjamin Petersona39e9662010-03-02 22:05:59 +00001015value as the "name" of each object. By default, for positional argument
1016actions, the dest_ value is used directly, and for optional argument actions,
Benjamin Peterson90c58022010-03-03 01:55:09 +00001017the dest_ value is uppercased. So, a single positional argument with
1018``dest='bar'`` will that argument will be referred to as ``bar``. A single
1019optional argument ``--foo`` that should be followed by a single command-line arg
1020will be referred to as ``FOO``. An example::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001021
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 Peterson90c58022010-03-03 01:55:09 +00001037An alternative name can be specified with ``metavar``::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001038
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
1054Note that ``metavar`` only changes the *displayed* name - the name of the
1055attribute on the :meth:`parse_args` object is still determined by the dest_
1056value.
1057
1058Different values of ``nargs`` may cause the metavar to be used multiple times.
Benjamin Peterson90c58022010-03-03 01:55:09 +00001059Providing a tuple to ``metavar`` specifies a different display for each of the
1060arguments::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001061
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
1074dest
1075^^^^
1076
Benjamin Peterson90c58022010-03-03 01:55:09 +00001077Most :class:`ArgumentParser` actions add some value as an attribute of the
1078object returned by :meth:`parse_args`. The name of this attribute is determined
1079by the ``dest`` keyword argument of :meth:`add_argument`. For positional
1080argument actions, ``dest`` is normally supplied as the first argument to
Benjamin Petersona39e9662010-03-02 22:05:59 +00001081:meth:`add_argument`::
1082
1083 >>> parser = argparse.ArgumentParser()
1084 >>> parser.add_argument('bar')
1085 >>> parser.parse_args('XXX'.split())
1086 Namespace(bar='XXX')
1087
1088For optional argument actions, the value of ``dest`` is normally inferred from
Benjamin Peterson90c58022010-03-03 01:55:09 +00001089the option strings. :class:`ArgumentParser` generates the value of ``dest`` by
Benjamin Petersona39e9662010-03-02 22:05:59 +00001090taking the first long option string and stripping away the initial ``'--'``
1091string. If no long option strings were supplied, ``dest`` will be derived from
1092the first short option string by stripping the initial ``'-'`` character. Any
Georg Brandld2decd92010-03-02 22:17:38 +00001093internal ``'-'`` characters will be converted to ``'_'`` characters to make sure
1094the string is a valid attribute name. The examples below illustrate this
Benjamin Petersona39e9662010-03-02 22:05:59 +00001095behavior::
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 Peterson90c58022010-03-03 01:55:09 +00001105``dest`` allows a custom attribute name to be provided::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001106
1107 >>> parser = argparse.ArgumentParser()
1108 >>> parser.add_argument('--foo', dest='bar')
1109 >>> parser.parse_args('--foo XXX'.split())
1110 Namespace(bar='XXX')
1111
1112
1113The parse_args() method
1114-----------------------
1115
Benjamin Peterson90c58022010-03-03 01:55:09 +00001116.. method:: ArgumentParser.parse_args([args], [namespace])
Benjamin Petersona39e9662010-03-02 22:05:59 +00001117
Benjamin Peterson90c58022010-03-03 01:55:09 +00001118 Convert argument strings to objects and assign them as attributes of the
Georg Brandld2decd92010-03-02 22:17:38 +00001119 namespace. Return the populated namespace.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001120
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 Brandld2decd92010-03-02 22:17:38 +00001125 By default, the arg strings are taken from :data:`sys.argv`, and a new empty
Benjamin Peterson90c58022010-03-03 01:55:09 +00001126 :class:`Namespace` object is created for the attributes.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001127
1128Option value syntax
1129^^^^^^^^^^^^^^^^^^^
1130
1131The :meth:`parse_args` method supports several ways of specifying the value of
Georg Brandld2decd92010-03-02 22:17:38 +00001132an option (if it takes one). In the simplest case, the option and its value are
Benjamin Petersona39e9662010-03-02 22:05:59 +00001133passed 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 Peterson90c58022010-03-03 01:55:09 +00001143For long options (options with names longer than a single character), the option
1144and value can also be passed as a single command line argument, using ``=`` to
Georg Brandld2decd92010-03-02 22:17:38 +00001145separate them::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001146
1147 >>> parser.parse_args('--foo=FOO'.split())
1148 Namespace(foo='FOO', x=None)
1149
Benjamin Peterson90c58022010-03-03 01:55:09 +00001150For short options (options only one character long), the option and its value
1151can be concatenated::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001152
1153 >>> parser.parse_args('-xX'.split())
1154 Namespace(foo=None, x='X')
1155
Benjamin Peterson90c58022010-03-03 01:55:09 +00001156Several short options can be joined together, using only a single ``-`` prefix,
1157as long as only the last option (or none of them) requires a value::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001158
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
1167Invalid arguments
1168^^^^^^^^^^^^^^^^^
1169
1170While parsing the command-line, ``parse_args`` checks for a variety of errors,
1171including ambiguous options, invalid types, invalid options, wrong number of
Georg Brandld2decd92010-03-02 22:17:38 +00001172positional arguments, etc. When it encounters such an error, it exits and
Benjamin Petersona39e9662010-03-02 22:05:59 +00001173prints 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
1195Arguments containing ``"-"``
1196^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1197
1198The ``parse_args`` method attempts to give errors whenever the user has clearly
Georg Brandld2decd92010-03-02 22:17:38 +00001199made a mistake, but some situations are inherently ambiguous. For example, the
Benjamin Petersona39e9662010-03-02 22:05:59 +00001200command-line arg ``'-1'`` could either be an attempt to specify an option or an
Georg Brandld2decd92010-03-02 22:17:38 +00001201attempt to provide a positional argument. The ``parse_args`` method is cautious
Benjamin Petersona39e9662010-03-02 22:05:59 +00001202here: positional arguments may only begin with ``'-'`` if they look like
1203negative numbers and there are no options in the parser that look like negative
1204numbers::
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
1236If you have positional arguments that must begin with ``'-'`` and don't look
1237like 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
1244Argument abbreviations
1245^^^^^^^^^^^^^^^^^^^^^^
1246
Benjamin Peterson90c58022010-03-03 01:55:09 +00001247The :meth:`parse_args` method allows long options to be abbreviated if the
Benjamin Petersona39e9662010-03-02 22:05:59 +00001248abbreviation 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 Peterson90c58022010-03-03 01:55:09 +00001261An error is produced for arguments that could produce more than one options.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001262
1263
1264Beyond ``sys.argv``
1265^^^^^^^^^^^^^^^^^^^
1266
Georg Brandld2decd92010-03-02 22:17:38 +00001267Sometimes it may be useful to have an ArgumentParser parse args other than those
1268of :data:`sys.argv`. This can be accomplished by passing a list of strings to
Benjamin Peterson90c58022010-03-03 01:55:09 +00001269``parse_args``. This is useful for testing at the interactive prompt::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001270
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
1284Custom namespaces
1285^^^^^^^^^^^^^^^^^
1286
Benjamin Peterson90c58022010-03-03 01:55:09 +00001287It may also be useful to have an :class:`ArgumentParser` assign attributes to an
1288already existing object, rather than the newly-created :class:`Namespace` object
1289that is normally used. This can be achieved by specifying the ``namespace=``
1290keyword argument::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001291
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
1303Other utilities
1304---------------
1305
1306Sub-commands
1307^^^^^^^^^^^^
1308
Benjamin Peterson90c58022010-03-03 01:55:09 +00001309.. method:: ArgumentParser.add_subparsers()
Benjamin Petersona39e9662010-03-02 22:05:59 +00001310
Benjamin Peterson90c58022010-03-03 01:55:09 +00001311 Many programs split up their functionality into a number of sub-commands,
Georg Brandld2decd92010-03-02 22:17:38 +00001312 for example, the ``svn`` program can invoke sub-commands like ``svn
Benjamin Peterson90c58022010-03-03 01:55:09 +00001313 checkout``, ``svn update``, and ``svn commit``. Splitting up functionality
Georg Brandld2decd92010-03-02 22:17:38 +00001314 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 Peterson90c58022010-03-03 01:55:09 +00001316 :class:`ArgumentParser` supports the creation of such sub-commands with the
Georg Brandld2decd92010-03-02 22:17:38 +00001317 :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 Peterson90c58022010-03-03 01:55:09 +00001320 :class:`ArgumentParser` constructor arguments, and returns an
1321 :class:`ArgumentParser` object that can be modified as usual.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001322
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 Brandld2decd92010-03-02 22:17:38 +00001347 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 Petersona39e9662010-03-02 22:05:59 +00001349 ``baz`` attributes are present.
1350
1351 Similarly, when a help message is requested from a subparser, only the help
Georg Brandld2decd92010-03-02 22:17:38 +00001352 for that particular parser will be printed. The help message will not
Benjamin Peterson90c58022010-03-03 01:55:09 +00001353 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 Petersona39e9662010-03-02 22:05:59 +00001356
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 Brandld2decd92010-03-02 22:17:38 +00001387 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 Petersona39e9662010-03-02 22:05:59 +00001390
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 Brandld2decd92010-03-02 22:17:38 +00001409 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 Petersona39e9662010-03-02 22:05:59 +00001412 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 Peterson90c58022010-03-03 01:55:09 +00001446 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 Petersona39e9662010-03-02 22:05:59 +00001452
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
1463FileType 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 Peterson90c58022010-03-03 01:55:09 +00001469 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 Petersona39e9662010-03-02 22:05:59 +00001472
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
1488Argument groups
1489^^^^^^^^^^^^^^^
1490
Benjamin Peterson90c58022010-03-03 01:55:09 +00001491.. method:: ArgumentParser.add_argument_group([title], [description])
Benjamin Petersona39e9662010-03-02 22:05:59 +00001492
Benjamin Peterson90c58022010-03-03 01:55:09 +00001493 By default, :class:`ArgumentParser` groups command-line arguments into
Benjamin Petersona39e9662010-03-02 22:05:59 +00001494 "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 Peterson90c58022010-03-03 01:55:09 +00001511 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 Petersona39e9662010-03-02 22:05:59 +00001517
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 Peterson90c58022010-03-03 01:55:09 +00001536 Note that any arguments not your user defined groups will end up back in the
1537 usual "positional arguments" and "optional arguments" sections.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001538
1539
1540Mutual exclusion
1541^^^^^^^^^^^^^^^^
1542
1543.. method:: add_mutually_exclusive_group([required=False])
1544
Benjamin Peterson90c58022010-03-03 01:55:09 +00001545 Create a mutually exclusive group. argparse will make sure that only one of
Benjamin Petersona39e9662010-03-02 22:05:59 +00001546 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 Peterson90c58022010-03-03 01:55:09 +00001574 ``title`` and ``description`` arguments of :meth:`add_argument_group`.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001575
1576
1577Parser defaults
1578^^^^^^^^^^^^^^^
1579
Benjamin Peterson90c58022010-03-03 01:55:09 +00001580.. method:: ArgumentParser.set_defaults(**kwargs)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001581
Georg Brandld2decd92010-03-02 22:17:38 +00001582 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 Petersonc516d192010-03-03 02:04:24 +00001584 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 Petersona39e9662010-03-02 22:05:59 +00001587
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 Peterson90c58022010-03-03 01:55:09 +00001594 Note that parser-level defaults always override argument-level defaults::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001595
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 Peterson90c58022010-03-03 01:55:09 +00001602 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 Petersona39e9662010-03-02 22:05:59 +00001605
Benjamin Peterson90c58022010-03-03 01:55:09 +00001606.. method:: ArgumentParser.get_default(dest)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001607
1608 Get the default value for a namespace attribute, as set by either
Benjamin Peterson90c58022010-03-03 01:55:09 +00001609 :meth:`~ArgumentParser.add_argument` or by
1610 :meth:`~ArgumentParser.set_defaults`::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001611
1612 >>> parser = argparse.ArgumentParser()
1613 >>> parser.add_argument('--foo', default='badger')
1614 >>> parser.get_default('foo')
1615 'badger'
1616
1617
1618Printing help
1619^^^^^^^^^^^^^
1620
1621In most typical applications, :meth:`parse_args` will take care of formatting
Benjamin Peterson90c58022010-03-03 01:55:09 +00001622and printing any usage or error messages. However, several formatting methods
1623are available:
Benjamin Petersona39e9662010-03-02 22:05:59 +00001624
Benjamin Peterson90c58022010-03-03 01:55:09 +00001625.. method:: ArgumentParser.print_usage([file]):
Benjamin Petersona39e9662010-03-02 22:05:59 +00001626
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 Peterson90c58022010-03-03 01:55:09 +00001631.. method:: ArgumentParser.print_help([file]):
Benjamin Petersona39e9662010-03-02 22:05:59 +00001632
1633 Print a help message, including the program usage and information about the
Georg Brandld2decd92010-03-02 22:17:38 +00001634 arguments registered with the :class:`ArgumentParser`. If ``file`` is not
Benjamin Petersona39e9662010-03-02 22:05:59 +00001635 present, ``sys.stderr`` is assumed.
1636
1637There are also variants of these methods that simply return a string instead of
1638printing it:
1639
Benjamin Peterson90c58022010-03-03 01:55:09 +00001640.. method:: ArgumentParser.format_usage():
Benjamin Petersona39e9662010-03-02 22:05:59 +00001641
1642 Return a string containing a brief description of how the
1643 :class:`ArgumentParser` should be invoked on the command line.
1644
Benjamin Peterson90c58022010-03-03 01:55:09 +00001645.. method:: ArgumentParser.format_help():
Benjamin Petersona39e9662010-03-02 22:05:59 +00001646
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
1652Partial parsing
1653^^^^^^^^^^^^^^^
1654
Benjamin Peterson90c58022010-03-03 01:55:09 +00001655.. method:: ArgumentParser.parse_known_args([args], [namespace])
Benjamin Petersona39e9662010-03-02 22:05:59 +00001656
1657Sometimes a script may only parse a few of the command line arguments, passing
1658the remaining arguments on to another script or program. In these cases, the
Georg Brandld2decd92010-03-02 22:17:38 +00001659:meth:`parse_known_args` method can be useful. It works much like
Benjamin Peterson90c58022010-03-03 01:55:09 +00001660:meth:`~ArgumentParser.parse_args` except that it does not produce an error when
1661extra arguments are present. Instead, it returns a two item tuple containing
1662the populated namespace and the list of remaining argument strings.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001663
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
1673Customizing file parsing
1674^^^^^^^^^^^^^^^^^^^^^^^^
1675
Benjamin Peterson90c58022010-03-03 01:55:09 +00001676.. method:: ArgumentParser.convert_arg_line_to_args(arg_line)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001677
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 Peterson90c58022010-03-03 01:55:09 +00001680 argument per line. :meth:`convert_arg_line_to_args` can be overriden for
1681 fancier reading.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001682
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 Brandld2decd92010-03-02 22:17:38 +00001687 A useful override of this method is one that treats each space-separated word
1688 as an argument::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001689
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
1697Upgrading optparse code
1698-----------------------
1699
1700Originally, the argparse module had attempted to maintain compatibility with
Georg Brandld2decd92010-03-02 22:17:38 +00001701optparse. However, optparse was difficult to extend transparently, particularly
1702with the changes required to support the new ``nargs=`` specifiers and better
1703usage messges. When most everything in optparse had either been copy-pasted
1704over or monkey-patched, it no longer seemed practical to try to maintain the
1705backwards compatibility.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001706
1707A partial upgrade path from optparse to argparse:
1708
Benjamin Peterson90c58022010-03-03 01:55:09 +00001709* Replace all ``add_option()`` calls with :meth:`ArgumentParser.add_argument` calls.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001710
Georg Brandld2decd92010-03-02 22:17:38 +00001711* Replace ``options, args = parser.parse_args()`` with ``args =
Benjamin Peterson90c58022010-03-03 01:55:09 +00001712 parser.parse_args()`` and add additional :meth:`ArgumentParser.add_argument` calls for the
Georg Brandld2decd92010-03-02 22:17:38 +00001713 positional arguments.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001714
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 Peterson90c58022010-03-03 01:55:09 +00001721* Replace :class:`optparse.Values` with :class:`Namespace` and
1722 :exc:`optparse.OptionError` and :exc:`optparse.OptionValueError` with
1723 :exc:`ArgumentError`.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001724
Georg Brandld2decd92010-03-02 22:17:38 +00001725* 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``.