blob: 0823141197a4bb41469179d70fd361eac0837598 [file] [log] [blame]
Ezio Melotti12125822011-04-16 23:04:51 +03001:mod:`argparse` --- Parser for command-line options, arguments and sub-commands
Georg Brandlb8d0e362010-11-26 07:53:50 +00002===============================================================================
Benjamin Petersona39e9662010-03-02 22:05:59 +00003
4.. module:: argparse
Ezio Melotti12125822011-04-16 23:04:51 +03005 :synopsis: Command-line option and argument-parsing library.
Benjamin Petersona39e9662010-03-02 22:05:59 +00006.. moduleauthor:: Steven Bethard <steven.bethard@gmail.com>
7.. versionadded:: 2.7
8.. sectionauthor:: Steven Bethard <steven.bethard@gmail.com>
9
10
Ezio Melotti12125822011-04-16 23:04:51 +030011The :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
Ezio Melotti2eab88e2011-04-21 15:26:46 +030078parse 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
Ezio Melottic69313a2011-04-22 01:29:13 +030096Later, calling :meth:`~ArgumentParser.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
Ezio Melotti12125822011-04-16 23:04:51 +0300107: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.
Éric Araujof0d44bc2011-07-29 17:59:17 +0200109In most cases, this means a simple :class:`Namespace` object will be built up from
Ezio Melotti12125822011-04-16 23:04:51 +0300110attributes 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
Ezio Melotti569083a2011-04-21 23:30:27 +0300123.. class:: ArgumentParser([description], [epilog], [prog], [usage], [add_help], [argument_default], [parents], [prefix_chars], [conflict_handler], [formatter_class])
Benjamin Petersona39e9662010-03-02 22:05:59 +0000124
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
Ezio Melotti12125822011-04-16 23:04:51 +0300218If ``-h`` or ``--help`` is supplied at the command line, the ArgumentParser
Benjamin Petersona39e9662010-03-02 22:05:59 +0000219help 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
Ezio Melottic69313a2011-04-22 01:29:13 +0300292:meth:`~ArgumentParser.convert_arg_line_to_args`) and are treated as if they
293were in the same place as the original file referencing argument on the command
294line. So in the example above, the expression ``['-f', 'foo', '@args.txt']``
295is considered equivalent to the expression ``['-f', 'foo', '-f', 'bar']``.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000296
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
Ezio Melottic69313a2011-04-22 01:29:13 +0300305:meth:`~ArgumentParser.add_argument` or by calling the
306:meth:`~ArgumentParser.set_defaults` methods with a specific set of name-value
307pairs. Sometimes however, it may be useful to specify a single parser-wide
308default for arguments. This can be accomplished by passing the
309``argument_default=`` keyword argument to :class:`ArgumentParser`. For example,
310to globally suppress attribute creation on :meth:`~ArgumentParser.parse_args`
Benjamin Peterson90c58022010-03-03 01:55:09 +0000311calls, we supply ``argument_default=SUPPRESS``::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000312
313 >>> parser = argparse.ArgumentParser(argument_default=argparse.SUPPRESS)
314 >>> parser.add_argument('--foo')
315 >>> parser.add_argument('bar', nargs='?')
316 >>> parser.parse_args(['--foo', '1', 'BAR'])
317 Namespace(bar='BAR', foo='1')
318 >>> parser.parse_args([])
319 Namespace()
320
321
322parents
323^^^^^^^
324
325Sometimes, several parsers share a common set of arguments. Rather than
Benjamin Peterson90c58022010-03-03 01:55:09 +0000326repeating the definitions of these arguments, a single parser with all the
327shared arguments and passed to ``parents=`` argument to :class:`ArgumentParser`
328can be used. The ``parents=`` argument takes a list of :class:`ArgumentParser`
329objects, collects all the positional and optional actions from them, and adds
330these actions to the :class:`ArgumentParser` object being constructed::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000331
332 >>> parent_parser = argparse.ArgumentParser(add_help=False)
333 >>> parent_parser.add_argument('--parent', type=int)
334
335 >>> foo_parser = argparse.ArgumentParser(parents=[parent_parser])
336 >>> foo_parser.add_argument('foo')
337 >>> foo_parser.parse_args(['--parent', '2', 'XXX'])
338 Namespace(foo='XXX', parent=2)
339
340 >>> bar_parser = argparse.ArgumentParser(parents=[parent_parser])
341 >>> bar_parser.add_argument('--bar')
342 >>> bar_parser.parse_args(['--bar', 'YYY'])
343 Namespace(bar='YYY', parent=None)
344
Georg Brandld2decd92010-03-02 22:17:38 +0000345Note that most parent parsers will specify ``add_help=False``. Otherwise, the
Benjamin Peterson90c58022010-03-03 01:55:09 +0000346:class:`ArgumentParser` will see two ``-h/--help`` options (one in the parent
347and one in the child) and raise an error.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000348
Steven Bethard5e0062d2011-03-26 21:50:38 +0100349.. note::
350 You must fully initialize the parsers before passing them via ``parents=``.
351 If you change the parent parsers after the child parser, those changes will
352 not be reflected in the child.
353
Benjamin Petersona39e9662010-03-02 22:05:59 +0000354
355formatter_class
356^^^^^^^^^^^^^^^
357
Benjamin Peterson90c58022010-03-03 01:55:09 +0000358:class:`ArgumentParser` objects allow the help formatting to be customized by
359specifying an alternate formatting class. Currently, there are three such
Ezio Melottic69313a2011-04-22 01:29:13 +0300360classes:
361
362.. class:: RawDescriptionHelpFormatter
363 RawTextHelpFormatter
364 ArgumentDefaultsHelpFormatter
365
366The first two allow more control over how textual descriptions are displayed,
367while the last automatically adds information about argument default values.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000368
Benjamin Peterson90c58022010-03-03 01:55:09 +0000369By default, :class:`ArgumentParser` objects line-wrap the description_ and
370epilog_ texts in command-line help messages::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000371
372 >>> parser = argparse.ArgumentParser(
373 ... prog='PROG',
374 ... description='''this description
375 ... was indented weird
376 ... but that is okay''',
377 ... epilog='''
378 ... likewise for this epilog whose whitespace will
379 ... be cleaned up and whose words will be wrapped
380 ... across a couple lines''')
381 >>> parser.print_help()
382 usage: PROG [-h]
383
384 this description was indented weird but that is okay
385
386 optional arguments:
387 -h, --help show this help message and exit
388
389 likewise for this epilog whose whitespace will be cleaned up and whose words
390 will be wrapped across a couple lines
391
Ezio Melottic69313a2011-04-22 01:29:13 +0300392Passing :class:`~argparse.RawDescriptionHelpFormatter` as ``formatter_class=``
Benjamin Petersonc516d192010-03-03 02:04:24 +0000393indicates that description_ and epilog_ are already correctly formatted and
Benjamin Peterson90c58022010-03-03 01:55:09 +0000394should not be line-wrapped::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000395
396 >>> parser = argparse.ArgumentParser(
397 ... prog='PROG',
398 ... formatter_class=argparse.RawDescriptionHelpFormatter,
399 ... description=textwrap.dedent('''\
400 ... Please do not mess up this text!
401 ... --------------------------------
402 ... I have indented it
403 ... exactly the way
404 ... I want it
405 ... '''))
406 >>> parser.print_help()
407 usage: PROG [-h]
408
409 Please do not mess up this text!
410 --------------------------------
411 I have indented it
412 exactly the way
413 I want it
414
415 optional arguments:
416 -h, --help show this help message and exit
417
Benjamin Peterson90c58022010-03-03 01:55:09 +0000418:class:`RawTextHelpFormatter` maintains whitespace for all sorts of help text
419including argument descriptions.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000420
Benjamin Peterson90c58022010-03-03 01:55:09 +0000421The other formatter class available, :class:`ArgumentDefaultsHelpFormatter`,
Georg Brandld2decd92010-03-02 22:17:38 +0000422will add information about the default value of each of the arguments::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000423
424 >>> parser = argparse.ArgumentParser(
425 ... prog='PROG',
426 ... formatter_class=argparse.ArgumentDefaultsHelpFormatter)
427 >>> parser.add_argument('--foo', type=int, default=42, help='FOO!')
428 >>> parser.add_argument('bar', nargs='*', default=[1, 2, 3], help='BAR!')
429 >>> parser.print_help()
430 usage: PROG [-h] [--foo FOO] [bar [bar ...]]
431
432 positional arguments:
433 bar BAR! (default: [1, 2, 3])
434
435 optional arguments:
436 -h, --help show this help message and exit
437 --foo FOO FOO! (default: 42)
438
439
440conflict_handler
441^^^^^^^^^^^^^^^^
442
Benjamin Peterson90c58022010-03-03 01:55:09 +0000443:class:`ArgumentParser` objects do not allow two actions with the same option
444string. By default, :class:`ArgumentParser` objects raises an exception if an
445attempt is made to create an argument with an option string that is already in
446use::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000447
448 >>> parser = argparse.ArgumentParser(prog='PROG')
449 >>> parser.add_argument('-f', '--foo', help='old foo help')
450 >>> parser.add_argument('--foo', help='new foo help')
451 Traceback (most recent call last):
452 ..
453 ArgumentError: argument --foo: conflicting option string(s): --foo
454
455Sometimes (e.g. when using parents_) it may be useful to simply override any
Georg Brandld2decd92010-03-02 22:17:38 +0000456older arguments with the same option string. To get this behavior, the value
Benjamin Petersona39e9662010-03-02 22:05:59 +0000457``'resolve'`` can be supplied to the ``conflict_handler=`` argument of
Benjamin Peterson90c58022010-03-03 01:55:09 +0000458:class:`ArgumentParser`::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000459
460 >>> parser = argparse.ArgumentParser(prog='PROG', conflict_handler='resolve')
461 >>> parser.add_argument('-f', '--foo', help='old foo help')
462 >>> parser.add_argument('--foo', help='new foo help')
463 >>> parser.print_help()
464 usage: PROG [-h] [-f FOO] [--foo FOO]
465
466 optional arguments:
467 -h, --help show this help message and exit
468 -f FOO old foo help
469 --foo FOO new foo help
470
Benjamin Peterson90c58022010-03-03 01:55:09 +0000471Note that :class:`ArgumentParser` objects only remove an action if all of its
472option strings are overridden. So, in the example above, the old ``-f/--foo``
473action is retained as the ``-f`` action, because only the ``--foo`` option
474string was overridden.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000475
476
477prog
478^^^^
479
Benjamin Peterson90c58022010-03-03 01:55:09 +0000480By default, :class:`ArgumentParser` objects uses ``sys.argv[0]`` to determine
481how to display the name of the program in help messages. This default is almost
Ezio Melotti019551f2010-05-19 00:32:52 +0000482always desirable because it will make the help messages match how the program was
Benjamin Peterson90c58022010-03-03 01:55:09 +0000483invoked on the command line. For example, consider a file named
484``myprogram.py`` with the following code::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000485
486 import argparse
487 parser = argparse.ArgumentParser()
488 parser.add_argument('--foo', help='foo help')
489 args = parser.parse_args()
490
491The help for this program will display ``myprogram.py`` as the program name
492(regardless of where the program was invoked from)::
493
494 $ python myprogram.py --help
495 usage: myprogram.py [-h] [--foo FOO]
496
497 optional arguments:
498 -h, --help show this help message and exit
499 --foo FOO foo help
500 $ cd ..
501 $ python subdir\myprogram.py --help
502 usage: myprogram.py [-h] [--foo FOO]
503
504 optional arguments:
505 -h, --help show this help message and exit
506 --foo FOO foo help
507
508To change this default behavior, another value can be supplied using the
Benjamin Peterson90c58022010-03-03 01:55:09 +0000509``prog=`` argument to :class:`ArgumentParser`::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000510
511 >>> parser = argparse.ArgumentParser(prog='myprogram')
512 >>> parser.print_help()
513 usage: myprogram [-h]
514
515 optional arguments:
516 -h, --help show this help message and exit
517
518Note that the program name, whether determined from ``sys.argv[0]`` or from the
519``prog=`` argument, is available to help messages using the ``%(prog)s`` format
520specifier.
521
522::
523
524 >>> parser = argparse.ArgumentParser(prog='myprogram')
525 >>> parser.add_argument('--foo', help='foo of the %(prog)s program')
526 >>> parser.print_help()
527 usage: myprogram [-h] [--foo FOO]
528
529 optional arguments:
530 -h, --help show this help message and exit
531 --foo FOO foo of the myprogram program
532
533
534usage
535^^^^^
536
Benjamin Peterson90c58022010-03-03 01:55:09 +0000537By default, :class:`ArgumentParser` calculates the usage message from the
Benjamin Petersona39e9662010-03-02 22:05:59 +0000538arguments it contains::
539
540 >>> parser = argparse.ArgumentParser(prog='PROG')
541 >>> parser.add_argument('--foo', nargs='?', help='foo help')
542 >>> parser.add_argument('bar', nargs='+', help='bar help')
543 >>> parser.print_help()
544 usage: PROG [-h] [--foo [FOO]] bar [bar ...]
545
546 positional arguments:
547 bar bar help
548
549 optional arguments:
550 -h, --help show this help message and exit
551 --foo [FOO] foo help
552
Benjamin Peterson90c58022010-03-03 01:55:09 +0000553The default message can be overridden with the ``usage=`` keyword argument::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000554
555 >>> parser = argparse.ArgumentParser(prog='PROG', usage='%(prog)s [options]')
556 >>> parser.add_argument('--foo', nargs='?', help='foo help')
557 >>> parser.add_argument('bar', nargs='+', help='bar help')
558 >>> parser.print_help()
559 usage: PROG [options]
560
561 positional arguments:
562 bar bar help
563
564 optional arguments:
565 -h, --help show this help message and exit
566 --foo [FOO] foo help
567
Benjamin Peterson90c58022010-03-03 01:55:09 +0000568The ``%(prog)s`` format specifier is available to fill in the program name in
569your usage messages.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000570
571
572The add_argument() method
573-------------------------
574
Ezio Melotti569083a2011-04-21 23:30:27 +0300575.. method:: ArgumentParser.add_argument(name or flags..., [action], [nargs], [const], [default], [type], [choices], [required], [help], [metavar], [dest])
Benjamin Petersona39e9662010-03-02 22:05:59 +0000576
Ezio Melotti12125822011-04-16 23:04:51 +0300577 Define how a single command-line argument should be parsed. Each parameter
Benjamin Petersona39e9662010-03-02 22:05:59 +0000578 has its own more detailed description below, but in short they are:
579
580 * `name or flags`_ - Either a name or a list of option strings, e.g. ``foo``
Ezio Melottid281f142011-04-21 23:09:27 +0300581 or ``-f, --foo``.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000582
583 * action_ - The basic type of action to be taken when this argument is
Ezio Melotti12125822011-04-16 23:04:51 +0300584 encountered at the command line.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000585
586 * nargs_ - The number of command-line arguments that should be consumed.
587
588 * const_ - A constant value required by some action_ and nargs_ selections.
589
590 * default_ - The value produced if the argument is absent from the
Ezio Melotti12125822011-04-16 23:04:51 +0300591 command line.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000592
Ezio Melotti12125822011-04-16 23:04:51 +0300593 * type_ - The type to which the command-line argument should be converted.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000594
595 * choices_ - A container of the allowable values for the argument.
596
597 * required_ - Whether or not the command-line option may be omitted
598 (optionals only).
599
600 * help_ - A brief description of what the argument does.
601
602 * metavar_ - A name for the argument in usage messages.
603
604 * dest_ - The name of the attribute to be added to the object returned by
605 :meth:`parse_args`.
606
Benjamin Peterson90c58022010-03-03 01:55:09 +0000607The following sections describe how each of these are used.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000608
Georg Brandlb8d0e362010-11-26 07:53:50 +0000609
Benjamin Petersona39e9662010-03-02 22:05:59 +0000610name or flags
611^^^^^^^^^^^^^
612
Ezio Melottic69313a2011-04-22 01:29:13 +0300613The :meth:`~ArgumentParser.add_argument` method must know whether an optional
614argument, like ``-f`` or ``--foo``, or a positional argument, like a list of
615filenames, is expected. The first arguments passed to
616:meth:`~ArgumentParser.add_argument` must therefore be either a series of
617flags, or a simple argument name. For example, an optional argument could
618be created like::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000619
620 >>> parser.add_argument('-f', '--foo')
621
622while a positional argument could be created like::
623
624 >>> parser.add_argument('bar')
625
Ezio Melottic69313a2011-04-22 01:29:13 +0300626When :meth:`~ArgumentParser.parse_args` is called, optional arguments will be
627identified by the ``-`` prefix, and the remaining arguments will be assumed to
628be positional::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000629
630 >>> parser = argparse.ArgumentParser(prog='PROG')
631 >>> parser.add_argument('-f', '--foo')
632 >>> parser.add_argument('bar')
633 >>> parser.parse_args(['BAR'])
634 Namespace(bar='BAR', foo=None)
635 >>> parser.parse_args(['BAR', '--foo', 'FOO'])
636 Namespace(bar='BAR', foo='FOO')
637 >>> parser.parse_args(['--foo', 'FOO'])
638 usage: PROG [-h] [-f FOO] bar
639 PROG: error: too few arguments
640
Georg Brandlb8d0e362010-11-26 07:53:50 +0000641
Benjamin Petersona39e9662010-03-02 22:05:59 +0000642action
643^^^^^^
644
Georg Brandld2decd92010-03-02 22:17:38 +0000645:class:`ArgumentParser` objects associate command-line args with actions. These
Benjamin Petersona39e9662010-03-02 22:05:59 +0000646actions can do just about anything with the command-line args associated with
647them, though most actions simply add an attribute to the object returned by
Ezio Melottic69313a2011-04-22 01:29:13 +0300648:meth:`~ArgumentParser.parse_args`. The ``action`` keyword argument specifies
649how the command-line args should be handled. The supported actions are:
Benjamin Petersona39e9662010-03-02 22:05:59 +0000650
Georg Brandld2decd92010-03-02 22:17:38 +0000651* ``'store'`` - This just stores the argument's value. This is the default
Ezio Melotti310619c2011-04-21 23:06:48 +0300652 action. For example::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000653
654 >>> parser = argparse.ArgumentParser()
655 >>> parser.add_argument('--foo')
656 >>> parser.parse_args('--foo 1'.split())
657 Namespace(foo='1')
658
659* ``'store_const'`` - This stores the value specified by the const_ keyword
Ezio Melotti310619c2011-04-21 23:06:48 +0300660 argument. (Note that the const_ keyword argument defaults to the rather
661 unhelpful ``None``.) The ``'store_const'`` action is most commonly used with
662 optional arguments that specify some sort of flag. For example::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000663
664 >>> parser = argparse.ArgumentParser()
665 >>> parser.add_argument('--foo', action='store_const', const=42)
666 >>> parser.parse_args('--foo'.split())
667 Namespace(foo=42)
668
669* ``'store_true'`` and ``'store_false'`` - These store the values ``True`` and
Benjamin Peterson90c58022010-03-03 01:55:09 +0000670 ``False`` respectively. These are special cases of ``'store_const'``. For
671 example::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000672
673 >>> parser = argparse.ArgumentParser()
674 >>> parser.add_argument('--foo', action='store_true')
675 >>> parser.add_argument('--bar', action='store_false')
676 >>> parser.parse_args('--foo --bar'.split())
677 Namespace(bar=False, foo=True)
678
679* ``'append'`` - This stores a list, and appends each argument value to the
Benjamin Peterson90c58022010-03-03 01:55:09 +0000680 list. This is useful to allow an option to be specified multiple times.
681 Example usage::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000682
683 >>> parser = argparse.ArgumentParser()
684 >>> parser.add_argument('--foo', action='append')
685 >>> parser.parse_args('--foo 1 --foo 2'.split())
686 Namespace(foo=['1', '2'])
687
688* ``'append_const'`` - This stores a list, and appends the value specified by
Benjamin Peterson90c58022010-03-03 01:55:09 +0000689 the const_ keyword argument to the list. (Note that the const_ keyword
690 argument defaults to ``None``.) The ``'append_const'`` action is typically
691 useful when multiple arguments need to store constants to the same list. For
692 example::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000693
694 >>> parser = argparse.ArgumentParser()
695 >>> parser.add_argument('--str', dest='types', action='append_const', const=str)
696 >>> parser.add_argument('--int', dest='types', action='append_const', const=int)
697 >>> parser.parse_args('--str --int'.split())
698 Namespace(types=[<type 'str'>, <type 'int'>])
699
700* ``'version'`` - This expects a ``version=`` keyword argument in the
Ezio Melottic69313a2011-04-22 01:29:13 +0300701 :meth:`~ArgumentParser.add_argument` call, and prints version information
702 and exits when invoked.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000703
704 >>> import argparse
705 >>> parser = argparse.ArgumentParser(prog='PROG')
Steven Bethard74bd9cf2010-05-24 02:38:00 +0000706 >>> parser.add_argument('--version', action='version', version='%(prog)s 2.0')
707 >>> parser.parse_args(['--version'])
Benjamin Petersona39e9662010-03-02 22:05:59 +0000708 PROG 2.0
709
710You can also specify an arbitrary action by passing an object that implements
Benjamin Peterson90c58022010-03-03 01:55:09 +0000711the Action API. The easiest way to do this is to extend
712:class:`argparse.Action`, supplying an appropriate ``__call__`` method. The
713``__call__`` method should accept four parameters:
Benjamin Petersona39e9662010-03-02 22:05:59 +0000714
715* ``parser`` - The ArgumentParser object which contains this action.
716
Éric Araujof0d44bc2011-07-29 17:59:17 +0200717* ``namespace`` - The :class:`Namespace` object that will be returned by
Ezio Melottic69313a2011-04-22 01:29:13 +0300718 :meth:`~ArgumentParser.parse_args`. Most actions add an attribute to this
719 object.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000720
721* ``values`` - The associated command-line args, with any type-conversions
722 applied. (Type-conversions are specified with the type_ keyword argument to
Ezio Melottic69313a2011-04-22 01:29:13 +0300723 :meth:`~ArgumentParser.add_argument`.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000724
725* ``option_string`` - The option string that was used to invoke this action.
726 The ``option_string`` argument is optional, and will be absent if the action
727 is associated with a positional argument.
728
Benjamin Peterson90c58022010-03-03 01:55:09 +0000729An example of a custom action::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000730
731 >>> class FooAction(argparse.Action):
732 ... def __call__(self, parser, namespace, values, option_string=None):
Georg Brandl8891e232010-08-01 21:23:50 +0000733 ... print '%r %r %r' % (namespace, values, option_string)
734 ... setattr(namespace, self.dest, values)
Benjamin Petersona39e9662010-03-02 22:05:59 +0000735 ...
736 >>> parser = argparse.ArgumentParser()
737 >>> parser.add_argument('--foo', action=FooAction)
738 >>> parser.add_argument('bar', action=FooAction)
739 >>> args = parser.parse_args('1 --foo 2'.split())
740 Namespace(bar=None, foo=None) '1' None
741 Namespace(bar='1', foo=None) '2' '--foo'
742 >>> args
743 Namespace(bar='1', foo='2')
744
745
746nargs
747^^^^^
748
749ArgumentParser objects usually associate a single command-line argument with a
Benjamin Peterson90c58022010-03-03 01:55:09 +0000750single action to be taken. The ``nargs`` keyword argument associates a
Ezio Melotti0a43ecc2011-04-21 22:56:51 +0300751different number of command-line arguments with a single action. The supported
Benjamin Peterson90c58022010-03-03 01:55:09 +0000752values are:
Benjamin Petersona39e9662010-03-02 22:05:59 +0000753
Ezio Melotti12125822011-04-16 23:04:51 +0300754* N (an integer). N args from the command line will be gathered together into a
Georg Brandld2decd92010-03-02 22:17:38 +0000755 list. For example::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000756
Georg Brandl35e7a8f2010-10-06 10:41:31 +0000757 >>> parser = argparse.ArgumentParser()
758 >>> parser.add_argument('--foo', nargs=2)
759 >>> parser.add_argument('bar', nargs=1)
760 >>> parser.parse_args('c --foo a b'.split())
761 Namespace(bar=['c'], foo=['a', 'b'])
Benjamin Petersona39e9662010-03-02 22:05:59 +0000762
Georg Brandl35e7a8f2010-10-06 10:41:31 +0000763 Note that ``nargs=1`` produces a list of one item. This is different from
764 the default, in which the item is produced by itself.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000765
Ezio Melotti12125822011-04-16 23:04:51 +0300766* ``'?'``. One arg will be consumed from the command line if possible, and
Benjamin Petersona39e9662010-03-02 22:05:59 +0000767 produced as a single item. If no command-line arg is present, the value from
768 default_ will be produced. Note that for optional arguments, there is an
769 additional case - the option string is present but not followed by a
770 command-line arg. In this case the value from const_ will be produced. Some
771 examples to illustrate this::
772
Georg Brandld2decd92010-03-02 22:17:38 +0000773 >>> parser = argparse.ArgumentParser()
774 >>> parser.add_argument('--foo', nargs='?', const='c', default='d')
775 >>> parser.add_argument('bar', nargs='?', default='d')
776 >>> parser.parse_args('XX --foo YY'.split())
777 Namespace(bar='XX', foo='YY')
778 >>> parser.parse_args('XX --foo'.split())
779 Namespace(bar='XX', foo='c')
780 >>> parser.parse_args(''.split())
781 Namespace(bar='d', foo='d')
Benjamin Petersona39e9662010-03-02 22:05:59 +0000782
Georg Brandld2decd92010-03-02 22:17:38 +0000783 One of the more common uses of ``nargs='?'`` is to allow optional input and
784 output files::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000785
Georg Brandld2decd92010-03-02 22:17:38 +0000786 >>> parser = argparse.ArgumentParser()
Georg Brandlb8d0e362010-11-26 07:53:50 +0000787 >>> parser.add_argument('infile', nargs='?', type=argparse.FileType('r'),
788 ... default=sys.stdin)
789 >>> parser.add_argument('outfile', nargs='?', type=argparse.FileType('w'),
790 ... default=sys.stdout)
Georg Brandld2decd92010-03-02 22:17:38 +0000791 >>> parser.parse_args(['input.txt', 'output.txt'])
Georg Brandl585bbb92011-01-09 09:33:09 +0000792 Namespace(infile=<open file 'input.txt', mode 'r' at 0x...>,
793 outfile=<open file 'output.txt', mode 'w' at 0x...>)
Georg Brandld2decd92010-03-02 22:17:38 +0000794 >>> parser.parse_args([])
Georg Brandl585bbb92011-01-09 09:33:09 +0000795 Namespace(infile=<open file '<stdin>', mode 'r' at 0x...>,
796 outfile=<open file '<stdout>', mode 'w' at 0x...>)
Benjamin Petersona39e9662010-03-02 22:05:59 +0000797
Georg Brandld2decd92010-03-02 22:17:38 +0000798* ``'*'``. All command-line args present are gathered into a list. Note that
799 it generally doesn't make much sense to have more than one positional argument
800 with ``nargs='*'``, but multiple optional arguments with ``nargs='*'`` is
801 possible. For example::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000802
Georg Brandld2decd92010-03-02 22:17:38 +0000803 >>> parser = argparse.ArgumentParser()
804 >>> parser.add_argument('--foo', nargs='*')
805 >>> parser.add_argument('--bar', nargs='*')
806 >>> parser.add_argument('baz', nargs='*')
807 >>> parser.parse_args('a b --foo x y --bar 1 2'.split())
808 Namespace(bar=['1', '2'], baz=['a', 'b'], foo=['x', 'y'])
Benjamin Petersona39e9662010-03-02 22:05:59 +0000809
810* ``'+'``. Just like ``'*'``, all command-line args present are gathered into a
811 list. Additionally, an error message will be generated if there wasn't at
812 least one command-line arg present. For example::
813
Georg Brandld2decd92010-03-02 22:17:38 +0000814 >>> parser = argparse.ArgumentParser(prog='PROG')
815 >>> parser.add_argument('foo', nargs='+')
816 >>> parser.parse_args('a b'.split())
817 Namespace(foo=['a', 'b'])
818 >>> parser.parse_args(''.split())
819 usage: PROG [-h] foo [foo ...]
820 PROG: error: too few arguments
Benjamin Petersona39e9662010-03-02 22:05:59 +0000821
822If the ``nargs`` keyword argument is not provided, the number of args consumed
Georg Brandld2decd92010-03-02 22:17:38 +0000823is determined by the action_. Generally this means a single command-line arg
Benjamin Petersona39e9662010-03-02 22:05:59 +0000824will be consumed and a single item (not a list) will be produced.
825
826
827const
828^^^^^
829
Ezio Melottic69313a2011-04-22 01:29:13 +0300830The ``const`` argument of :meth:`~ArgumentParser.add_argument` is used to hold
831constant values that are not read from the command line but are required for
832the various :class:`ArgumentParser` actions. The two most common uses of it are:
Benjamin Petersona39e9662010-03-02 22:05:59 +0000833
Ezio Melottic69313a2011-04-22 01:29:13 +0300834* When :meth:`~ArgumentParser.add_argument` is called with
835 ``action='store_const'`` or ``action='append_const'``. These actions add the
836 ``const`` value to one of the attributes of the object returned by :meth:`~ArgumentParser.parse_args`. See the action_ description for examples.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000837
Ezio Melottic69313a2011-04-22 01:29:13 +0300838* When :meth:`~ArgumentParser.add_argument` is called with option strings
839 (like ``-f`` or ``--foo``) and ``nargs='?'``. This creates an optional
840 argument that can be followed by zero or one command-line args.
841 When parsing the command line, if the option string is encountered with no
842 command-line arg following it, the value of ``const`` will be assumed instead.
843 See the nargs_ description for examples.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000844
845The ``const`` keyword argument defaults to ``None``.
846
847
848default
849^^^^^^^
850
851All optional arguments and some positional arguments may be omitted at the
Ezio Melottic69313a2011-04-22 01:29:13 +0300852command line. The ``default`` keyword argument of
853:meth:`~ArgumentParser.add_argument`, whose value defaults to ``None``,
854specifies what value should be used if the command-line arg is not present.
855For optional arguments, the ``default`` value is used when the option string
856was not present at the command line::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000857
858 >>> parser = argparse.ArgumentParser()
859 >>> parser.add_argument('--foo', default=42)
860 >>> parser.parse_args('--foo 2'.split())
861 Namespace(foo='2')
862 >>> parser.parse_args(''.split())
863 Namespace(foo=42)
864
865For positional arguments with nargs_ ``='?'`` or ``'*'``, the ``default`` value
866is used when no command-line arg was present::
867
868 >>> parser = argparse.ArgumentParser()
869 >>> parser.add_argument('foo', nargs='?', default=42)
870 >>> parser.parse_args('a'.split())
871 Namespace(foo='a')
872 >>> parser.parse_args(''.split())
873 Namespace(foo=42)
874
875
Benjamin Peterson90c58022010-03-03 01:55:09 +0000876Providing ``default=argparse.SUPPRESS`` causes no attribute to be added if the
877command-line argument was not present.::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000878
879 >>> parser = argparse.ArgumentParser()
880 >>> parser.add_argument('--foo', default=argparse.SUPPRESS)
881 >>> parser.parse_args([])
882 Namespace()
883 >>> parser.parse_args(['--foo', '1'])
884 Namespace(foo='1')
885
886
887type
888^^^^
889
890By default, ArgumentParser objects read command-line args in as simple strings.
891However, quite often the command-line string should instead be interpreted as
Benjamin Peterson90c58022010-03-03 01:55:09 +0000892another type, like a :class:`float`, :class:`int` or :class:`file`. The
Ezio Melottic69313a2011-04-22 01:29:13 +0300893``type`` keyword argument of :meth:`~ArgumentParser.add_argument` allows any
894necessary type-checking and type-conversions to be performed. Many common
895built-in types can be used directly as the value of the ``type`` argument::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000896
897 >>> parser = argparse.ArgumentParser()
898 >>> parser.add_argument('foo', type=int)
899 >>> parser.add_argument('bar', type=file)
900 >>> parser.parse_args('2 temp.txt'.split())
901 Namespace(bar=<open file 'temp.txt', mode 'r' at 0x...>, foo=2)
902
903To ease the use of various types of files, the argparse module provides the
904factory FileType which takes the ``mode=`` and ``bufsize=`` arguments of the
Georg Brandld2decd92010-03-02 22:17:38 +0000905``file`` object. For example, ``FileType('w')`` can be used to create a
Benjamin Petersona39e9662010-03-02 22:05:59 +0000906writable file::
907
908 >>> parser = argparse.ArgumentParser()
909 >>> parser.add_argument('bar', type=argparse.FileType('w'))
910 >>> parser.parse_args(['out.txt'])
911 Namespace(bar=<open file 'out.txt', mode 'w' at 0x...>)
912
Benjamin Peterson90c58022010-03-03 01:55:09 +0000913``type=`` can take any callable that takes a single string argument and returns
914the type-converted value::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000915
916 >>> def perfect_square(string):
917 ... value = int(string)
918 ... sqrt = math.sqrt(value)
919 ... if sqrt != int(sqrt):
920 ... msg = "%r is not a perfect square" % string
921 ... raise argparse.ArgumentTypeError(msg)
922 ... return value
923 ...
924 >>> parser = argparse.ArgumentParser(prog='PROG')
925 >>> parser.add_argument('foo', type=perfect_square)
926 >>> parser.parse_args('9'.split())
927 Namespace(foo=9)
928 >>> parser.parse_args('7'.split())
929 usage: PROG [-h] foo
930 PROG: error: argument foo: '7' is not a perfect square
931
Benjamin Peterson90c58022010-03-03 01:55:09 +0000932The choices_ keyword argument may be more convenient for type checkers that
933simply check against a range of values::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000934
935 >>> parser = argparse.ArgumentParser(prog='PROG')
936 >>> parser.add_argument('foo', type=int, choices=xrange(5, 10))
937 >>> parser.parse_args('7'.split())
938 Namespace(foo=7)
939 >>> parser.parse_args('11'.split())
940 usage: PROG [-h] {5,6,7,8,9}
941 PROG: error: argument foo: invalid choice: 11 (choose from 5, 6, 7, 8, 9)
942
943See the choices_ section for more details.
944
945
946choices
947^^^^^^^
948
949Some command-line args should be selected from a restricted set of values.
Benjamin Peterson90c58022010-03-03 01:55:09 +0000950These can be handled by passing a container object as the ``choices`` keyword
Ezio Melottic69313a2011-04-22 01:29:13 +0300951argument to :meth:`~ArgumentParser.add_argument`. When the command line is
952parsed, arg values will be checked, and an error message will be displayed if
953the arg was not one of the acceptable values::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000954
955 >>> parser = argparse.ArgumentParser(prog='PROG')
956 >>> parser.add_argument('foo', choices='abc')
957 >>> parser.parse_args('c'.split())
958 Namespace(foo='c')
959 >>> parser.parse_args('X'.split())
960 usage: PROG [-h] {a,b,c}
961 PROG: error: argument foo: invalid choice: 'X' (choose from 'a', 'b', 'c')
962
963Note that inclusion in the ``choices`` container is checked after any type_
964conversions have been performed, so the type of the objects in the ``choices``
965container should match the type_ specified::
966
967 >>> parser = argparse.ArgumentParser(prog='PROG')
968 >>> parser.add_argument('foo', type=complex, choices=[1, 1j])
969 >>> parser.parse_args('1j'.split())
970 Namespace(foo=1j)
971 >>> parser.parse_args('-- -4'.split())
972 usage: PROG [-h] {1,1j}
973 PROG: error: argument foo: invalid choice: (-4+0j) (choose from 1, 1j)
974
975Any object that supports the ``in`` operator can be passed as the ``choices``
Georg Brandld2decd92010-03-02 22:17:38 +0000976value, so :class:`dict` objects, :class:`set` objects, custom containers,
977etc. are all supported.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000978
979
980required
981^^^^^^^^
982
Ezio Melotti01b600c2011-04-21 16:12:17 +0300983In general, the :mod:`argparse` module assumes that flags like ``-f`` and ``--bar``
Ezio Melotti12125822011-04-16 23:04:51 +0300984indicate *optional* arguments, which can always be omitted at the command line.
Benjamin Peterson90c58022010-03-03 01:55:09 +0000985To make an option *required*, ``True`` can be specified for the ``required=``
Ezio Melottic69313a2011-04-22 01:29:13 +0300986keyword argument to :meth:`~ArgumentParser.add_argument`::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000987
988 >>> parser = argparse.ArgumentParser()
989 >>> parser.add_argument('--foo', required=True)
990 >>> parser.parse_args(['--foo', 'BAR'])
991 Namespace(foo='BAR')
992 >>> parser.parse_args([])
993 usage: argparse.py [-h] [--foo FOO]
994 argparse.py: error: option --foo is required
995
Ezio Melottic69313a2011-04-22 01:29:13 +0300996As the example shows, if an option is marked as ``required``,
997:meth:`~ArgumentParser.parse_args` will report an error if that option is not
998present at the command line.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000999
Benjamin Peterson90c58022010-03-03 01:55:09 +00001000.. note::
1001
1002 Required options are generally considered bad form because users expect
1003 *options* to be *optional*, and thus they should be avoided when possible.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001004
1005
1006help
1007^^^^
1008
Benjamin Peterson90c58022010-03-03 01:55:09 +00001009The ``help`` value is a string containing a brief description of the argument.
1010When a user requests help (usually by using ``-h`` or ``--help`` at the
Ezio Melotti12125822011-04-16 23:04:51 +03001011command line), these ``help`` descriptions will be displayed with each
Georg Brandld2decd92010-03-02 22:17:38 +00001012argument::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001013
1014 >>> parser = argparse.ArgumentParser(prog='frobble')
1015 >>> parser.add_argument('--foo', action='store_true',
1016 ... help='foo the bars before frobbling')
1017 >>> parser.add_argument('bar', nargs='+',
1018 ... help='one of the bars to be frobbled')
1019 >>> parser.parse_args('-h'.split())
1020 usage: frobble [-h] [--foo] bar [bar ...]
1021
1022 positional arguments:
1023 bar one of the bars to be frobbled
1024
1025 optional arguments:
1026 -h, --help show this help message and exit
1027 --foo foo the bars before frobbling
1028
1029The ``help`` strings can include various format specifiers to avoid repetition
1030of things like the program name or the argument default_. The available
1031specifiers include the program name, ``%(prog)s`` and most keyword arguments to
Ezio Melottic69313a2011-04-22 01:29:13 +03001032:meth:`~ArgumentParser.add_argument`, e.g. ``%(default)s``, ``%(type)s``, etc.::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001033
1034 >>> parser = argparse.ArgumentParser(prog='frobble')
1035 >>> parser.add_argument('bar', nargs='?', type=int, default=42,
1036 ... help='the bar to %(prog)s (default: %(default)s)')
1037 >>> parser.print_help()
1038 usage: frobble [-h] [bar]
1039
1040 positional arguments:
1041 bar the bar to frobble (default: 42)
1042
1043 optional arguments:
1044 -h, --help show this help message and exit
1045
1046
1047metavar
1048^^^^^^^
1049
Benjamin Peterson90c58022010-03-03 01:55:09 +00001050When :class:`ArgumentParser` generates help messages, it need some way to refer
Georg Brandld2decd92010-03-02 22:17:38 +00001051to each expected argument. By default, ArgumentParser objects use the dest_
Benjamin Petersona39e9662010-03-02 22:05:59 +00001052value as the "name" of each object. By default, for positional argument
1053actions, the dest_ value is used directly, and for optional argument actions,
Benjamin Peterson90c58022010-03-03 01:55:09 +00001054the dest_ value is uppercased. So, a single positional argument with
1055``dest='bar'`` will that argument will be referred to as ``bar``. A single
1056optional argument ``--foo`` that should be followed by a single command-line arg
1057will be referred to as ``FOO``. An example::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001058
1059 >>> parser = argparse.ArgumentParser()
1060 >>> parser.add_argument('--foo')
1061 >>> parser.add_argument('bar')
1062 >>> parser.parse_args('X --foo Y'.split())
1063 Namespace(bar='X', foo='Y')
1064 >>> parser.print_help()
1065 usage: [-h] [--foo FOO] bar
1066
1067 positional arguments:
1068 bar
1069
1070 optional arguments:
1071 -h, --help show this help message and exit
1072 --foo FOO
1073
Benjamin Peterson90c58022010-03-03 01:55:09 +00001074An alternative name can be specified with ``metavar``::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001075
1076 >>> parser = argparse.ArgumentParser()
1077 >>> parser.add_argument('--foo', metavar='YYY')
1078 >>> parser.add_argument('bar', metavar='XXX')
1079 >>> parser.parse_args('X --foo Y'.split())
1080 Namespace(bar='X', foo='Y')
1081 >>> parser.print_help()
1082 usage: [-h] [--foo YYY] XXX
1083
1084 positional arguments:
1085 XXX
1086
1087 optional arguments:
1088 -h, --help show this help message and exit
1089 --foo YYY
1090
1091Note that ``metavar`` only changes the *displayed* name - the name of the
Ezio Melottic69313a2011-04-22 01:29:13 +03001092attribute on the :meth:`~ArgumentParser.parse_args` object is still determined
1093by the dest_ value.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001094
1095Different values of ``nargs`` may cause the metavar to be used multiple times.
Benjamin Peterson90c58022010-03-03 01:55:09 +00001096Providing a tuple to ``metavar`` specifies a different display for each of the
1097arguments::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001098
1099 >>> parser = argparse.ArgumentParser(prog='PROG')
1100 >>> parser.add_argument('-x', nargs=2)
1101 >>> parser.add_argument('--foo', nargs=2, metavar=('bar', 'baz'))
1102 >>> parser.print_help()
1103 usage: PROG [-h] [-x X X] [--foo bar baz]
1104
1105 optional arguments:
1106 -h, --help show this help message and exit
1107 -x X X
1108 --foo bar baz
1109
1110
1111dest
1112^^^^
1113
Benjamin Peterson90c58022010-03-03 01:55:09 +00001114Most :class:`ArgumentParser` actions add some value as an attribute of the
Ezio Melottic69313a2011-04-22 01:29:13 +03001115object returned by :meth:`~ArgumentParser.parse_args`. The name of this
1116attribute is determined by the ``dest`` keyword argument of
1117:meth:`~ArgumentParser.add_argument`. For positional argument actions,
1118``dest`` is normally supplied as the first argument to
1119:meth:`~ArgumentParser.add_argument`::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001120
1121 >>> parser = argparse.ArgumentParser()
1122 >>> parser.add_argument('bar')
1123 >>> parser.parse_args('XXX'.split())
1124 Namespace(bar='XXX')
1125
1126For optional argument actions, the value of ``dest`` is normally inferred from
Benjamin Peterson90c58022010-03-03 01:55:09 +00001127the option strings. :class:`ArgumentParser` generates the value of ``dest`` by
Benjamin Petersona39e9662010-03-02 22:05:59 +00001128taking the first long option string and stripping away the initial ``'--'``
1129string. If no long option strings were supplied, ``dest`` will be derived from
1130the first short option string by stripping the initial ``'-'`` character. Any
Georg Brandld2decd92010-03-02 22:17:38 +00001131internal ``'-'`` characters will be converted to ``'_'`` characters to make sure
1132the string is a valid attribute name. The examples below illustrate this
Benjamin Petersona39e9662010-03-02 22:05:59 +00001133behavior::
1134
1135 >>> parser = argparse.ArgumentParser()
1136 >>> parser.add_argument('-f', '--foo-bar', '--foo')
1137 >>> parser.add_argument('-x', '-y')
1138 >>> parser.parse_args('-f 1 -x 2'.split())
1139 Namespace(foo_bar='1', x='2')
1140 >>> parser.parse_args('--foo 1 -y 2'.split())
1141 Namespace(foo_bar='1', x='2')
1142
Benjamin Peterson90c58022010-03-03 01:55:09 +00001143``dest`` allows a custom attribute name to be provided::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001144
1145 >>> parser = argparse.ArgumentParser()
1146 >>> parser.add_argument('--foo', dest='bar')
1147 >>> parser.parse_args('--foo XXX'.split())
1148 Namespace(bar='XXX')
1149
1150
1151The parse_args() method
1152-----------------------
1153
Georg Brandlb8d0e362010-11-26 07:53:50 +00001154.. method:: ArgumentParser.parse_args(args=None, namespace=None)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001155
Benjamin Peterson90c58022010-03-03 01:55:09 +00001156 Convert argument strings to objects and assign them as attributes of the
Georg Brandld2decd92010-03-02 22:17:38 +00001157 namespace. Return the populated namespace.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001158
1159 Previous calls to :meth:`add_argument` determine exactly what objects are
1160 created and how they are assigned. See the documentation for
1161 :meth:`add_argument` for details.
1162
Georg Brandld2decd92010-03-02 22:17:38 +00001163 By default, the arg strings are taken from :data:`sys.argv`, and a new empty
Benjamin Peterson90c58022010-03-03 01:55:09 +00001164 :class:`Namespace` object is created for the attributes.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001165
Georg Brandlb8d0e362010-11-26 07:53:50 +00001166
Benjamin Petersona39e9662010-03-02 22:05:59 +00001167Option value syntax
1168^^^^^^^^^^^^^^^^^^^
1169
Ezio Melottic69313a2011-04-22 01:29:13 +03001170The :meth:`~ArgumentParser.parse_args` method supports several ways of
1171specifying the value of an option (if it takes one). In the simplest case, the
1172option and its value are passed as two separate arguments::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001173
1174 >>> parser = argparse.ArgumentParser(prog='PROG')
1175 >>> parser.add_argument('-x')
1176 >>> parser.add_argument('--foo')
1177 >>> parser.parse_args('-x X'.split())
1178 Namespace(foo=None, x='X')
1179 >>> parser.parse_args('--foo FOO'.split())
1180 Namespace(foo='FOO', x=None)
1181
Benjamin Peterson90c58022010-03-03 01:55:09 +00001182For long options (options with names longer than a single character), the option
Ezio Melotti12125822011-04-16 23:04:51 +03001183and value can also be passed as a single command-line argument, using ``=`` to
Georg Brandld2decd92010-03-02 22:17:38 +00001184separate them::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001185
1186 >>> parser.parse_args('--foo=FOO'.split())
1187 Namespace(foo='FOO', x=None)
1188
Benjamin Peterson90c58022010-03-03 01:55:09 +00001189For short options (options only one character long), the option and its value
1190can be concatenated::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001191
1192 >>> parser.parse_args('-xX'.split())
1193 Namespace(foo=None, x='X')
1194
Benjamin Peterson90c58022010-03-03 01:55:09 +00001195Several short options can be joined together, using only a single ``-`` prefix,
1196as long as only the last option (or none of them) requires a value::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001197
1198 >>> parser = argparse.ArgumentParser(prog='PROG')
1199 >>> parser.add_argument('-x', action='store_true')
1200 >>> parser.add_argument('-y', action='store_true')
1201 >>> parser.add_argument('-z')
1202 >>> parser.parse_args('-xyzZ'.split())
1203 Namespace(x=True, y=True, z='Z')
1204
1205
1206Invalid arguments
1207^^^^^^^^^^^^^^^^^
1208
Ezio Melottic69313a2011-04-22 01:29:13 +03001209While parsing the command line, :meth:`~ArgumentParser.parse_args` checks for a
1210variety of errors, including ambiguous options, invalid types, invalid options,
1211wrong number of positional arguments, etc. When it encounters such an error,
1212it exits and prints the error along with a usage message::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001213
1214 >>> parser = argparse.ArgumentParser(prog='PROG')
1215 >>> parser.add_argument('--foo', type=int)
1216 >>> parser.add_argument('bar', nargs='?')
1217
1218 >>> # invalid type
1219 >>> parser.parse_args(['--foo', 'spam'])
1220 usage: PROG [-h] [--foo FOO] [bar]
1221 PROG: error: argument --foo: invalid int value: 'spam'
1222
1223 >>> # invalid option
1224 >>> parser.parse_args(['--bar'])
1225 usage: PROG [-h] [--foo FOO] [bar]
1226 PROG: error: no such option: --bar
1227
1228 >>> # wrong number of arguments
1229 >>> parser.parse_args(['spam', 'badger'])
1230 usage: PROG [-h] [--foo FOO] [bar]
1231 PROG: error: extra arguments found: badger
1232
1233
1234Arguments containing ``"-"``
1235^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1236
Ezio Melottic69313a2011-04-22 01:29:13 +03001237The :meth:`~ArgumentParser.parse_args` method attempts to give errors whenever
1238the user has clearly made a mistake, but some situations are inherently
1239ambiguous. For example, the command-line arg ``'-1'`` could either be an
1240attempt to specify an option or an attempt to provide a positional argument.
1241The :meth:`~ArgumentParser.parse_args` method is cautious here: positional
1242arguments may only begin with ``'-'`` if they look like negative numbers and
1243there are no options in the parser that look like negative numbers::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001244
1245 >>> parser = argparse.ArgumentParser(prog='PROG')
1246 >>> parser.add_argument('-x')
1247 >>> parser.add_argument('foo', nargs='?')
1248
1249 >>> # no negative number options, so -1 is a positional argument
1250 >>> parser.parse_args(['-x', '-1'])
1251 Namespace(foo=None, x='-1')
1252
1253 >>> # no negative number options, so -1 and -5 are positional arguments
1254 >>> parser.parse_args(['-x', '-1', '-5'])
1255 Namespace(foo='-5', x='-1')
1256
1257 >>> parser = argparse.ArgumentParser(prog='PROG')
1258 >>> parser.add_argument('-1', dest='one')
1259 >>> parser.add_argument('foo', nargs='?')
1260
1261 >>> # negative number options present, so -1 is an option
1262 >>> parser.parse_args(['-1', 'X'])
1263 Namespace(foo=None, one='X')
1264
1265 >>> # negative number options present, so -2 is an option
1266 >>> parser.parse_args(['-2'])
1267 usage: PROG [-h] [-1 ONE] [foo]
1268 PROG: error: no such option: -2
1269
1270 >>> # negative number options present, so both -1s are options
1271 >>> parser.parse_args(['-1', '-1'])
1272 usage: PROG [-h] [-1 ONE] [foo]
1273 PROG: error: argument -1: expected one argument
1274
1275If you have positional arguments that must begin with ``'-'`` and don't look
1276like negative numbers, you can insert the pseudo-argument ``'--'`` which tells
Ezio Melottic69313a2011-04-22 01:29:13 +03001277:meth:`~ArgumentParser.parse_args` that everything after that is a positional
1278argument::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001279
1280 >>> parser.parse_args(['--', '-f'])
1281 Namespace(foo='-f', one=None)
1282
1283
1284Argument abbreviations
1285^^^^^^^^^^^^^^^^^^^^^^
1286
Ezio Melottic69313a2011-04-22 01:29:13 +03001287The :meth:`~ArgumentParser.parse_args` method allows long options to be
1288abbreviated if the abbreviation is unambiguous::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001289
1290 >>> parser = argparse.ArgumentParser(prog='PROG')
1291 >>> parser.add_argument('-bacon')
1292 >>> parser.add_argument('-badger')
1293 >>> parser.parse_args('-bac MMM'.split())
1294 Namespace(bacon='MMM', badger=None)
1295 >>> parser.parse_args('-bad WOOD'.split())
1296 Namespace(bacon=None, badger='WOOD')
1297 >>> parser.parse_args('-ba BA'.split())
1298 usage: PROG [-h] [-bacon BACON] [-badger BADGER]
1299 PROG: error: ambiguous option: -ba could match -badger, -bacon
1300
Benjamin Peterson90c58022010-03-03 01:55:09 +00001301An error is produced for arguments that could produce more than one options.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001302
1303
1304Beyond ``sys.argv``
1305^^^^^^^^^^^^^^^^^^^
1306
Georg Brandld2decd92010-03-02 22:17:38 +00001307Sometimes it may be useful to have an ArgumentParser parse args other than those
1308of :data:`sys.argv`. This can be accomplished by passing a list of strings to
Ezio Melottic69313a2011-04-22 01:29:13 +03001309:meth:`~ArgumentParser.parse_args`. This is useful for testing at the
1310interactive prompt::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001311
1312 >>> parser = argparse.ArgumentParser()
1313 >>> parser.add_argument(
1314 ... 'integers', metavar='int', type=int, choices=xrange(10),
1315 ... nargs='+', help='an integer in the range 0..9')
1316 >>> parser.add_argument(
1317 ... '--sum', dest='accumulate', action='store_const', const=sum,
1318 ... default=max, help='sum the integers (default: find the max)')
1319 >>> parser.parse_args(['1', '2', '3', '4'])
1320 Namespace(accumulate=<built-in function max>, integers=[1, 2, 3, 4])
1321 >>> parser.parse_args('1 2 3 4 --sum'.split())
1322 Namespace(accumulate=<built-in function sum>, integers=[1, 2, 3, 4])
1323
1324
Steven Bethard3f69a052011-03-26 19:59:02 +01001325The Namespace object
1326^^^^^^^^^^^^^^^^^^^^
1327
Éric Araujof0d44bc2011-07-29 17:59:17 +02001328.. class:: Namespace
1329
1330 Simple class used by default by :meth:`~ArgumentParser.parse_args` to create
1331 an object holding attributes and return it.
1332
1333This class is deliberately simple, just an :class:`object` subclass with a
1334readable string representation. If you prefer to have dict-like view of the
1335attributes, you can use the standard Python idiom, :func:`vars`::
Steven Bethard3f69a052011-03-26 19:59:02 +01001336
1337 >>> parser = argparse.ArgumentParser()
1338 >>> parser.add_argument('--foo')
1339 >>> args = parser.parse_args(['--foo', 'BAR'])
1340 >>> vars(args)
1341 {'foo': 'BAR'}
Benjamin Petersona39e9662010-03-02 22:05:59 +00001342
Benjamin Peterson90c58022010-03-03 01:55:09 +00001343It may also be useful to have an :class:`ArgumentParser` assign attributes to an
Steven Bethard3f69a052011-03-26 19:59:02 +01001344already existing object, rather than a new :class:`Namespace` object. This can
1345be achieved by specifying the ``namespace=`` keyword argument::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001346
1347 >>> class C(object):
1348 ... pass
1349 ...
1350 >>> c = C()
1351 >>> parser = argparse.ArgumentParser()
1352 >>> parser.add_argument('--foo')
1353 >>> parser.parse_args(args=['--foo', 'BAR'], namespace=c)
1354 >>> c.foo
1355 'BAR'
1356
1357
1358Other utilities
1359---------------
1360
1361Sub-commands
1362^^^^^^^^^^^^
1363
Benjamin Peterson90c58022010-03-03 01:55:09 +00001364.. method:: ArgumentParser.add_subparsers()
Benjamin Petersona39e9662010-03-02 22:05:59 +00001365
Benjamin Peterson90c58022010-03-03 01:55:09 +00001366 Many programs split up their functionality into a number of sub-commands,
Georg Brandld2decd92010-03-02 22:17:38 +00001367 for example, the ``svn`` program can invoke sub-commands like ``svn
Benjamin Peterson90c58022010-03-03 01:55:09 +00001368 checkout``, ``svn update``, and ``svn commit``. Splitting up functionality
Georg Brandld2decd92010-03-02 22:17:38 +00001369 this way can be a particularly good idea when a program performs several
1370 different functions which require different kinds of command-line arguments.
Benjamin Peterson90c58022010-03-03 01:55:09 +00001371 :class:`ArgumentParser` supports the creation of such sub-commands with the
Georg Brandld2decd92010-03-02 22:17:38 +00001372 :meth:`add_subparsers` method. The :meth:`add_subparsers` method is normally
1373 called with no arguments and returns an special action object. This object
Ezio Melottic69313a2011-04-22 01:29:13 +03001374 has a single method, :meth:`~ArgumentParser.add_parser`, which takes a
1375 command name and any :class:`ArgumentParser` constructor arguments, and
1376 returns an :class:`ArgumentParser` object that can be modified as usual.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001377
1378 Some example usage::
1379
1380 >>> # create the top-level parser
1381 >>> parser = argparse.ArgumentParser(prog='PROG')
1382 >>> parser.add_argument('--foo', action='store_true', help='foo help')
1383 >>> subparsers = parser.add_subparsers(help='sub-command help')
1384 >>>
1385 >>> # create the parser for the "a" command
1386 >>> parser_a = subparsers.add_parser('a', help='a help')
1387 >>> parser_a.add_argument('bar', type=int, help='bar help')
1388 >>>
1389 >>> # create the parser for the "b" command
1390 >>> parser_b = subparsers.add_parser('b', help='b help')
1391 >>> parser_b.add_argument('--baz', choices='XYZ', help='baz help')
1392 >>>
1393 >>> # parse some arg lists
1394 >>> parser.parse_args(['a', '12'])
1395 Namespace(bar=12, foo=False)
1396 >>> parser.parse_args(['--foo', 'b', '--baz', 'Z'])
1397 Namespace(baz='Z', foo=True)
1398
1399 Note that the object returned by :meth:`parse_args` will only contain
1400 attributes for the main parser and the subparser that was selected by the
1401 command line (and not any other subparsers). So in the example above, when
Georg Brandld2decd92010-03-02 22:17:38 +00001402 the ``"a"`` command is specified, only the ``foo`` and ``bar`` attributes are
1403 present, and when the ``"b"`` command is specified, only the ``foo`` and
Benjamin Petersona39e9662010-03-02 22:05:59 +00001404 ``baz`` attributes are present.
1405
1406 Similarly, when a help message is requested from a subparser, only the help
Georg Brandld2decd92010-03-02 22:17:38 +00001407 for that particular parser will be printed. The help message will not
Benjamin Peterson90c58022010-03-03 01:55:09 +00001408 include parent parser or sibling parser messages. (A help message for each
1409 subparser command, however, can be given by supplying the ``help=`` argument
Ezio Melottic69313a2011-04-22 01:29:13 +03001410 to :meth:`add_parser` as above.)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001411
1412 ::
1413
1414 >>> parser.parse_args(['--help'])
1415 usage: PROG [-h] [--foo] {a,b} ...
1416
1417 positional arguments:
1418 {a,b} sub-command help
1419 a a help
1420 b b help
1421
1422 optional arguments:
1423 -h, --help show this help message and exit
1424 --foo foo help
1425
1426 >>> parser.parse_args(['a', '--help'])
1427 usage: PROG a [-h] bar
1428
1429 positional arguments:
1430 bar bar help
1431
1432 optional arguments:
1433 -h, --help show this help message and exit
1434
1435 >>> parser.parse_args(['b', '--help'])
1436 usage: PROG b [-h] [--baz {X,Y,Z}]
1437
1438 optional arguments:
1439 -h, --help show this help message and exit
1440 --baz {X,Y,Z} baz help
1441
Georg Brandld2decd92010-03-02 22:17:38 +00001442 The :meth:`add_subparsers` method also supports ``title`` and ``description``
1443 keyword arguments. When either is present, the subparser's commands will
1444 appear in their own group in the help output. For example::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001445
1446 >>> parser = argparse.ArgumentParser()
1447 >>> subparsers = parser.add_subparsers(title='subcommands',
1448 ... description='valid subcommands',
1449 ... help='additional help')
1450 >>> subparsers.add_parser('foo')
1451 >>> subparsers.add_parser('bar')
1452 >>> parser.parse_args(['-h'])
1453 usage: [-h] {foo,bar} ...
1454
1455 optional arguments:
1456 -h, --help show this help message and exit
1457
1458 subcommands:
1459 valid subcommands
1460
1461 {foo,bar} additional help
1462
1463
Georg Brandld2decd92010-03-02 22:17:38 +00001464 One particularly effective way of handling sub-commands is to combine the use
1465 of the :meth:`add_subparsers` method with calls to :meth:`set_defaults` so
1466 that each subparser knows which Python function it should execute. For
Benjamin Petersona39e9662010-03-02 22:05:59 +00001467 example::
1468
1469 >>> # sub-command functions
1470 >>> def foo(args):
1471 ... print args.x * args.y
1472 ...
1473 >>> def bar(args):
1474 ... print '((%s))' % args.z
1475 ...
1476 >>> # create the top-level parser
1477 >>> parser = argparse.ArgumentParser()
1478 >>> subparsers = parser.add_subparsers()
1479 >>>
1480 >>> # create the parser for the "foo" command
1481 >>> parser_foo = subparsers.add_parser('foo')
1482 >>> parser_foo.add_argument('-x', type=int, default=1)
1483 >>> parser_foo.add_argument('y', type=float)
1484 >>> parser_foo.set_defaults(func=foo)
1485 >>>
1486 >>> # create the parser for the "bar" command
1487 >>> parser_bar = subparsers.add_parser('bar')
1488 >>> parser_bar.add_argument('z')
1489 >>> parser_bar.set_defaults(func=bar)
1490 >>>
1491 >>> # parse the args and call whatever function was selected
1492 >>> args = parser.parse_args('foo 1 -x 2'.split())
1493 >>> args.func(args)
1494 2.0
1495 >>>
1496 >>> # parse the args and call whatever function was selected
1497 >>> args = parser.parse_args('bar XYZYX'.split())
1498 >>> args.func(args)
1499 ((XYZYX))
1500
Benjamin Peterson90c58022010-03-03 01:55:09 +00001501 This way, you can let :meth:`parse_args` does the job of calling the
1502 appropriate function after argument parsing is complete. Associating
1503 functions with actions like this is typically the easiest way to handle the
1504 different actions for each of your subparsers. However, if it is necessary
1505 to check the name of the subparser that was invoked, the ``dest`` keyword
1506 argument to the :meth:`add_subparsers` call will work::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001507
1508 >>> parser = argparse.ArgumentParser()
1509 >>> subparsers = parser.add_subparsers(dest='subparser_name')
1510 >>> subparser1 = subparsers.add_parser('1')
1511 >>> subparser1.add_argument('-x')
1512 >>> subparser2 = subparsers.add_parser('2')
1513 >>> subparser2.add_argument('y')
1514 >>> parser.parse_args(['2', 'frobble'])
1515 Namespace(subparser_name='2', y='frobble')
1516
1517
1518FileType objects
1519^^^^^^^^^^^^^^^^
1520
1521.. class:: FileType(mode='r', bufsize=None)
1522
1523 The :class:`FileType` factory creates objects that can be passed to the type
Benjamin Peterson90c58022010-03-03 01:55:09 +00001524 argument of :meth:`ArgumentParser.add_argument`. Arguments that have
1525 :class:`FileType` objects as their type will open command-line args as files
1526 with the requested modes and buffer sizes:
Benjamin Petersona39e9662010-03-02 22:05:59 +00001527
1528 >>> parser = argparse.ArgumentParser()
1529 >>> parser.add_argument('--output', type=argparse.FileType('wb', 0))
1530 >>> parser.parse_args(['--output', 'out'])
1531 Namespace(output=<open file 'out', mode 'wb' at 0x...>)
1532
1533 FileType objects understand the pseudo-argument ``'-'`` and automatically
1534 convert this into ``sys.stdin`` for readable :class:`FileType` objects and
1535 ``sys.stdout`` for writable :class:`FileType` objects:
1536
1537 >>> parser = argparse.ArgumentParser()
1538 >>> parser.add_argument('infile', type=argparse.FileType('r'))
1539 >>> parser.parse_args(['-'])
1540 Namespace(infile=<open file '<stdin>', mode 'r' at 0x...>)
1541
1542
1543Argument groups
1544^^^^^^^^^^^^^^^
1545
Georg Brandlb8d0e362010-11-26 07:53:50 +00001546.. method:: ArgumentParser.add_argument_group(title=None, description=None)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001547
Benjamin Peterson90c58022010-03-03 01:55:09 +00001548 By default, :class:`ArgumentParser` groups command-line arguments into
Benjamin Petersona39e9662010-03-02 22:05:59 +00001549 "positional arguments" and "optional arguments" when displaying help
1550 messages. When there is a better conceptual grouping of arguments than this
1551 default one, appropriate groups can be created using the
1552 :meth:`add_argument_group` method::
1553
1554 >>> parser = argparse.ArgumentParser(prog='PROG', add_help=False)
1555 >>> group = parser.add_argument_group('group')
1556 >>> group.add_argument('--foo', help='foo help')
1557 >>> group.add_argument('bar', help='bar help')
1558 >>> parser.print_help()
1559 usage: PROG [--foo FOO] bar
1560
1561 group:
1562 bar bar help
1563 --foo FOO foo help
1564
1565 The :meth:`add_argument_group` method returns an argument group object which
Benjamin Peterson90c58022010-03-03 01:55:09 +00001566 has an :meth:`~ArgumentParser.add_argument` method just like a regular
1567 :class:`ArgumentParser`. When an argument is added to the group, the parser
1568 treats it just like a normal argument, but displays the argument in a
1569 separate group for help messages. The :meth:`add_argument_group` method
Georg Brandlb8d0e362010-11-26 07:53:50 +00001570 accepts *title* and *description* arguments which can be used to
Benjamin Peterson90c58022010-03-03 01:55:09 +00001571 customize this display::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001572
1573 >>> parser = argparse.ArgumentParser(prog='PROG', add_help=False)
1574 >>> group1 = parser.add_argument_group('group1', 'group1 description')
1575 >>> group1.add_argument('foo', help='foo help')
1576 >>> group2 = parser.add_argument_group('group2', 'group2 description')
1577 >>> group2.add_argument('--bar', help='bar help')
1578 >>> parser.print_help()
1579 usage: PROG [--bar BAR] foo
1580
1581 group1:
1582 group1 description
1583
1584 foo foo help
1585
1586 group2:
1587 group2 description
1588
1589 --bar BAR bar help
1590
Benjamin Peterson90c58022010-03-03 01:55:09 +00001591 Note that any arguments not your user defined groups will end up back in the
1592 usual "positional arguments" and "optional arguments" sections.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001593
1594
1595Mutual exclusion
1596^^^^^^^^^^^^^^^^
1597
Georg Brandlb8d0e362010-11-26 07:53:50 +00001598.. method:: add_mutually_exclusive_group(required=False)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001599
Ezio Melotti01b600c2011-04-21 16:12:17 +03001600 Create a mutually exclusive group. :mod:`argparse` will make sure that only
1601 one of the arguments in the mutually exclusive group was present on the
1602 command line::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001603
1604 >>> parser = argparse.ArgumentParser(prog='PROG')
1605 >>> group = parser.add_mutually_exclusive_group()
1606 >>> group.add_argument('--foo', action='store_true')
1607 >>> group.add_argument('--bar', action='store_false')
1608 >>> parser.parse_args(['--foo'])
1609 Namespace(bar=True, foo=True)
1610 >>> parser.parse_args(['--bar'])
1611 Namespace(bar=False, foo=False)
1612 >>> parser.parse_args(['--foo', '--bar'])
1613 usage: PROG [-h] [--foo | --bar]
1614 PROG: error: argument --bar: not allowed with argument --foo
1615
Georg Brandlb8d0e362010-11-26 07:53:50 +00001616 The :meth:`add_mutually_exclusive_group` method also accepts a *required*
Benjamin Petersona39e9662010-03-02 22:05:59 +00001617 argument, to indicate that at least one of the mutually exclusive arguments
1618 is required::
1619
1620 >>> parser = argparse.ArgumentParser(prog='PROG')
1621 >>> group = parser.add_mutually_exclusive_group(required=True)
1622 >>> group.add_argument('--foo', action='store_true')
1623 >>> group.add_argument('--bar', action='store_false')
1624 >>> parser.parse_args([])
1625 usage: PROG [-h] (--foo | --bar)
1626 PROG: error: one of the arguments --foo --bar is required
1627
1628 Note that currently mutually exclusive argument groups do not support the
Ezio Melottic69313a2011-04-22 01:29:13 +03001629 *title* and *description* arguments of
1630 :meth:`~ArgumentParser.add_argument_group`.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001631
1632
1633Parser defaults
1634^^^^^^^^^^^^^^^
1635
Benjamin Peterson90c58022010-03-03 01:55:09 +00001636.. method:: ArgumentParser.set_defaults(**kwargs)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001637
Georg Brandld2decd92010-03-02 22:17:38 +00001638 Most of the time, the attributes of the object returned by :meth:`parse_args`
1639 will be fully determined by inspecting the command-line args and the argument
Ezio Melottic69313a2011-04-22 01:29:13 +03001640 actions. :meth:`set_defaults` allows some additional
Ezio Melotti12125822011-04-16 23:04:51 +03001641 attributes that are determined without any inspection of the command line to
Benjamin Petersonc516d192010-03-03 02:04:24 +00001642 be added::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001643
1644 >>> parser = argparse.ArgumentParser()
1645 >>> parser.add_argument('foo', type=int)
1646 >>> parser.set_defaults(bar=42, baz='badger')
1647 >>> parser.parse_args(['736'])
1648 Namespace(bar=42, baz='badger', foo=736)
1649
Benjamin Peterson90c58022010-03-03 01:55:09 +00001650 Note that parser-level defaults always override argument-level defaults::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001651
1652 >>> parser = argparse.ArgumentParser()
1653 >>> parser.add_argument('--foo', default='bar')
1654 >>> parser.set_defaults(foo='spam')
1655 >>> parser.parse_args([])
1656 Namespace(foo='spam')
1657
Benjamin Peterson90c58022010-03-03 01:55:09 +00001658 Parser-level defaults can be particularly useful when working with multiple
1659 parsers. See the :meth:`~ArgumentParser.add_subparsers` method for an
1660 example of this type.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001661
Benjamin Peterson90c58022010-03-03 01:55:09 +00001662.. method:: ArgumentParser.get_default(dest)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001663
1664 Get the default value for a namespace attribute, as set by either
Benjamin Peterson90c58022010-03-03 01:55:09 +00001665 :meth:`~ArgumentParser.add_argument` or by
1666 :meth:`~ArgumentParser.set_defaults`::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001667
1668 >>> parser = argparse.ArgumentParser()
1669 >>> parser.add_argument('--foo', default='badger')
1670 >>> parser.get_default('foo')
1671 'badger'
1672
1673
1674Printing help
1675^^^^^^^^^^^^^
1676
Ezio Melottic69313a2011-04-22 01:29:13 +03001677In most typical applications, :meth:`~ArgumentParser.parse_args` will take
1678care of formatting and printing any usage or error messages. However, several
1679formatting methods are available:
Benjamin Petersona39e9662010-03-02 22:05:59 +00001680
Georg Brandlb8d0e362010-11-26 07:53:50 +00001681.. method:: ArgumentParser.print_usage(file=None)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001682
1683 Print a brief description of how the :class:`ArgumentParser` should be
R. David Murray561b96f2011-02-11 17:25:54 +00001684 invoked on the command line. If *file* is ``None``, :data:`sys.stdout` is
Benjamin Petersona39e9662010-03-02 22:05:59 +00001685 assumed.
1686
Georg Brandlb8d0e362010-11-26 07:53:50 +00001687.. method:: ArgumentParser.print_help(file=None)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001688
1689 Print a help message, including the program usage and information about the
Georg Brandlb8d0e362010-11-26 07:53:50 +00001690 arguments registered with the :class:`ArgumentParser`. If *file* is
R. David Murray561b96f2011-02-11 17:25:54 +00001691 ``None``, :data:`sys.stdout` is assumed.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001692
1693There are also variants of these methods that simply return a string instead of
1694printing it:
1695
Georg Brandlb8d0e362010-11-26 07:53:50 +00001696.. method:: ArgumentParser.format_usage()
Benjamin Petersona39e9662010-03-02 22:05:59 +00001697
1698 Return a string containing a brief description of how the
1699 :class:`ArgumentParser` should be invoked on the command line.
1700
Georg Brandlb8d0e362010-11-26 07:53:50 +00001701.. method:: ArgumentParser.format_help()
Benjamin Petersona39e9662010-03-02 22:05:59 +00001702
1703 Return a string containing a help message, including the program usage and
1704 information about the arguments registered with the :class:`ArgumentParser`.
1705
1706
Benjamin Petersona39e9662010-03-02 22:05:59 +00001707Partial parsing
1708^^^^^^^^^^^^^^^
1709
Georg Brandlb8d0e362010-11-26 07:53:50 +00001710.. method:: ArgumentParser.parse_known_args(args=None, namespace=None)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001711
Ezio Melotti12125822011-04-16 23:04:51 +03001712Sometimes a script may only parse a few of the command-line arguments, passing
Benjamin Petersona39e9662010-03-02 22:05:59 +00001713the remaining arguments on to another script or program. In these cases, the
Ezio Melottic69313a2011-04-22 01:29:13 +03001714:meth:`~ArgumentParser.parse_known_args` method can be useful. It works much like
Benjamin Peterson90c58022010-03-03 01:55:09 +00001715:meth:`~ArgumentParser.parse_args` except that it does not produce an error when
1716extra arguments are present. Instead, it returns a two item tuple containing
1717the populated namespace and the list of remaining argument strings.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001718
1719::
1720
1721 >>> parser = argparse.ArgumentParser()
1722 >>> parser.add_argument('--foo', action='store_true')
1723 >>> parser.add_argument('bar')
1724 >>> parser.parse_known_args(['--foo', '--badger', 'BAR', 'spam'])
1725 (Namespace(bar='BAR', foo=True), ['--badger', 'spam'])
1726
1727
1728Customizing file parsing
1729^^^^^^^^^^^^^^^^^^^^^^^^
1730
Benjamin Peterson90c58022010-03-03 01:55:09 +00001731.. method:: ArgumentParser.convert_arg_line_to_args(arg_line)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001732
Georg Brandlb8d0e362010-11-26 07:53:50 +00001733 Arguments that are read from a file (see the *fromfile_prefix_chars*
Benjamin Petersona39e9662010-03-02 22:05:59 +00001734 keyword argument to the :class:`ArgumentParser` constructor) are read one
Benjamin Peterson90c58022010-03-03 01:55:09 +00001735 argument per line. :meth:`convert_arg_line_to_args` can be overriden for
1736 fancier reading.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001737
Georg Brandlb8d0e362010-11-26 07:53:50 +00001738 This method takes a single argument *arg_line* which is a string read from
Benjamin Petersona39e9662010-03-02 22:05:59 +00001739 the argument file. It returns a list of arguments parsed from this string.
1740 The method is called once per line read from the argument file, in order.
1741
Georg Brandld2decd92010-03-02 22:17:38 +00001742 A useful override of this method is one that treats each space-separated word
1743 as an argument::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001744
1745 def convert_arg_line_to_args(self, arg_line):
1746 for arg in arg_line.split():
1747 if not arg.strip():
1748 continue
1749 yield arg
1750
1751
Georg Brandlb8d0e362010-11-26 07:53:50 +00001752Exiting methods
1753^^^^^^^^^^^^^^^
1754
1755.. method:: ArgumentParser.exit(status=0, message=None)
1756
1757 This method terminates the program, exiting with the specified *status*
1758 and, if given, it prints a *message* before that.
1759
1760.. method:: ArgumentParser.error(message)
1761
1762 This method prints a usage message including the *message* to the
Senthil Kumaranc1ee4ef2011-08-03 07:43:52 +08001763 standard error and terminates the program with a status code of 2.
Georg Brandlb8d0e362010-11-26 07:53:50 +00001764
1765
Georg Brandl58df6792010-07-03 10:25:47 +00001766.. _argparse-from-optparse:
1767
Benjamin Petersona39e9662010-03-02 22:05:59 +00001768Upgrading optparse code
1769-----------------------
1770
Ezio Melottic69313a2011-04-22 01:29:13 +03001771Originally, the :mod:`argparse` module had attempted to maintain compatibility
Ezio Melotti01b600c2011-04-21 16:12:17 +03001772with :mod:`optparse`. However, :mod:`optparse` was difficult to extend
1773transparently, particularly with the changes required to support the new
1774``nargs=`` specifiers and better usage messages. When most everything in
1775:mod:`optparse` had either been copy-pasted over or monkey-patched, it no
1776longer seemed practical to try to maintain the backwards compatibility.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001777
Ezio Melotti01b600c2011-04-21 16:12:17 +03001778A partial upgrade path from :mod:`optparse` to :mod:`argparse`:
Benjamin Petersona39e9662010-03-02 22:05:59 +00001779
Ezio Melottic69313a2011-04-22 01:29:13 +03001780* Replace all :meth:`optparse.OptionParser.add_option` calls with
1781 :meth:`ArgumentParser.add_argument` calls.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001782
Georg Brandld2decd92010-03-02 22:17:38 +00001783* Replace ``options, args = parser.parse_args()`` with ``args =
Georg Brandl585bbb92011-01-09 09:33:09 +00001784 parser.parse_args()`` and add additional :meth:`ArgumentParser.add_argument`
1785 calls for the positional arguments.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001786
1787* Replace callback actions and the ``callback_*`` keyword arguments with
1788 ``type`` or ``action`` arguments.
1789
1790* Replace string names for ``type`` keyword arguments with the corresponding
1791 type objects (e.g. int, float, complex, etc).
1792
Benjamin Peterson90c58022010-03-03 01:55:09 +00001793* Replace :class:`optparse.Values` with :class:`Namespace` and
1794 :exc:`optparse.OptionError` and :exc:`optparse.OptionValueError` with
1795 :exc:`ArgumentError`.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001796
Georg Brandld2decd92010-03-02 22:17:38 +00001797* Replace strings with implicit arguments such as ``%default`` or ``%prog`` with
Ezio Melotti2eab88e2011-04-21 15:26:46 +03001798 the standard Python syntax to use dictionaries to format strings, that is,
Georg Brandld2decd92010-03-02 22:17:38 +00001799 ``%(default)s`` and ``%(prog)s``.
Steven Bethard74bd9cf2010-05-24 02:38:00 +00001800
1801* Replace the OptionParser constructor ``version`` argument with a call to
1802 ``parser.add_argument('--version', action='version', version='<the version>')``