blob: 0ea8195a0e0bfb3ff9df88276c9e6ea64bb6c4bf [file] [log] [blame]
Georg Brandlb8d0e362010-11-26 07:53:50 +00001:mod:`argparse` --- Parser for command line options, arguments and sub-commands
2===============================================================================
Benjamin Petersona39e9662010-03-02 22:05:59 +00003
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
Georg Brandlb8d0e362010-11-26 07:53:50 +000017
Benjamin Petersona39e9662010-03-02 22:05:59 +000018Example
19-------
20
Benjamin Peterson90c58022010-03-03 01:55:09 +000021The following code is a Python program that takes a list of integers and
22produces either the sum or the max::
Benjamin Petersona39e9662010-03-02 22:05:59 +000023
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
36Assuming the Python code above is saved into a file called ``prog.py``, it can
37be 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
51When run with the appropriate arguments, it prints either the sum or the max of
52the 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
60If 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
66The following sections walk you through this example.
67
Georg Brandlb8d0e362010-11-26 07:53:50 +000068
Benjamin Petersona39e9662010-03-02 22:05:59 +000069Creating a parser
70^^^^^^^^^^^^^^^^^
71
Benjamin Petersonac80c152010-03-03 21:28:25 +000072The first step in using the :mod:`argparse` is creating an
Benjamin Peterson90c58022010-03-03 01:55:09 +000073:class:`ArgumentParser` object::
Benjamin Petersona39e9662010-03-02 22:05:59 +000074
75 >>> parser = argparse.ArgumentParser(description='Process some integers.')
76
77The :class:`ArgumentParser` object will hold all the information necessary to
Benjamin Peterson90c58022010-03-03 01:55:09 +000078parse the command line into python data types.
Benjamin Petersona39e9662010-03-02 22:05:59 +000079
80
81Adding arguments
82^^^^^^^^^^^^^^^^
83
Benjamin Peterson90c58022010-03-03 01:55:09 +000084Filling an :class:`ArgumentParser` with information about program arguments is
85done by making calls to the :meth:`~ArgumentParser.add_argument` method.
86Generally, these calls tell the :class:`ArgumentParser` how to take the strings
87on the command line and turn them into objects. This information is stored and
88used when :meth:`~ArgumentParser.parse_args` is called. For example::
Benjamin Petersona39e9662010-03-02 22:05:59 +000089
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
Benjamin Peterson90c58022010-03-03 01:55:09 +000096Later, calling :meth:`parse_args` will return an object with
Georg Brandld2decd92010-03-02 22:17:38 +000097two attributes, ``integers`` and ``accumulate``. The ``integers`` attribute
98will be a list of one or more ints, and the ``accumulate`` attribute will be
99either the :func:`sum` function, if ``--sum`` was specified at the command line,
100or the :func:`max` function if it was not.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000101
Georg Brandlb8d0e362010-11-26 07:53:50 +0000102
Benjamin Petersona39e9662010-03-02 22:05:59 +0000103Parsing arguments
104^^^^^^^^^^^^^^^^^
105
Benjamin Peterson90c58022010-03-03 01:55:09 +0000106:class:`ArgumentParser` parses args through the
107:meth:`~ArgumentParser.parse_args` method. This will inspect the command-line,
Georg Brandld2decd92010-03-02 22:17:38 +0000108convert each arg to the appropriate type and then invoke the appropriate action.
109In most cases, this means a simple namespace object will be built up from
110attributes parsed out of the command-line::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000111
112 >>> parser.parse_args(['--sum', '7', '-1', '42'])
113 Namespace(accumulate=<built-in function sum>, integers=[7, -1, 42])
114
Benjamin Peterson90c58022010-03-03 01:55:09 +0000115In a script, :meth:`~ArgumentParser.parse_args` will typically be called with no
116arguments, and the :class:`ArgumentParser` will automatically determine the
117command-line args from :data:`sys.argv`.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000118
119
120ArgumentParser objects
121----------------------
122
123.. class:: ArgumentParser([description], [epilog], [prog], [usage], [add_help], [argument_default], [parents], [prefix_chars], [conflict_handler], [formatter_class])
124
Georg Brandld2decd92010-03-02 22:17:38 +0000125 Create a new :class:`ArgumentParser` object. Each parameter has its own more
Benjamin Petersona39e9662010-03-02 22:05:59 +0000126 detailed description below, but in short they are:
127
128 * description_ - Text to display before the argument help.
129
130 * epilog_ - Text to display after the argument help.
131
Benjamin Peterson90c58022010-03-03 01:55:09 +0000132 * add_help_ - Add a -h/--help option to the parser. (default: ``True``)
Benjamin Petersona39e9662010-03-02 22:05:59 +0000133
134 * argument_default_ - Set the global default value for arguments.
Benjamin Peterson90c58022010-03-03 01:55:09 +0000135 (default: ``None``)
Benjamin Petersona39e9662010-03-02 22:05:59 +0000136
Benjamin Peterson90c58022010-03-03 01:55:09 +0000137 * parents_ - A list of :class:`ArgumentParser` objects whose arguments should
Benjamin Petersona39e9662010-03-02 22:05:59 +0000138 also be included.
139
140 * prefix_chars_ - The set of characters that prefix optional arguments.
141 (default: '-')
142
143 * fromfile_prefix_chars_ - The set of characters that prefix files from
Benjamin Peterson90c58022010-03-03 01:55:09 +0000144 which additional arguments should be read. (default: ``None``)
Benjamin Petersona39e9662010-03-02 22:05:59 +0000145
146 * formatter_class_ - A class for customizing the help output.
147
148 * conflict_handler_ - Usually unnecessary, defines strategy for resolving
149 conflicting optionals.
150
Benjamin Peterson90c58022010-03-03 01:55:09 +0000151 * prog_ - The name of the program (default:
152 :data:`sys.argv[0]`)
Benjamin Petersona39e9662010-03-02 22:05:59 +0000153
Benjamin Peterson90c58022010-03-03 01:55:09 +0000154 * usage_ - The string describing the program usage (default: generated)
Benjamin Petersona39e9662010-03-02 22:05:59 +0000155
Benjamin Peterson90c58022010-03-03 01:55:09 +0000156The following sections describe how each of these are used.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000157
158
159description
160^^^^^^^^^^^
161
Benjamin Peterson90c58022010-03-03 01:55:09 +0000162Most calls to the :class:`ArgumentParser` constructor will use the
163``description=`` keyword argument. This argument gives a brief description of
164what the program does and how it works. In help messages, the description is
165displayed between the command-line usage string and the help messages for the
166various arguments::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000167
168 >>> parser = argparse.ArgumentParser(description='A foo that bars')
169 >>> parser.print_help()
170 usage: argparse.py [-h]
171
172 A foo that bars
173
174 optional arguments:
175 -h, --help show this help message and exit
176
177By default, the description will be line-wrapped so that it fits within the
Georg Brandld2decd92010-03-02 22:17:38 +0000178given space. To change this behavior, see the formatter_class_ argument.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000179
180
181epilog
182^^^^^^
183
184Some programs like to display additional description of the program after the
Georg Brandld2decd92010-03-02 22:17:38 +0000185description of the arguments. Such text can be specified using the ``epilog=``
186argument to :class:`ArgumentParser`::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000187
188 >>> parser = argparse.ArgumentParser(
189 ... description='A foo that bars',
190 ... epilog="And that's how you'd foo a bar")
191 >>> parser.print_help()
192 usage: argparse.py [-h]
193
194 A foo that bars
195
196 optional arguments:
197 -h, --help show this help message and exit
198
199 And that's how you'd foo a bar
200
201As with the description_ argument, the ``epilog=`` text is by default
202line-wrapped, but this behavior can be adjusted with the formatter_class_
Benjamin Peterson90c58022010-03-03 01:55:09 +0000203argument to :class:`ArgumentParser`.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000204
205
206add_help
207^^^^^^^^
208
R. David Murray1cbf78e2010-08-03 18:14:01 +0000209By default, ArgumentParser objects add an option which simply displays
210the parser's help message. For example, consider a file named
Benjamin Petersona39e9662010-03-02 22:05:59 +0000211``myprogram.py`` containing the following code::
212
213 import argparse
214 parser = argparse.ArgumentParser()
215 parser.add_argument('--foo', help='foo help')
216 args = parser.parse_args()
217
218If ``-h`` or ``--help`` is supplied is at the command-line, the ArgumentParser
219help will be printed::
220
221 $ python myprogram.py --help
222 usage: myprogram.py [-h] [--foo FOO]
223
224 optional arguments:
225 -h, --help show this help message and exit
226 --foo FOO foo help
227
228Occasionally, it may be useful to disable the addition of this help option.
229This can be achieved by passing ``False`` as the ``add_help=`` argument to
Benjamin Peterson90c58022010-03-03 01:55:09 +0000230:class:`ArgumentParser`::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000231
232 >>> parser = argparse.ArgumentParser(prog='PROG', add_help=False)
233 >>> parser.add_argument('--foo', help='foo help')
234 >>> parser.print_help()
235 usage: PROG [--foo FOO]
236
237 optional arguments:
238 --foo FOO foo help
239
R. David Murray1cbf78e2010-08-03 18:14:01 +0000240The help option is typically ``-h/--help``. The exception to this is
241if the ``prefix_chars=`` is specified and does not include ``'-'``, in
242which case ``-h`` and ``--help`` are not valid options. In
243this case, the first character in ``prefix_chars`` is used to prefix
244the help options::
245
246 >>> parser = argparse.ArgumentParser(prog='PROG', prefix_chars='+/')
247 >>> parser.print_help()
248 usage: PROG [+h]
249
250 optional arguments:
251 +h, ++help show this help message and exit
252
253
Benjamin Petersona39e9662010-03-02 22:05:59 +0000254prefix_chars
255^^^^^^^^^^^^
256
257Most command-line options will use ``'-'`` as the prefix, e.g. ``-f/--foo``.
R. David Murray1cbf78e2010-08-03 18:14:01 +0000258Parsers that need to support different or additional prefix
259characters, e.g. for options
Benjamin Petersona39e9662010-03-02 22:05:59 +0000260like ``+f`` or ``/foo``, may specify them using the ``prefix_chars=`` argument
261to the ArgumentParser constructor::
262
263 >>> parser = argparse.ArgumentParser(prog='PROG', prefix_chars='-+')
264 >>> parser.add_argument('+f')
265 >>> parser.add_argument('++bar')
266 >>> parser.parse_args('+f X ++bar Y'.split())
267 Namespace(bar='Y', f='X')
268
269The ``prefix_chars=`` argument defaults to ``'-'``. Supplying a set of
270characters that does not include ``'-'`` will cause ``-f/--foo`` options to be
271disallowed.
272
273
274fromfile_prefix_chars
275^^^^^^^^^^^^^^^^^^^^^
276
Benjamin Peterson90c58022010-03-03 01:55:09 +0000277Sometimes, for example when dealing with a particularly long argument lists, it
278may make sense to keep the list of arguments in a file rather than typing it out
279at the command line. If the ``fromfile_prefix_chars=`` argument is given to the
280:class:`ArgumentParser` constructor, then arguments that start with any of the
281specified characters will be treated as files, and will be replaced by the
282arguments they contain. For example::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000283
Benjamin Peterson90c58022010-03-03 01:55:09 +0000284 >>> with open('args.txt', 'w') as fp:
285 ... fp.write('-f\nbar')
Benjamin Petersona39e9662010-03-02 22:05:59 +0000286 >>> parser = argparse.ArgumentParser(fromfile_prefix_chars='@')
287 >>> parser.add_argument('-f')
288 >>> parser.parse_args(['-f', 'foo', '@args.txt'])
289 Namespace(f='bar')
290
291Arguments read from a file must by default be one per line (but see also
292:meth:`convert_arg_line_to_args`) and are treated as if they were in the same
Georg Brandld2decd92010-03-02 22:17:38 +0000293place as the original file referencing argument on the command line. So in the
Benjamin Petersona39e9662010-03-02 22:05:59 +0000294example above, the expression ``['-f', 'foo', '@args.txt']`` is considered
295equivalent to the expression ``['-f', 'foo', '-f', 'bar']``.
296
297The ``fromfile_prefix_chars=`` argument defaults to ``None``, meaning that
298arguments will never be treated as file references.
299
Georg Brandlb8d0e362010-11-26 07:53:50 +0000300
Benjamin Petersona39e9662010-03-02 22:05:59 +0000301argument_default
302^^^^^^^^^^^^^^^^
303
304Generally, argument defaults are specified either by passing a default to
305:meth:`add_argument` or by calling the :meth:`set_defaults` methods with a
Georg Brandld2decd92010-03-02 22:17:38 +0000306specific set of name-value pairs. Sometimes however, it may be useful to
307specify a single parser-wide default for arguments. This can be accomplished by
Benjamin Peterson90c58022010-03-03 01:55:09 +0000308passing the ``argument_default=`` keyword argument to :class:`ArgumentParser`.
309For example, to globally suppress attribute creation on :meth:`parse_args`
310calls, we supply ``argument_default=SUPPRESS``::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000311
312 >>> parser = argparse.ArgumentParser(argument_default=argparse.SUPPRESS)
313 >>> parser.add_argument('--foo')
314 >>> parser.add_argument('bar', nargs='?')
315 >>> parser.parse_args(['--foo', '1', 'BAR'])
316 Namespace(bar='BAR', foo='1')
317 >>> parser.parse_args([])
318 Namespace()
319
320
321parents
322^^^^^^^
323
324Sometimes, several parsers share a common set of arguments. Rather than
Benjamin Peterson90c58022010-03-03 01:55:09 +0000325repeating the definitions of these arguments, a single parser with all the
326shared arguments and passed to ``parents=`` argument to :class:`ArgumentParser`
327can be used. The ``parents=`` argument takes a list of :class:`ArgumentParser`
328objects, collects all the positional and optional actions from them, and adds
329these actions to the :class:`ArgumentParser` object being constructed::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000330
331 >>> parent_parser = argparse.ArgumentParser(add_help=False)
332 >>> parent_parser.add_argument('--parent', type=int)
333
334 >>> foo_parser = argparse.ArgumentParser(parents=[parent_parser])
335 >>> foo_parser.add_argument('foo')
336 >>> foo_parser.parse_args(['--parent', '2', 'XXX'])
337 Namespace(foo='XXX', parent=2)
338
339 >>> bar_parser = argparse.ArgumentParser(parents=[parent_parser])
340 >>> bar_parser.add_argument('--bar')
341 >>> bar_parser.parse_args(['--bar', 'YYY'])
342 Namespace(bar='YYY', parent=None)
343
Georg Brandld2decd92010-03-02 22:17:38 +0000344Note that most parent parsers will specify ``add_help=False``. Otherwise, the
Benjamin Peterson90c58022010-03-03 01:55:09 +0000345:class:`ArgumentParser` will see two ``-h/--help`` options (one in the parent
346and one in the child) and raise an error.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000347
348
349formatter_class
350^^^^^^^^^^^^^^^
351
Benjamin Peterson90c58022010-03-03 01:55:09 +0000352:class:`ArgumentParser` objects allow the help formatting to be customized by
353specifying an alternate formatting class. Currently, there are three such
354classes: :class:`argparse.RawDescriptionHelpFormatter`,
Georg Brandld2decd92010-03-02 22:17:38 +0000355:class:`argparse.RawTextHelpFormatter` and
356:class:`argparse.ArgumentDefaultsHelpFormatter`. The first two allow more
357control over how textual descriptions are displayed, while the last
358automatically adds information about argument default values.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000359
Benjamin Peterson90c58022010-03-03 01:55:09 +0000360By default, :class:`ArgumentParser` objects line-wrap the description_ and
361epilog_ texts in command-line help messages::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000362
363 >>> parser = argparse.ArgumentParser(
364 ... prog='PROG',
365 ... description='''this description
366 ... was indented weird
367 ... but that is okay''',
368 ... epilog='''
369 ... likewise for this epilog whose whitespace will
370 ... be cleaned up and whose words will be wrapped
371 ... across a couple lines''')
372 >>> parser.print_help()
373 usage: PROG [-h]
374
375 this description was indented weird but that is okay
376
377 optional arguments:
378 -h, --help show this help message and exit
379
380 likewise for this epilog whose whitespace will be cleaned up and whose words
381 will be wrapped across a couple lines
382
Benjamin Peterson90c58022010-03-03 01:55:09 +0000383Passing :class:`argparse.RawDescriptionHelpFormatter` as ``formatter_class=``
Benjamin Petersonc516d192010-03-03 02:04:24 +0000384indicates that description_ and epilog_ are already correctly formatted and
Benjamin Peterson90c58022010-03-03 01:55:09 +0000385should not be line-wrapped::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000386
387 >>> parser = argparse.ArgumentParser(
388 ... prog='PROG',
389 ... formatter_class=argparse.RawDescriptionHelpFormatter,
390 ... description=textwrap.dedent('''\
391 ... Please do not mess up this text!
392 ... --------------------------------
393 ... I have indented it
394 ... exactly the way
395 ... I want it
396 ... '''))
397 >>> parser.print_help()
398 usage: PROG [-h]
399
400 Please do not mess up this text!
401 --------------------------------
402 I have indented it
403 exactly the way
404 I want it
405
406 optional arguments:
407 -h, --help show this help message and exit
408
Benjamin Peterson90c58022010-03-03 01:55:09 +0000409:class:`RawTextHelpFormatter` maintains whitespace for all sorts of help text
410including argument descriptions.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000411
Benjamin Peterson90c58022010-03-03 01:55:09 +0000412The other formatter class available, :class:`ArgumentDefaultsHelpFormatter`,
Georg Brandld2decd92010-03-02 22:17:38 +0000413will add information about the default value of each of the arguments::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000414
415 >>> parser = argparse.ArgumentParser(
416 ... prog='PROG',
417 ... formatter_class=argparse.ArgumentDefaultsHelpFormatter)
418 >>> parser.add_argument('--foo', type=int, default=42, help='FOO!')
419 >>> parser.add_argument('bar', nargs='*', default=[1, 2, 3], help='BAR!')
420 >>> parser.print_help()
421 usage: PROG [-h] [--foo FOO] [bar [bar ...]]
422
423 positional arguments:
424 bar BAR! (default: [1, 2, 3])
425
426 optional arguments:
427 -h, --help show this help message and exit
428 --foo FOO FOO! (default: 42)
429
430
431conflict_handler
432^^^^^^^^^^^^^^^^
433
Benjamin Peterson90c58022010-03-03 01:55:09 +0000434:class:`ArgumentParser` objects do not allow two actions with the same option
435string. By default, :class:`ArgumentParser` objects raises an exception if an
436attempt is made to create an argument with an option string that is already in
437use::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000438
439 >>> parser = argparse.ArgumentParser(prog='PROG')
440 >>> parser.add_argument('-f', '--foo', help='old foo help')
441 >>> parser.add_argument('--foo', help='new foo help')
442 Traceback (most recent call last):
443 ..
444 ArgumentError: argument --foo: conflicting option string(s): --foo
445
446Sometimes (e.g. when using parents_) it may be useful to simply override any
Georg Brandld2decd92010-03-02 22:17:38 +0000447older arguments with the same option string. To get this behavior, the value
Benjamin Petersona39e9662010-03-02 22:05:59 +0000448``'resolve'`` can be supplied to the ``conflict_handler=`` argument of
Benjamin Peterson90c58022010-03-03 01:55:09 +0000449:class:`ArgumentParser`::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000450
451 >>> parser = argparse.ArgumentParser(prog='PROG', conflict_handler='resolve')
452 >>> parser.add_argument('-f', '--foo', help='old foo help')
453 >>> parser.add_argument('--foo', help='new foo help')
454 >>> parser.print_help()
455 usage: PROG [-h] [-f FOO] [--foo FOO]
456
457 optional arguments:
458 -h, --help show this help message and exit
459 -f FOO old foo help
460 --foo FOO new foo help
461
Benjamin Peterson90c58022010-03-03 01:55:09 +0000462Note that :class:`ArgumentParser` objects only remove an action if all of its
463option strings are overridden. So, in the example above, the old ``-f/--foo``
464action is retained as the ``-f`` action, because only the ``--foo`` option
465string was overridden.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000466
467
468prog
469^^^^
470
Benjamin Peterson90c58022010-03-03 01:55:09 +0000471By default, :class:`ArgumentParser` objects uses ``sys.argv[0]`` to determine
472how to display the name of the program in help messages. This default is almost
Ezio Melotti019551f2010-05-19 00:32:52 +0000473always desirable because it will make the help messages match how the program was
Benjamin Peterson90c58022010-03-03 01:55:09 +0000474invoked on the command line. For example, consider a file named
475``myprogram.py`` with the following code::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000476
477 import argparse
478 parser = argparse.ArgumentParser()
479 parser.add_argument('--foo', help='foo help')
480 args = parser.parse_args()
481
482The help for this program will display ``myprogram.py`` as the program name
483(regardless of where the program was invoked from)::
484
485 $ python myprogram.py --help
486 usage: myprogram.py [-h] [--foo FOO]
487
488 optional arguments:
489 -h, --help show this help message and exit
490 --foo FOO foo help
491 $ cd ..
492 $ python subdir\myprogram.py --help
493 usage: myprogram.py [-h] [--foo FOO]
494
495 optional arguments:
496 -h, --help show this help message and exit
497 --foo FOO foo help
498
499To change this default behavior, another value can be supplied using the
Benjamin Peterson90c58022010-03-03 01:55:09 +0000500``prog=`` argument to :class:`ArgumentParser`::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000501
502 >>> parser = argparse.ArgumentParser(prog='myprogram')
503 >>> parser.print_help()
504 usage: myprogram [-h]
505
506 optional arguments:
507 -h, --help show this help message and exit
508
509Note that the program name, whether determined from ``sys.argv[0]`` or from the
510``prog=`` argument, is available to help messages using the ``%(prog)s`` format
511specifier.
512
513::
514
515 >>> parser = argparse.ArgumentParser(prog='myprogram')
516 >>> parser.add_argument('--foo', help='foo of the %(prog)s program')
517 >>> parser.print_help()
518 usage: myprogram [-h] [--foo FOO]
519
520 optional arguments:
521 -h, --help show this help message and exit
522 --foo FOO foo of the myprogram program
523
524
525usage
526^^^^^
527
Benjamin Peterson90c58022010-03-03 01:55:09 +0000528By default, :class:`ArgumentParser` calculates the usage message from the
Benjamin Petersona39e9662010-03-02 22:05:59 +0000529arguments it contains::
530
531 >>> parser = argparse.ArgumentParser(prog='PROG')
532 >>> parser.add_argument('--foo', nargs='?', help='foo help')
533 >>> parser.add_argument('bar', nargs='+', help='bar help')
534 >>> parser.print_help()
535 usage: PROG [-h] [--foo [FOO]] bar [bar ...]
536
537 positional arguments:
538 bar bar help
539
540 optional arguments:
541 -h, --help show this help message and exit
542 --foo [FOO] foo help
543
Benjamin Peterson90c58022010-03-03 01:55:09 +0000544The default message can be overridden with the ``usage=`` keyword argument::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000545
546 >>> parser = argparse.ArgumentParser(prog='PROG', usage='%(prog)s [options]')
547 >>> parser.add_argument('--foo', nargs='?', help='foo help')
548 >>> parser.add_argument('bar', nargs='+', help='bar help')
549 >>> parser.print_help()
550 usage: PROG [options]
551
552 positional arguments:
553 bar bar help
554
555 optional arguments:
556 -h, --help show this help message and exit
557 --foo [FOO] foo help
558
Benjamin Peterson90c58022010-03-03 01:55:09 +0000559The ``%(prog)s`` format specifier is available to fill in the program name in
560your usage messages.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000561
562
563The add_argument() method
564-------------------------
565
Benjamin Peterson90c58022010-03-03 01:55:09 +0000566.. method:: ArgumentParser.add_argument(name or flags..., [action], [nargs], [const], [default], [type], [choices], [required], [help], [metavar], [dest])
Benjamin Petersona39e9662010-03-02 22:05:59 +0000567
Georg Brandld2decd92010-03-02 22:17:38 +0000568 Define how a single command line argument should be parsed. Each parameter
Benjamin Petersona39e9662010-03-02 22:05:59 +0000569 has its own more detailed description below, but in short they are:
570
571 * `name or flags`_ - Either a name or a list of option strings, e.g. ``foo``
572 or ``-f, --foo``
573
574 * action_ - The basic type of action to be taken when this argument is
575 encountered at the command-line.
576
577 * nargs_ - The number of command-line arguments that should be consumed.
578
579 * const_ - A constant value required by some action_ and nargs_ selections.
580
581 * default_ - The value produced if the argument is absent from the
582 command-line.
583
584 * type_ - The type to which the command-line arg should be converted.
585
586 * choices_ - A container of the allowable values for the argument.
587
588 * required_ - Whether or not the command-line option may be omitted
589 (optionals only).
590
591 * help_ - A brief description of what the argument does.
592
593 * metavar_ - A name for the argument in usage messages.
594
595 * dest_ - The name of the attribute to be added to the object returned by
596 :meth:`parse_args`.
597
Benjamin Peterson90c58022010-03-03 01:55:09 +0000598The following sections describe how each of these are used.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000599
Georg Brandlb8d0e362010-11-26 07:53:50 +0000600
Benjamin Petersona39e9662010-03-02 22:05:59 +0000601name or flags
602^^^^^^^^^^^^^
603
Benjamin Peterson90c58022010-03-03 01:55:09 +0000604The :meth:`add_argument` method must know whether an optional argument, like
605``-f`` or ``--foo``, or a positional argument, like a list of filenames, is
606expected. The first arguments passed to :meth:`add_argument` must therefore be
607either a series of flags, or a simple argument name. For example, an optional
608argument could be created like::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000609
610 >>> parser.add_argument('-f', '--foo')
611
612while a positional argument could be created like::
613
614 >>> parser.add_argument('bar')
615
616When :meth:`parse_args` is called, optional arguments will be identified by the
617``-`` prefix, and the remaining arguments will be assumed to be positional::
618
619 >>> parser = argparse.ArgumentParser(prog='PROG')
620 >>> parser.add_argument('-f', '--foo')
621 >>> parser.add_argument('bar')
622 >>> parser.parse_args(['BAR'])
623 Namespace(bar='BAR', foo=None)
624 >>> parser.parse_args(['BAR', '--foo', 'FOO'])
625 Namespace(bar='BAR', foo='FOO')
626 >>> parser.parse_args(['--foo', 'FOO'])
627 usage: PROG [-h] [-f FOO] bar
628 PROG: error: too few arguments
629
Georg Brandlb8d0e362010-11-26 07:53:50 +0000630
Benjamin Petersona39e9662010-03-02 22:05:59 +0000631action
632^^^^^^
633
Georg Brandld2decd92010-03-02 22:17:38 +0000634:class:`ArgumentParser` objects associate command-line args with actions. These
Benjamin Petersona39e9662010-03-02 22:05:59 +0000635actions can do just about anything with the command-line args associated with
636them, though most actions simply add an attribute to the object returned by
Benjamin Peterson90c58022010-03-03 01:55:09 +0000637:meth:`parse_args`. The ``action`` keyword argument specifies how the
638command-line args should be handled. The supported actions are:
Benjamin Petersona39e9662010-03-02 22:05:59 +0000639
Georg Brandld2decd92010-03-02 22:17:38 +0000640* ``'store'`` - This just stores the argument's value. This is the default
Benjamin Petersona39e9662010-03-02 22:05:59 +0000641 action. For example::
642
643 >>> parser = argparse.ArgumentParser()
644 >>> parser.add_argument('--foo')
645 >>> parser.parse_args('--foo 1'.split())
646 Namespace(foo='1')
647
648* ``'store_const'`` - This stores the value specified by the const_ keyword
Benjamin Peterson90c58022010-03-03 01:55:09 +0000649 argument. (Note that the const_ keyword argument defaults to the rather
650 unhelpful ``None``.) The ``'store_const'`` action is most commonly used with
651 optional arguments that specify some sort of flag. For example::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000652
653 >>> parser = argparse.ArgumentParser()
654 >>> parser.add_argument('--foo', action='store_const', const=42)
655 >>> parser.parse_args('--foo'.split())
656 Namespace(foo=42)
657
658* ``'store_true'`` and ``'store_false'`` - These store the values ``True`` and
Benjamin Peterson90c58022010-03-03 01:55:09 +0000659 ``False`` respectively. These are special cases of ``'store_const'``. For
660 example::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000661
662 >>> parser = argparse.ArgumentParser()
663 >>> parser.add_argument('--foo', action='store_true')
664 >>> parser.add_argument('--bar', action='store_false')
665 >>> parser.parse_args('--foo --bar'.split())
666 Namespace(bar=False, foo=True)
667
668* ``'append'`` - This stores a list, and appends each argument value to the
Benjamin Peterson90c58022010-03-03 01:55:09 +0000669 list. This is useful to allow an option to be specified multiple times.
670 Example usage::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000671
672 >>> parser = argparse.ArgumentParser()
673 >>> parser.add_argument('--foo', action='append')
674 >>> parser.parse_args('--foo 1 --foo 2'.split())
675 Namespace(foo=['1', '2'])
676
677* ``'append_const'`` - This stores a list, and appends the value specified by
Benjamin Peterson90c58022010-03-03 01:55:09 +0000678 the const_ keyword argument to the list. (Note that the const_ keyword
679 argument defaults to ``None``.) The ``'append_const'`` action is typically
680 useful when multiple arguments need to store constants to the same list. For
681 example::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000682
683 >>> parser = argparse.ArgumentParser()
684 >>> parser.add_argument('--str', dest='types', action='append_const', const=str)
685 >>> parser.add_argument('--int', dest='types', action='append_const', const=int)
686 >>> parser.parse_args('--str --int'.split())
687 Namespace(types=[<type 'str'>, <type 'int'>])
688
689* ``'version'`` - This expects a ``version=`` keyword argument in the
690 :meth:`add_argument` call, and prints version information and exits when
691 invoked.
692
693 >>> import argparse
694 >>> parser = argparse.ArgumentParser(prog='PROG')
Steven Bethard74bd9cf2010-05-24 02:38:00 +0000695 >>> parser.add_argument('--version', action='version', version='%(prog)s 2.0')
696 >>> parser.parse_args(['--version'])
Benjamin Petersona39e9662010-03-02 22:05:59 +0000697 PROG 2.0
698
699You can also specify an arbitrary action by passing an object that implements
Benjamin Peterson90c58022010-03-03 01:55:09 +0000700the Action API. The easiest way to do this is to extend
701:class:`argparse.Action`, supplying an appropriate ``__call__`` method. The
702``__call__`` method should accept four parameters:
Benjamin Petersona39e9662010-03-02 22:05:59 +0000703
704* ``parser`` - The ArgumentParser object which contains this action.
705
706* ``namespace`` - The namespace object that will be returned by
Georg Brandld2decd92010-03-02 22:17:38 +0000707 :meth:`parse_args`. Most actions add an attribute to this object.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000708
709* ``values`` - The associated command-line args, with any type-conversions
710 applied. (Type-conversions are specified with the type_ keyword argument to
711 :meth:`add_argument`.
712
713* ``option_string`` - The option string that was used to invoke this action.
714 The ``option_string`` argument is optional, and will be absent if the action
715 is associated with a positional argument.
716
Benjamin Peterson90c58022010-03-03 01:55:09 +0000717An example of a custom action::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000718
719 >>> class FooAction(argparse.Action):
720 ... def __call__(self, parser, namespace, values, option_string=None):
Georg Brandl8891e232010-08-01 21:23:50 +0000721 ... print '%r %r %r' % (namespace, values, option_string)
722 ... setattr(namespace, self.dest, values)
Benjamin Petersona39e9662010-03-02 22:05:59 +0000723 ...
724 >>> parser = argparse.ArgumentParser()
725 >>> parser.add_argument('--foo', action=FooAction)
726 >>> parser.add_argument('bar', action=FooAction)
727 >>> args = parser.parse_args('1 --foo 2'.split())
728 Namespace(bar=None, foo=None) '1' None
729 Namespace(bar='1', foo=None) '2' '--foo'
730 >>> args
731 Namespace(bar='1', foo='2')
732
733
734nargs
735^^^^^
736
737ArgumentParser objects usually associate a single command-line argument with a
Benjamin Peterson90c58022010-03-03 01:55:09 +0000738single action to be taken. The ``nargs`` keyword argument associates a
739different number of command-line arguments with a single action.. The supported
740values are:
Benjamin Petersona39e9662010-03-02 22:05:59 +0000741
Georg Brandld2decd92010-03-02 22:17:38 +0000742* N (an integer). N args from the command-line will be gathered together into a
743 list. For example::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000744
Georg Brandl35e7a8f2010-10-06 10:41:31 +0000745 >>> parser = argparse.ArgumentParser()
746 >>> parser.add_argument('--foo', nargs=2)
747 >>> parser.add_argument('bar', nargs=1)
748 >>> parser.parse_args('c --foo a b'.split())
749 Namespace(bar=['c'], foo=['a', 'b'])
Benjamin Petersona39e9662010-03-02 22:05:59 +0000750
Georg Brandl35e7a8f2010-10-06 10:41:31 +0000751 Note that ``nargs=1`` produces a list of one item. This is different from
752 the default, in which the item is produced by itself.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000753
754* ``'?'``. One arg will be consumed from the command-line if possible, and
755 produced as a single item. If no command-line arg is present, the value from
756 default_ will be produced. Note that for optional arguments, there is an
757 additional case - the option string is present but not followed by a
758 command-line arg. In this case the value from const_ will be produced. Some
759 examples to illustrate this::
760
Georg Brandld2decd92010-03-02 22:17:38 +0000761 >>> parser = argparse.ArgumentParser()
762 >>> parser.add_argument('--foo', nargs='?', const='c', default='d')
763 >>> parser.add_argument('bar', nargs='?', default='d')
764 >>> parser.parse_args('XX --foo YY'.split())
765 Namespace(bar='XX', foo='YY')
766 >>> parser.parse_args('XX --foo'.split())
767 Namespace(bar='XX', foo='c')
768 >>> parser.parse_args(''.split())
769 Namespace(bar='d', foo='d')
Benjamin Petersona39e9662010-03-02 22:05:59 +0000770
Georg Brandld2decd92010-03-02 22:17:38 +0000771 One of the more common uses of ``nargs='?'`` is to allow optional input and
772 output files::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000773
Georg Brandld2decd92010-03-02 22:17:38 +0000774 >>> parser = argparse.ArgumentParser()
Georg Brandlb8d0e362010-11-26 07:53:50 +0000775 >>> parser.add_argument('infile', nargs='?', type=argparse.FileType('r'),
776 ... default=sys.stdin)
777 >>> parser.add_argument('outfile', nargs='?', type=argparse.FileType('w'),
778 ... default=sys.stdout)
Georg Brandld2decd92010-03-02 22:17:38 +0000779 >>> parser.parse_args(['input.txt', 'output.txt'])
780 Namespace(infile=<open file 'input.txt', mode 'r' at 0x...>, outfile=<open file 'output.txt', mode 'w' at 0x...>)
781 >>> parser.parse_args([])
782 Namespace(infile=<open file '<stdin>', mode 'r' at 0x...>, outfile=<open file '<stdout>', mode 'w' at 0x...>)
Benjamin Petersona39e9662010-03-02 22:05:59 +0000783
Georg Brandld2decd92010-03-02 22:17:38 +0000784* ``'*'``. All command-line args present are gathered into a list. Note that
785 it generally doesn't make much sense to have more than one positional argument
786 with ``nargs='*'``, but multiple optional arguments with ``nargs='*'`` is
787 possible. For example::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000788
Georg Brandld2decd92010-03-02 22:17:38 +0000789 >>> parser = argparse.ArgumentParser()
790 >>> parser.add_argument('--foo', nargs='*')
791 >>> parser.add_argument('--bar', nargs='*')
792 >>> parser.add_argument('baz', nargs='*')
793 >>> parser.parse_args('a b --foo x y --bar 1 2'.split())
794 Namespace(bar=['1', '2'], baz=['a', 'b'], foo=['x', 'y'])
Benjamin Petersona39e9662010-03-02 22:05:59 +0000795
796* ``'+'``. Just like ``'*'``, all command-line args present are gathered into a
797 list. Additionally, an error message will be generated if there wasn't at
798 least one command-line arg present. For example::
799
Georg Brandld2decd92010-03-02 22:17:38 +0000800 >>> parser = argparse.ArgumentParser(prog='PROG')
801 >>> parser.add_argument('foo', nargs='+')
802 >>> parser.parse_args('a b'.split())
803 Namespace(foo=['a', 'b'])
804 >>> parser.parse_args(''.split())
805 usage: PROG [-h] foo [foo ...]
806 PROG: error: too few arguments
Benjamin Petersona39e9662010-03-02 22:05:59 +0000807
808If the ``nargs`` keyword argument is not provided, the number of args consumed
Georg Brandld2decd92010-03-02 22:17:38 +0000809is determined by the action_. Generally this means a single command-line arg
Benjamin Petersona39e9662010-03-02 22:05:59 +0000810will be consumed and a single item (not a list) will be produced.
811
812
813const
814^^^^^
815
816The ``const`` argument of :meth:`add_argument` is used to hold constant values
817that are not read from the command line but are required for the various
818ArgumentParser actions. The two most common uses of it are:
819
820* When :meth:`add_argument` is called with ``action='store_const'`` or
821 ``action='append_const'``. These actions add the ``const`` value to one of
822 the attributes of the object returned by :meth:`parse_args`. See the action_
823 description for examples.
824
825* When :meth:`add_argument` is called with option strings (like ``-f`` or
Georg Brandld2decd92010-03-02 22:17:38 +0000826 ``--foo``) and ``nargs='?'``. This creates an optional argument that can be
Benjamin Petersona39e9662010-03-02 22:05:59 +0000827 followed by zero or one command-line args. When parsing the command-line, if
828 the option string is encountered with no command-line arg following it, the
829 value of ``const`` will be assumed instead. See the nargs_ description for
830 examples.
831
832The ``const`` keyword argument defaults to ``None``.
833
834
835default
836^^^^^^^
837
838All optional arguments and some positional arguments may be omitted at the
839command-line. The ``default`` keyword argument of :meth:`add_argument`, whose
840value defaults to ``None``, specifies what value should be used if the
841command-line arg is not present. For optional arguments, the ``default`` value
842is used when the option string was not present at the command line::
843
844 >>> parser = argparse.ArgumentParser()
845 >>> parser.add_argument('--foo', default=42)
846 >>> parser.parse_args('--foo 2'.split())
847 Namespace(foo='2')
848 >>> parser.parse_args(''.split())
849 Namespace(foo=42)
850
851For positional arguments with nargs_ ``='?'`` or ``'*'``, the ``default`` value
852is used when no command-line arg was present::
853
854 >>> parser = argparse.ArgumentParser()
855 >>> parser.add_argument('foo', nargs='?', default=42)
856 >>> parser.parse_args('a'.split())
857 Namespace(foo='a')
858 >>> parser.parse_args(''.split())
859 Namespace(foo=42)
860
861
Benjamin Peterson90c58022010-03-03 01:55:09 +0000862Providing ``default=argparse.SUPPRESS`` causes no attribute to be added if the
863command-line argument was not present.::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000864
865 >>> parser = argparse.ArgumentParser()
866 >>> parser.add_argument('--foo', default=argparse.SUPPRESS)
867 >>> parser.parse_args([])
868 Namespace()
869 >>> parser.parse_args(['--foo', '1'])
870 Namespace(foo='1')
871
872
873type
874^^^^
875
876By default, ArgumentParser objects read command-line args in as simple strings.
877However, quite often the command-line string should instead be interpreted as
Benjamin Peterson90c58022010-03-03 01:55:09 +0000878another type, like a :class:`float`, :class:`int` or :class:`file`. The
879``type`` keyword argument of :meth:`add_argument` allows any necessary
Georg Brandl21e99f42010-03-07 15:23:59 +0000880type-checking and type-conversions to be performed. Many common built-in types
Benjamin Peterson90c58022010-03-03 01:55:09 +0000881can be used directly as the value of the ``type`` argument::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000882
883 >>> parser = argparse.ArgumentParser()
884 >>> parser.add_argument('foo', type=int)
885 >>> parser.add_argument('bar', type=file)
886 >>> parser.parse_args('2 temp.txt'.split())
887 Namespace(bar=<open file 'temp.txt', mode 'r' at 0x...>, foo=2)
888
889To ease the use of various types of files, the argparse module provides the
890factory FileType which takes the ``mode=`` and ``bufsize=`` arguments of the
Georg Brandld2decd92010-03-02 22:17:38 +0000891``file`` object. For example, ``FileType('w')`` can be used to create a
Benjamin Petersona39e9662010-03-02 22:05:59 +0000892writable file::
893
894 >>> parser = argparse.ArgumentParser()
895 >>> parser.add_argument('bar', type=argparse.FileType('w'))
896 >>> parser.parse_args(['out.txt'])
897 Namespace(bar=<open file 'out.txt', mode 'w' at 0x...>)
898
Benjamin Peterson90c58022010-03-03 01:55:09 +0000899``type=`` can take any callable that takes a single string argument and returns
900the type-converted value::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000901
902 >>> def perfect_square(string):
903 ... value = int(string)
904 ... sqrt = math.sqrt(value)
905 ... if sqrt != int(sqrt):
906 ... msg = "%r is not a perfect square" % string
907 ... raise argparse.ArgumentTypeError(msg)
908 ... return value
909 ...
910 >>> parser = argparse.ArgumentParser(prog='PROG')
911 >>> parser.add_argument('foo', type=perfect_square)
912 >>> parser.parse_args('9'.split())
913 Namespace(foo=9)
914 >>> parser.parse_args('7'.split())
915 usage: PROG [-h] foo
916 PROG: error: argument foo: '7' is not a perfect square
917
Benjamin Peterson90c58022010-03-03 01:55:09 +0000918The choices_ keyword argument may be more convenient for type checkers that
919simply check against a range of values::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000920
921 >>> parser = argparse.ArgumentParser(prog='PROG')
922 >>> parser.add_argument('foo', type=int, choices=xrange(5, 10))
923 >>> parser.parse_args('7'.split())
924 Namespace(foo=7)
925 >>> parser.parse_args('11'.split())
926 usage: PROG [-h] {5,6,7,8,9}
927 PROG: error: argument foo: invalid choice: 11 (choose from 5, 6, 7, 8, 9)
928
929See the choices_ section for more details.
930
931
932choices
933^^^^^^^
934
935Some command-line args should be selected from a restricted set of values.
Benjamin Peterson90c58022010-03-03 01:55:09 +0000936These can be handled by passing a container object as the ``choices`` keyword
937argument to :meth:`add_argument`. When the command-line is parsed, arg values
938will be checked, and an error message will be displayed if the arg was not one
939of the acceptable values::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000940
941 >>> parser = argparse.ArgumentParser(prog='PROG')
942 >>> parser.add_argument('foo', choices='abc')
943 >>> parser.parse_args('c'.split())
944 Namespace(foo='c')
945 >>> parser.parse_args('X'.split())
946 usage: PROG [-h] {a,b,c}
947 PROG: error: argument foo: invalid choice: 'X' (choose from 'a', 'b', 'c')
948
949Note that inclusion in the ``choices`` container is checked after any type_
950conversions have been performed, so the type of the objects in the ``choices``
951container should match the type_ specified::
952
953 >>> parser = argparse.ArgumentParser(prog='PROG')
954 >>> parser.add_argument('foo', type=complex, choices=[1, 1j])
955 >>> parser.parse_args('1j'.split())
956 Namespace(foo=1j)
957 >>> parser.parse_args('-- -4'.split())
958 usage: PROG [-h] {1,1j}
959 PROG: error: argument foo: invalid choice: (-4+0j) (choose from 1, 1j)
960
961Any object that supports the ``in`` operator can be passed as the ``choices``
Georg Brandld2decd92010-03-02 22:17:38 +0000962value, so :class:`dict` objects, :class:`set` objects, custom containers,
963etc. are all supported.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000964
965
966required
967^^^^^^^^
968
969In general, the argparse module assumes that flags like ``-f`` and ``--bar``
970indicate *optional* arguments, which can always be omitted at the command-line.
Benjamin Peterson90c58022010-03-03 01:55:09 +0000971To make an option *required*, ``True`` can be specified for the ``required=``
972keyword argument to :meth:`add_argument`::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000973
974 >>> parser = argparse.ArgumentParser()
975 >>> parser.add_argument('--foo', required=True)
976 >>> parser.parse_args(['--foo', 'BAR'])
977 Namespace(foo='BAR')
978 >>> parser.parse_args([])
979 usage: argparse.py [-h] [--foo FOO]
980 argparse.py: error: option --foo is required
981
982As the example shows, if an option is marked as ``required``, :meth:`parse_args`
983will report an error if that option is not present at the command line.
984
Benjamin Peterson90c58022010-03-03 01:55:09 +0000985.. note::
986
987 Required options are generally considered bad form because users expect
988 *options* to be *optional*, and thus they should be avoided when possible.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000989
990
991help
992^^^^
993
Benjamin Peterson90c58022010-03-03 01:55:09 +0000994The ``help`` value is a string containing a brief description of the argument.
995When a user requests help (usually by using ``-h`` or ``--help`` at the
996command-line), these ``help`` descriptions will be displayed with each
Georg Brandld2decd92010-03-02 22:17:38 +0000997argument::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000998
999 >>> parser = argparse.ArgumentParser(prog='frobble')
1000 >>> parser.add_argument('--foo', action='store_true',
1001 ... help='foo the bars before frobbling')
1002 >>> parser.add_argument('bar', nargs='+',
1003 ... help='one of the bars to be frobbled')
1004 >>> parser.parse_args('-h'.split())
1005 usage: frobble [-h] [--foo] bar [bar ...]
1006
1007 positional arguments:
1008 bar one of the bars to be frobbled
1009
1010 optional arguments:
1011 -h, --help show this help message and exit
1012 --foo foo the bars before frobbling
1013
1014The ``help`` strings can include various format specifiers to avoid repetition
1015of things like the program name or the argument default_. The available
1016specifiers include the program name, ``%(prog)s`` and most keyword arguments to
1017:meth:`add_argument`, e.g. ``%(default)s``, ``%(type)s``, etc.::
1018
1019 >>> parser = argparse.ArgumentParser(prog='frobble')
1020 >>> parser.add_argument('bar', nargs='?', type=int, default=42,
1021 ... help='the bar to %(prog)s (default: %(default)s)')
1022 >>> parser.print_help()
1023 usage: frobble [-h] [bar]
1024
1025 positional arguments:
1026 bar the bar to frobble (default: 42)
1027
1028 optional arguments:
1029 -h, --help show this help message and exit
1030
1031
1032metavar
1033^^^^^^^
1034
Benjamin Peterson90c58022010-03-03 01:55:09 +00001035When :class:`ArgumentParser` generates help messages, it need some way to refer
Georg Brandld2decd92010-03-02 22:17:38 +00001036to each expected argument. By default, ArgumentParser objects use the dest_
Benjamin Petersona39e9662010-03-02 22:05:59 +00001037value as the "name" of each object. By default, for positional argument
1038actions, the dest_ value is used directly, and for optional argument actions,
Benjamin Peterson90c58022010-03-03 01:55:09 +00001039the dest_ value is uppercased. So, a single positional argument with
1040``dest='bar'`` will that argument will be referred to as ``bar``. A single
1041optional argument ``--foo`` that should be followed by a single command-line arg
1042will be referred to as ``FOO``. An example::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001043
1044 >>> parser = argparse.ArgumentParser()
1045 >>> parser.add_argument('--foo')
1046 >>> parser.add_argument('bar')
1047 >>> parser.parse_args('X --foo Y'.split())
1048 Namespace(bar='X', foo='Y')
1049 >>> parser.print_help()
1050 usage: [-h] [--foo FOO] bar
1051
1052 positional arguments:
1053 bar
1054
1055 optional arguments:
1056 -h, --help show this help message and exit
1057 --foo FOO
1058
Benjamin Peterson90c58022010-03-03 01:55:09 +00001059An alternative name can be specified with ``metavar``::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001060
1061 >>> parser = argparse.ArgumentParser()
1062 >>> parser.add_argument('--foo', metavar='YYY')
1063 >>> parser.add_argument('bar', metavar='XXX')
1064 >>> parser.parse_args('X --foo Y'.split())
1065 Namespace(bar='X', foo='Y')
1066 >>> parser.print_help()
1067 usage: [-h] [--foo YYY] XXX
1068
1069 positional arguments:
1070 XXX
1071
1072 optional arguments:
1073 -h, --help show this help message and exit
1074 --foo YYY
1075
1076Note that ``metavar`` only changes the *displayed* name - the name of the
1077attribute on the :meth:`parse_args` object is still determined by the dest_
1078value.
1079
1080Different values of ``nargs`` may cause the metavar to be used multiple times.
Benjamin Peterson90c58022010-03-03 01:55:09 +00001081Providing a tuple to ``metavar`` specifies a different display for each of the
1082arguments::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001083
1084 >>> parser = argparse.ArgumentParser(prog='PROG')
1085 >>> parser.add_argument('-x', nargs=2)
1086 >>> parser.add_argument('--foo', nargs=2, metavar=('bar', 'baz'))
1087 >>> parser.print_help()
1088 usage: PROG [-h] [-x X X] [--foo bar baz]
1089
1090 optional arguments:
1091 -h, --help show this help message and exit
1092 -x X X
1093 --foo bar baz
1094
1095
1096dest
1097^^^^
1098
Benjamin Peterson90c58022010-03-03 01:55:09 +00001099Most :class:`ArgumentParser` actions add some value as an attribute of the
1100object returned by :meth:`parse_args`. The name of this attribute is determined
1101by the ``dest`` keyword argument of :meth:`add_argument`. For positional
1102argument actions, ``dest`` is normally supplied as the first argument to
Benjamin Petersona39e9662010-03-02 22:05:59 +00001103:meth:`add_argument`::
1104
1105 >>> parser = argparse.ArgumentParser()
1106 >>> parser.add_argument('bar')
1107 >>> parser.parse_args('XXX'.split())
1108 Namespace(bar='XXX')
1109
1110For optional argument actions, the value of ``dest`` is normally inferred from
Benjamin Peterson90c58022010-03-03 01:55:09 +00001111the option strings. :class:`ArgumentParser` generates the value of ``dest`` by
Benjamin Petersona39e9662010-03-02 22:05:59 +00001112taking the first long option string and stripping away the initial ``'--'``
1113string. If no long option strings were supplied, ``dest`` will be derived from
1114the first short option string by stripping the initial ``'-'`` character. Any
Georg Brandld2decd92010-03-02 22:17:38 +00001115internal ``'-'`` characters will be converted to ``'_'`` characters to make sure
1116the string is a valid attribute name. The examples below illustrate this
Benjamin Petersona39e9662010-03-02 22:05:59 +00001117behavior::
1118
1119 >>> parser = argparse.ArgumentParser()
1120 >>> parser.add_argument('-f', '--foo-bar', '--foo')
1121 >>> parser.add_argument('-x', '-y')
1122 >>> parser.parse_args('-f 1 -x 2'.split())
1123 Namespace(foo_bar='1', x='2')
1124 >>> parser.parse_args('--foo 1 -y 2'.split())
1125 Namespace(foo_bar='1', x='2')
1126
Benjamin Peterson90c58022010-03-03 01:55:09 +00001127``dest`` allows a custom attribute name to be provided::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001128
1129 >>> parser = argparse.ArgumentParser()
1130 >>> parser.add_argument('--foo', dest='bar')
1131 >>> parser.parse_args('--foo XXX'.split())
1132 Namespace(bar='XXX')
1133
1134
1135The parse_args() method
1136-----------------------
1137
Georg Brandlb8d0e362010-11-26 07:53:50 +00001138.. method:: ArgumentParser.parse_args(args=None, namespace=None)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001139
Benjamin Peterson90c58022010-03-03 01:55:09 +00001140 Convert argument strings to objects and assign them as attributes of the
Georg Brandld2decd92010-03-02 22:17:38 +00001141 namespace. Return the populated namespace.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001142
1143 Previous calls to :meth:`add_argument` determine exactly what objects are
1144 created and how they are assigned. See the documentation for
1145 :meth:`add_argument` for details.
1146
Georg Brandld2decd92010-03-02 22:17:38 +00001147 By default, the arg strings are taken from :data:`sys.argv`, and a new empty
Benjamin Peterson90c58022010-03-03 01:55:09 +00001148 :class:`Namespace` object is created for the attributes.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001149
Georg Brandlb8d0e362010-11-26 07:53:50 +00001150
Benjamin Petersona39e9662010-03-02 22:05:59 +00001151Option value syntax
1152^^^^^^^^^^^^^^^^^^^
1153
1154The :meth:`parse_args` method supports several ways of specifying the value of
Georg Brandld2decd92010-03-02 22:17:38 +00001155an option (if it takes one). In the simplest case, the option and its value are
Benjamin Petersona39e9662010-03-02 22:05:59 +00001156passed as two separate arguments::
1157
1158 >>> parser = argparse.ArgumentParser(prog='PROG')
1159 >>> parser.add_argument('-x')
1160 >>> parser.add_argument('--foo')
1161 >>> parser.parse_args('-x X'.split())
1162 Namespace(foo=None, x='X')
1163 >>> parser.parse_args('--foo FOO'.split())
1164 Namespace(foo='FOO', x=None)
1165
Benjamin Peterson90c58022010-03-03 01:55:09 +00001166For long options (options with names longer than a single character), the option
1167and value can also be passed as a single command line argument, using ``=`` to
Georg Brandld2decd92010-03-02 22:17:38 +00001168separate them::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001169
1170 >>> parser.parse_args('--foo=FOO'.split())
1171 Namespace(foo='FOO', x=None)
1172
Benjamin Peterson90c58022010-03-03 01:55:09 +00001173For short options (options only one character long), the option and its value
1174can be concatenated::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001175
1176 >>> parser.parse_args('-xX'.split())
1177 Namespace(foo=None, x='X')
1178
Benjamin Peterson90c58022010-03-03 01:55:09 +00001179Several short options can be joined together, using only a single ``-`` prefix,
1180as long as only the last option (or none of them) requires a value::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001181
1182 >>> parser = argparse.ArgumentParser(prog='PROG')
1183 >>> parser.add_argument('-x', action='store_true')
1184 >>> parser.add_argument('-y', action='store_true')
1185 >>> parser.add_argument('-z')
1186 >>> parser.parse_args('-xyzZ'.split())
1187 Namespace(x=True, y=True, z='Z')
1188
1189
1190Invalid arguments
1191^^^^^^^^^^^^^^^^^
1192
1193While parsing the command-line, ``parse_args`` checks for a variety of errors,
1194including ambiguous options, invalid types, invalid options, wrong number of
Georg Brandld2decd92010-03-02 22:17:38 +00001195positional arguments, etc. When it encounters such an error, it exits and
Benjamin Petersona39e9662010-03-02 22:05:59 +00001196prints the error along with a usage message::
1197
1198 >>> parser = argparse.ArgumentParser(prog='PROG')
1199 >>> parser.add_argument('--foo', type=int)
1200 >>> parser.add_argument('bar', nargs='?')
1201
1202 >>> # invalid type
1203 >>> parser.parse_args(['--foo', 'spam'])
1204 usage: PROG [-h] [--foo FOO] [bar]
1205 PROG: error: argument --foo: invalid int value: 'spam'
1206
1207 >>> # invalid option
1208 >>> parser.parse_args(['--bar'])
1209 usage: PROG [-h] [--foo FOO] [bar]
1210 PROG: error: no such option: --bar
1211
1212 >>> # wrong number of arguments
1213 >>> parser.parse_args(['spam', 'badger'])
1214 usage: PROG [-h] [--foo FOO] [bar]
1215 PROG: error: extra arguments found: badger
1216
1217
1218Arguments containing ``"-"``
1219^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1220
1221The ``parse_args`` method attempts to give errors whenever the user has clearly
Georg Brandld2decd92010-03-02 22:17:38 +00001222made a mistake, but some situations are inherently ambiguous. For example, the
Benjamin Petersona39e9662010-03-02 22:05:59 +00001223command-line arg ``'-1'`` could either be an attempt to specify an option or an
Georg Brandld2decd92010-03-02 22:17:38 +00001224attempt to provide a positional argument. The ``parse_args`` method is cautious
Benjamin Petersona39e9662010-03-02 22:05:59 +00001225here: positional arguments may only begin with ``'-'`` if they look like
1226negative numbers and there are no options in the parser that look like negative
1227numbers::
1228
1229 >>> parser = argparse.ArgumentParser(prog='PROG')
1230 >>> parser.add_argument('-x')
1231 >>> parser.add_argument('foo', nargs='?')
1232
1233 >>> # no negative number options, so -1 is a positional argument
1234 >>> parser.parse_args(['-x', '-1'])
1235 Namespace(foo=None, x='-1')
1236
1237 >>> # no negative number options, so -1 and -5 are positional arguments
1238 >>> parser.parse_args(['-x', '-1', '-5'])
1239 Namespace(foo='-5', x='-1')
1240
1241 >>> parser = argparse.ArgumentParser(prog='PROG')
1242 >>> parser.add_argument('-1', dest='one')
1243 >>> parser.add_argument('foo', nargs='?')
1244
1245 >>> # negative number options present, so -1 is an option
1246 >>> parser.parse_args(['-1', 'X'])
1247 Namespace(foo=None, one='X')
1248
1249 >>> # negative number options present, so -2 is an option
1250 >>> parser.parse_args(['-2'])
1251 usage: PROG [-h] [-1 ONE] [foo]
1252 PROG: error: no such option: -2
1253
1254 >>> # negative number options present, so both -1s are options
1255 >>> parser.parse_args(['-1', '-1'])
1256 usage: PROG [-h] [-1 ONE] [foo]
1257 PROG: error: argument -1: expected one argument
1258
1259If you have positional arguments that must begin with ``'-'`` and don't look
1260like negative numbers, you can insert the pseudo-argument ``'--'`` which tells
1261``parse_args`` that everything after that is a positional argument::
1262
1263 >>> parser.parse_args(['--', '-f'])
1264 Namespace(foo='-f', one=None)
1265
1266
1267Argument abbreviations
1268^^^^^^^^^^^^^^^^^^^^^^
1269
Benjamin Peterson90c58022010-03-03 01:55:09 +00001270The :meth:`parse_args` method allows long options to be abbreviated if the
Benjamin Petersona39e9662010-03-02 22:05:59 +00001271abbreviation is unambiguous::
1272
1273 >>> parser = argparse.ArgumentParser(prog='PROG')
1274 >>> parser.add_argument('-bacon')
1275 >>> parser.add_argument('-badger')
1276 >>> parser.parse_args('-bac MMM'.split())
1277 Namespace(bacon='MMM', badger=None)
1278 >>> parser.parse_args('-bad WOOD'.split())
1279 Namespace(bacon=None, badger='WOOD')
1280 >>> parser.parse_args('-ba BA'.split())
1281 usage: PROG [-h] [-bacon BACON] [-badger BADGER]
1282 PROG: error: ambiguous option: -ba could match -badger, -bacon
1283
Benjamin Peterson90c58022010-03-03 01:55:09 +00001284An error is produced for arguments that could produce more than one options.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001285
1286
1287Beyond ``sys.argv``
1288^^^^^^^^^^^^^^^^^^^
1289
Georg Brandld2decd92010-03-02 22:17:38 +00001290Sometimes it may be useful to have an ArgumentParser parse args other than those
1291of :data:`sys.argv`. This can be accomplished by passing a list of strings to
Benjamin Peterson90c58022010-03-03 01:55:09 +00001292``parse_args``. This is useful for testing at the interactive prompt::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001293
1294 >>> parser = argparse.ArgumentParser()
1295 >>> parser.add_argument(
1296 ... 'integers', metavar='int', type=int, choices=xrange(10),
1297 ... nargs='+', help='an integer in the range 0..9')
1298 >>> parser.add_argument(
1299 ... '--sum', dest='accumulate', action='store_const', const=sum,
1300 ... default=max, help='sum the integers (default: find the max)')
1301 >>> parser.parse_args(['1', '2', '3', '4'])
1302 Namespace(accumulate=<built-in function max>, integers=[1, 2, 3, 4])
1303 >>> parser.parse_args('1 2 3 4 --sum'.split())
1304 Namespace(accumulate=<built-in function sum>, integers=[1, 2, 3, 4])
1305
1306
1307Custom namespaces
1308^^^^^^^^^^^^^^^^^
1309
Benjamin Peterson90c58022010-03-03 01:55:09 +00001310It may also be useful to have an :class:`ArgumentParser` assign attributes to an
1311already existing object, rather than the newly-created :class:`Namespace` object
1312that is normally used. This can be achieved by specifying the ``namespace=``
1313keyword argument::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001314
1315 >>> class C(object):
1316 ... pass
1317 ...
1318 >>> c = C()
1319 >>> parser = argparse.ArgumentParser()
1320 >>> parser.add_argument('--foo')
1321 >>> parser.parse_args(args=['--foo', 'BAR'], namespace=c)
1322 >>> c.foo
1323 'BAR'
1324
1325
1326Other utilities
1327---------------
1328
1329Sub-commands
1330^^^^^^^^^^^^
1331
Benjamin Peterson90c58022010-03-03 01:55:09 +00001332.. method:: ArgumentParser.add_subparsers()
Benjamin Petersona39e9662010-03-02 22:05:59 +00001333
Benjamin Peterson90c58022010-03-03 01:55:09 +00001334 Many programs split up their functionality into a number of sub-commands,
Georg Brandld2decd92010-03-02 22:17:38 +00001335 for example, the ``svn`` program can invoke sub-commands like ``svn
Benjamin Peterson90c58022010-03-03 01:55:09 +00001336 checkout``, ``svn update``, and ``svn commit``. Splitting up functionality
Georg Brandld2decd92010-03-02 22:17:38 +00001337 this way can be a particularly good idea when a program performs several
1338 different functions which require different kinds of command-line arguments.
Benjamin Peterson90c58022010-03-03 01:55:09 +00001339 :class:`ArgumentParser` supports the creation of such sub-commands with the
Georg Brandld2decd92010-03-02 22:17:38 +00001340 :meth:`add_subparsers` method. The :meth:`add_subparsers` method is normally
1341 called with no arguments and returns an special action object. This object
1342 has a single method, ``add_parser``, which takes a command name and any
Benjamin Peterson90c58022010-03-03 01:55:09 +00001343 :class:`ArgumentParser` constructor arguments, and returns an
1344 :class:`ArgumentParser` object that can be modified as usual.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001345
1346 Some example usage::
1347
1348 >>> # create the top-level parser
1349 >>> parser = argparse.ArgumentParser(prog='PROG')
1350 >>> parser.add_argument('--foo', action='store_true', help='foo help')
1351 >>> subparsers = parser.add_subparsers(help='sub-command help')
1352 >>>
1353 >>> # create the parser for the "a" command
1354 >>> parser_a = subparsers.add_parser('a', help='a help')
1355 >>> parser_a.add_argument('bar', type=int, help='bar help')
1356 >>>
1357 >>> # create the parser for the "b" command
1358 >>> parser_b = subparsers.add_parser('b', help='b help')
1359 >>> parser_b.add_argument('--baz', choices='XYZ', help='baz help')
1360 >>>
1361 >>> # parse some arg lists
1362 >>> parser.parse_args(['a', '12'])
1363 Namespace(bar=12, foo=False)
1364 >>> parser.parse_args(['--foo', 'b', '--baz', 'Z'])
1365 Namespace(baz='Z', foo=True)
1366
1367 Note that the object returned by :meth:`parse_args` will only contain
1368 attributes for the main parser and the subparser that was selected by the
1369 command line (and not any other subparsers). So in the example above, when
Georg Brandld2decd92010-03-02 22:17:38 +00001370 the ``"a"`` command is specified, only the ``foo`` and ``bar`` attributes are
1371 present, and when the ``"b"`` command is specified, only the ``foo`` and
Benjamin Petersona39e9662010-03-02 22:05:59 +00001372 ``baz`` attributes are present.
1373
1374 Similarly, when a help message is requested from a subparser, only the help
Georg Brandld2decd92010-03-02 22:17:38 +00001375 for that particular parser will be printed. The help message will not
Benjamin Peterson90c58022010-03-03 01:55:09 +00001376 include parent parser or sibling parser messages. (A help message for each
1377 subparser command, however, can be given by supplying the ``help=`` argument
1378 to ``add_parser`` as above.)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001379
1380 ::
1381
1382 >>> parser.parse_args(['--help'])
1383 usage: PROG [-h] [--foo] {a,b} ...
1384
1385 positional arguments:
1386 {a,b} sub-command help
1387 a a help
1388 b b help
1389
1390 optional arguments:
1391 -h, --help show this help message and exit
1392 --foo foo help
1393
1394 >>> parser.parse_args(['a', '--help'])
1395 usage: PROG a [-h] bar
1396
1397 positional arguments:
1398 bar bar help
1399
1400 optional arguments:
1401 -h, --help show this help message and exit
1402
1403 >>> parser.parse_args(['b', '--help'])
1404 usage: PROG b [-h] [--baz {X,Y,Z}]
1405
1406 optional arguments:
1407 -h, --help show this help message and exit
1408 --baz {X,Y,Z} baz help
1409
Georg Brandld2decd92010-03-02 22:17:38 +00001410 The :meth:`add_subparsers` method also supports ``title`` and ``description``
1411 keyword arguments. When either is present, the subparser's commands will
1412 appear in their own group in the help output. For example::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001413
1414 >>> parser = argparse.ArgumentParser()
1415 >>> subparsers = parser.add_subparsers(title='subcommands',
1416 ... description='valid subcommands',
1417 ... help='additional help')
1418 >>> subparsers.add_parser('foo')
1419 >>> subparsers.add_parser('bar')
1420 >>> parser.parse_args(['-h'])
1421 usage: [-h] {foo,bar} ...
1422
1423 optional arguments:
1424 -h, --help show this help message and exit
1425
1426 subcommands:
1427 valid subcommands
1428
1429 {foo,bar} additional help
1430
1431
Georg Brandld2decd92010-03-02 22:17:38 +00001432 One particularly effective way of handling sub-commands is to combine the use
1433 of the :meth:`add_subparsers` method with calls to :meth:`set_defaults` so
1434 that each subparser knows which Python function it should execute. For
Benjamin Petersona39e9662010-03-02 22:05:59 +00001435 example::
1436
1437 >>> # sub-command functions
1438 >>> def foo(args):
1439 ... print args.x * args.y
1440 ...
1441 >>> def bar(args):
1442 ... print '((%s))' % args.z
1443 ...
1444 >>> # create the top-level parser
1445 >>> parser = argparse.ArgumentParser()
1446 >>> subparsers = parser.add_subparsers()
1447 >>>
1448 >>> # create the parser for the "foo" command
1449 >>> parser_foo = subparsers.add_parser('foo')
1450 >>> parser_foo.add_argument('-x', type=int, default=1)
1451 >>> parser_foo.add_argument('y', type=float)
1452 >>> parser_foo.set_defaults(func=foo)
1453 >>>
1454 >>> # create the parser for the "bar" command
1455 >>> parser_bar = subparsers.add_parser('bar')
1456 >>> parser_bar.add_argument('z')
1457 >>> parser_bar.set_defaults(func=bar)
1458 >>>
1459 >>> # parse the args and call whatever function was selected
1460 >>> args = parser.parse_args('foo 1 -x 2'.split())
1461 >>> args.func(args)
1462 2.0
1463 >>>
1464 >>> # parse the args and call whatever function was selected
1465 >>> args = parser.parse_args('bar XYZYX'.split())
1466 >>> args.func(args)
1467 ((XYZYX))
1468
Benjamin Peterson90c58022010-03-03 01:55:09 +00001469 This way, you can let :meth:`parse_args` does the job of calling the
1470 appropriate function after argument parsing is complete. Associating
1471 functions with actions like this is typically the easiest way to handle the
1472 different actions for each of your subparsers. However, if it is necessary
1473 to check the name of the subparser that was invoked, the ``dest`` keyword
1474 argument to the :meth:`add_subparsers` call will work::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001475
1476 >>> parser = argparse.ArgumentParser()
1477 >>> subparsers = parser.add_subparsers(dest='subparser_name')
1478 >>> subparser1 = subparsers.add_parser('1')
1479 >>> subparser1.add_argument('-x')
1480 >>> subparser2 = subparsers.add_parser('2')
1481 >>> subparser2.add_argument('y')
1482 >>> parser.parse_args(['2', 'frobble'])
1483 Namespace(subparser_name='2', y='frobble')
1484
1485
1486FileType objects
1487^^^^^^^^^^^^^^^^
1488
1489.. class:: FileType(mode='r', bufsize=None)
1490
1491 The :class:`FileType` factory creates objects that can be passed to the type
Benjamin Peterson90c58022010-03-03 01:55:09 +00001492 argument of :meth:`ArgumentParser.add_argument`. Arguments that have
1493 :class:`FileType` objects as their type will open command-line args as files
1494 with the requested modes and buffer sizes:
Benjamin Petersona39e9662010-03-02 22:05:59 +00001495
1496 >>> parser = argparse.ArgumentParser()
1497 >>> parser.add_argument('--output', type=argparse.FileType('wb', 0))
1498 >>> parser.parse_args(['--output', 'out'])
1499 Namespace(output=<open file 'out', mode 'wb' at 0x...>)
1500
1501 FileType objects understand the pseudo-argument ``'-'`` and automatically
1502 convert this into ``sys.stdin`` for readable :class:`FileType` objects and
1503 ``sys.stdout`` for writable :class:`FileType` objects:
1504
1505 >>> parser = argparse.ArgumentParser()
1506 >>> parser.add_argument('infile', type=argparse.FileType('r'))
1507 >>> parser.parse_args(['-'])
1508 Namespace(infile=<open file '<stdin>', mode 'r' at 0x...>)
1509
1510
1511Argument groups
1512^^^^^^^^^^^^^^^
1513
Georg Brandlb8d0e362010-11-26 07:53:50 +00001514.. method:: ArgumentParser.add_argument_group(title=None, description=None)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001515
Benjamin Peterson90c58022010-03-03 01:55:09 +00001516 By default, :class:`ArgumentParser` groups command-line arguments into
Benjamin Petersona39e9662010-03-02 22:05:59 +00001517 "positional arguments" and "optional arguments" when displaying help
1518 messages. When there is a better conceptual grouping of arguments than this
1519 default one, appropriate groups can be created using the
1520 :meth:`add_argument_group` method::
1521
1522 >>> parser = argparse.ArgumentParser(prog='PROG', add_help=False)
1523 >>> group = parser.add_argument_group('group')
1524 >>> group.add_argument('--foo', help='foo help')
1525 >>> group.add_argument('bar', help='bar help')
1526 >>> parser.print_help()
1527 usage: PROG [--foo FOO] bar
1528
1529 group:
1530 bar bar help
1531 --foo FOO foo help
1532
1533 The :meth:`add_argument_group` method returns an argument group object which
Benjamin Peterson90c58022010-03-03 01:55:09 +00001534 has an :meth:`~ArgumentParser.add_argument` method just like a regular
1535 :class:`ArgumentParser`. When an argument is added to the group, the parser
1536 treats it just like a normal argument, but displays the argument in a
1537 separate group for help messages. The :meth:`add_argument_group` method
Georg Brandlb8d0e362010-11-26 07:53:50 +00001538 accepts *title* and *description* arguments which can be used to
Benjamin Peterson90c58022010-03-03 01:55:09 +00001539 customize this display::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001540
1541 >>> parser = argparse.ArgumentParser(prog='PROG', add_help=False)
1542 >>> group1 = parser.add_argument_group('group1', 'group1 description')
1543 >>> group1.add_argument('foo', help='foo help')
1544 >>> group2 = parser.add_argument_group('group2', 'group2 description')
1545 >>> group2.add_argument('--bar', help='bar help')
1546 >>> parser.print_help()
1547 usage: PROG [--bar BAR] foo
1548
1549 group1:
1550 group1 description
1551
1552 foo foo help
1553
1554 group2:
1555 group2 description
1556
1557 --bar BAR bar help
1558
Benjamin Peterson90c58022010-03-03 01:55:09 +00001559 Note that any arguments not your user defined groups will end up back in the
1560 usual "positional arguments" and "optional arguments" sections.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001561
1562
1563Mutual exclusion
1564^^^^^^^^^^^^^^^^
1565
Georg Brandlb8d0e362010-11-26 07:53:50 +00001566.. method:: add_mutually_exclusive_group(required=False)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001567
Benjamin Peterson90c58022010-03-03 01:55:09 +00001568 Create a mutually exclusive group. argparse will make sure that only one of
Benjamin Petersona39e9662010-03-02 22:05:59 +00001569 the arguments in the mutually exclusive group was present on the command
1570 line::
1571
1572 >>> parser = argparse.ArgumentParser(prog='PROG')
1573 >>> group = parser.add_mutually_exclusive_group()
1574 >>> group.add_argument('--foo', action='store_true')
1575 >>> group.add_argument('--bar', action='store_false')
1576 >>> parser.parse_args(['--foo'])
1577 Namespace(bar=True, foo=True)
1578 >>> parser.parse_args(['--bar'])
1579 Namespace(bar=False, foo=False)
1580 >>> parser.parse_args(['--foo', '--bar'])
1581 usage: PROG [-h] [--foo | --bar]
1582 PROG: error: argument --bar: not allowed with argument --foo
1583
Georg Brandlb8d0e362010-11-26 07:53:50 +00001584 The :meth:`add_mutually_exclusive_group` method also accepts a *required*
Benjamin Petersona39e9662010-03-02 22:05:59 +00001585 argument, to indicate that at least one of the mutually exclusive arguments
1586 is required::
1587
1588 >>> parser = argparse.ArgumentParser(prog='PROG')
1589 >>> group = parser.add_mutually_exclusive_group(required=True)
1590 >>> group.add_argument('--foo', action='store_true')
1591 >>> group.add_argument('--bar', action='store_false')
1592 >>> parser.parse_args([])
1593 usage: PROG [-h] (--foo | --bar)
1594 PROG: error: one of the arguments --foo --bar is required
1595
1596 Note that currently mutually exclusive argument groups do not support the
Georg Brandlb8d0e362010-11-26 07:53:50 +00001597 *title* and *description* arguments of :meth:`add_argument_group`.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001598
1599
1600Parser defaults
1601^^^^^^^^^^^^^^^
1602
Benjamin Peterson90c58022010-03-03 01:55:09 +00001603.. method:: ArgumentParser.set_defaults(**kwargs)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001604
Georg Brandld2decd92010-03-02 22:17:38 +00001605 Most of the time, the attributes of the object returned by :meth:`parse_args`
1606 will be fully determined by inspecting the command-line args and the argument
Benjamin Petersonc516d192010-03-03 02:04:24 +00001607 actions. :meth:`ArgumentParser.set_defaults` allows some additional
1608 attributes that are determined without any inspection of the command-line to
1609 be added::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001610
1611 >>> parser = argparse.ArgumentParser()
1612 >>> parser.add_argument('foo', type=int)
1613 >>> parser.set_defaults(bar=42, baz='badger')
1614 >>> parser.parse_args(['736'])
1615 Namespace(bar=42, baz='badger', foo=736)
1616
Benjamin Peterson90c58022010-03-03 01:55:09 +00001617 Note that parser-level defaults always override argument-level defaults::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001618
1619 >>> parser = argparse.ArgumentParser()
1620 >>> parser.add_argument('--foo', default='bar')
1621 >>> parser.set_defaults(foo='spam')
1622 >>> parser.parse_args([])
1623 Namespace(foo='spam')
1624
Benjamin Peterson90c58022010-03-03 01:55:09 +00001625 Parser-level defaults can be particularly useful when working with multiple
1626 parsers. See the :meth:`~ArgumentParser.add_subparsers` method for an
1627 example of this type.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001628
Benjamin Peterson90c58022010-03-03 01:55:09 +00001629.. method:: ArgumentParser.get_default(dest)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001630
1631 Get the default value for a namespace attribute, as set by either
Benjamin Peterson90c58022010-03-03 01:55:09 +00001632 :meth:`~ArgumentParser.add_argument` or by
1633 :meth:`~ArgumentParser.set_defaults`::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001634
1635 >>> parser = argparse.ArgumentParser()
1636 >>> parser.add_argument('--foo', default='badger')
1637 >>> parser.get_default('foo')
1638 'badger'
1639
1640
1641Printing help
1642^^^^^^^^^^^^^
1643
1644In most typical applications, :meth:`parse_args` will take care of formatting
Benjamin Peterson90c58022010-03-03 01:55:09 +00001645and printing any usage or error messages. However, several formatting methods
1646are available:
Benjamin Petersona39e9662010-03-02 22:05:59 +00001647
Georg Brandlb8d0e362010-11-26 07:53:50 +00001648.. method:: ArgumentParser.print_usage(file=None)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001649
1650 Print a brief description of how the :class:`ArgumentParser` should be
Georg Brandlb8d0e362010-11-26 07:53:50 +00001651 invoked on the command line. If *file* is ``None``, :data:`sys.stderr` is
Benjamin Petersona39e9662010-03-02 22:05:59 +00001652 assumed.
1653
Georg Brandlb8d0e362010-11-26 07:53:50 +00001654.. method:: ArgumentParser.print_help(file=None)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001655
1656 Print a help message, including the program usage and information about the
Georg Brandlb8d0e362010-11-26 07:53:50 +00001657 arguments registered with the :class:`ArgumentParser`. If *file* is
1658 ``None``, :data:`sys.stderr` is assumed.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001659
1660There are also variants of these methods that simply return a string instead of
1661printing it:
1662
Georg Brandlb8d0e362010-11-26 07:53:50 +00001663.. method:: ArgumentParser.format_usage()
Benjamin Petersona39e9662010-03-02 22:05:59 +00001664
1665 Return a string containing a brief description of how the
1666 :class:`ArgumentParser` should be invoked on the command line.
1667
Georg Brandlb8d0e362010-11-26 07:53:50 +00001668.. method:: ArgumentParser.format_help()
Benjamin Petersona39e9662010-03-02 22:05:59 +00001669
1670 Return a string containing a help message, including the program usage and
1671 information about the arguments registered with the :class:`ArgumentParser`.
1672
1673
Benjamin Petersona39e9662010-03-02 22:05:59 +00001674Partial parsing
1675^^^^^^^^^^^^^^^
1676
Georg Brandlb8d0e362010-11-26 07:53:50 +00001677.. method:: ArgumentParser.parse_known_args(args=None, namespace=None)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001678
1679Sometimes a script may only parse a few of the command line arguments, passing
1680the remaining arguments on to another script or program. In these cases, the
Georg Brandld2decd92010-03-02 22:17:38 +00001681:meth:`parse_known_args` method can be useful. It works much like
Benjamin Peterson90c58022010-03-03 01:55:09 +00001682:meth:`~ArgumentParser.parse_args` except that it does not produce an error when
1683extra arguments are present. Instead, it returns a two item tuple containing
1684the populated namespace and the list of remaining argument strings.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001685
1686::
1687
1688 >>> parser = argparse.ArgumentParser()
1689 >>> parser.add_argument('--foo', action='store_true')
1690 >>> parser.add_argument('bar')
1691 >>> parser.parse_known_args(['--foo', '--badger', 'BAR', 'spam'])
1692 (Namespace(bar='BAR', foo=True), ['--badger', 'spam'])
1693
1694
1695Customizing file parsing
1696^^^^^^^^^^^^^^^^^^^^^^^^
1697
Benjamin Peterson90c58022010-03-03 01:55:09 +00001698.. method:: ArgumentParser.convert_arg_line_to_args(arg_line)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001699
Georg Brandlb8d0e362010-11-26 07:53:50 +00001700 Arguments that are read from a file (see the *fromfile_prefix_chars*
Benjamin Petersona39e9662010-03-02 22:05:59 +00001701 keyword argument to the :class:`ArgumentParser` constructor) are read one
Benjamin Peterson90c58022010-03-03 01:55:09 +00001702 argument per line. :meth:`convert_arg_line_to_args` can be overriden for
1703 fancier reading.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001704
Georg Brandlb8d0e362010-11-26 07:53:50 +00001705 This method takes a single argument *arg_line* which is a string read from
Benjamin Petersona39e9662010-03-02 22:05:59 +00001706 the argument file. It returns a list of arguments parsed from this string.
1707 The method is called once per line read from the argument file, in order.
1708
Georg Brandld2decd92010-03-02 22:17:38 +00001709 A useful override of this method is one that treats each space-separated word
1710 as an argument::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001711
1712 def convert_arg_line_to_args(self, arg_line):
1713 for arg in arg_line.split():
1714 if not arg.strip():
1715 continue
1716 yield arg
1717
1718
Georg Brandlb8d0e362010-11-26 07:53:50 +00001719Exiting methods
1720^^^^^^^^^^^^^^^
1721
1722.. method:: ArgumentParser.exit(status=0, message=None)
1723
1724 This method terminates the program, exiting with the specified *status*
1725 and, if given, it prints a *message* before that.
1726
1727.. method:: ArgumentParser.error(message)
1728
1729 This method prints a usage message including the *message* to the
1730 standard output and terminates the program with a status code of 2.
1731
1732
Georg Brandl58df6792010-07-03 10:25:47 +00001733.. _argparse-from-optparse:
1734
Benjamin Petersona39e9662010-03-02 22:05:59 +00001735Upgrading optparse code
1736-----------------------
1737
1738Originally, the argparse module had attempted to maintain compatibility with
Georg Brandld2decd92010-03-02 22:17:38 +00001739optparse. However, optparse was difficult to extend transparently, particularly
1740with the changes required to support the new ``nargs=`` specifiers and better
Georg Brandl404bd7f2010-04-25 10:16:00 +00001741usage messages. When most everything in optparse had either been copy-pasted
Georg Brandld2decd92010-03-02 22:17:38 +00001742over or monkey-patched, it no longer seemed practical to try to maintain the
1743backwards compatibility.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001744
1745A partial upgrade path from optparse to argparse:
1746
Benjamin Peterson90c58022010-03-03 01:55:09 +00001747* Replace all ``add_option()`` calls with :meth:`ArgumentParser.add_argument` calls.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001748
Georg Brandld2decd92010-03-02 22:17:38 +00001749* Replace ``options, args = parser.parse_args()`` with ``args =
Benjamin Peterson90c58022010-03-03 01:55:09 +00001750 parser.parse_args()`` and add additional :meth:`ArgumentParser.add_argument` calls for the
Georg Brandld2decd92010-03-02 22:17:38 +00001751 positional arguments.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001752
1753* Replace callback actions and the ``callback_*`` keyword arguments with
1754 ``type`` or ``action`` arguments.
1755
1756* Replace string names for ``type`` keyword arguments with the corresponding
1757 type objects (e.g. int, float, complex, etc).
1758
Benjamin Peterson90c58022010-03-03 01:55:09 +00001759* Replace :class:`optparse.Values` with :class:`Namespace` and
1760 :exc:`optparse.OptionError` and :exc:`optparse.OptionValueError` with
1761 :exc:`ArgumentError`.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001762
Georg Brandld2decd92010-03-02 22:17:38 +00001763* Replace strings with implicit arguments such as ``%default`` or ``%prog`` with
1764 the standard python syntax to use dictionaries to format strings, that is,
1765 ``%(default)s`` and ``%(prog)s``.
Steven Bethard74bd9cf2010-05-24 02:38:00 +00001766
1767* Replace the OptionParser constructor ``version`` argument with a call to
1768 ``parser.add_argument('--version', action='version', version='<the version>')``