blob: b37b43fc1026046ee26c44a31be65a5eb557a53d [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
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
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.
109In most cases, this means a simple 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
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
Steven Bethard5e0062d2011-03-26 21:50:38 +0100348.. note::
349 You must fully initialize the parsers before passing them via ``parents=``.
350 If you change the parent parsers after the child parser, those changes will
351 not be reflected in the child.
352
Benjamin Petersona39e9662010-03-02 22:05:59 +0000353
354formatter_class
355^^^^^^^^^^^^^^^
356
Benjamin Peterson90c58022010-03-03 01:55:09 +0000357:class:`ArgumentParser` objects allow the help formatting to be customized by
358specifying an alternate formatting class. Currently, there are three such
359classes: :class:`argparse.RawDescriptionHelpFormatter`,
Georg Brandld2decd92010-03-02 22:17:38 +0000360:class:`argparse.RawTextHelpFormatter` and
361:class:`argparse.ArgumentDefaultsHelpFormatter`. The first two allow more
362control over how textual descriptions are displayed, while the last
363automatically adds information about argument default values.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000364
Benjamin Peterson90c58022010-03-03 01:55:09 +0000365By default, :class:`ArgumentParser` objects line-wrap the description_ and
366epilog_ texts in command-line help messages::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000367
368 >>> parser = argparse.ArgumentParser(
369 ... prog='PROG',
370 ... description='''this description
371 ... was indented weird
372 ... but that is okay''',
373 ... epilog='''
374 ... likewise for this epilog whose whitespace will
375 ... be cleaned up and whose words will be wrapped
376 ... across a couple lines''')
377 >>> parser.print_help()
378 usage: PROG [-h]
379
380 this description was indented weird but that is okay
381
382 optional arguments:
383 -h, --help show this help message and exit
384
385 likewise for this epilog whose whitespace will be cleaned up and whose words
386 will be wrapped across a couple lines
387
Benjamin Peterson90c58022010-03-03 01:55:09 +0000388Passing :class:`argparse.RawDescriptionHelpFormatter` as ``formatter_class=``
Benjamin Petersonc516d192010-03-03 02:04:24 +0000389indicates that description_ and epilog_ are already correctly formatted and
Benjamin Peterson90c58022010-03-03 01:55:09 +0000390should not be line-wrapped::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000391
392 >>> parser = argparse.ArgumentParser(
393 ... prog='PROG',
394 ... formatter_class=argparse.RawDescriptionHelpFormatter,
395 ... description=textwrap.dedent('''\
396 ... Please do not mess up this text!
397 ... --------------------------------
398 ... I have indented it
399 ... exactly the way
400 ... I want it
401 ... '''))
402 >>> parser.print_help()
403 usage: PROG [-h]
404
405 Please do not mess up this text!
406 --------------------------------
407 I have indented it
408 exactly the way
409 I want it
410
411 optional arguments:
412 -h, --help show this help message and exit
413
Benjamin Peterson90c58022010-03-03 01:55:09 +0000414:class:`RawTextHelpFormatter` maintains whitespace for all sorts of help text
415including argument descriptions.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000416
Benjamin Peterson90c58022010-03-03 01:55:09 +0000417The other formatter class available, :class:`ArgumentDefaultsHelpFormatter`,
Georg Brandld2decd92010-03-02 22:17:38 +0000418will add information about the default value of each of the arguments::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000419
420 >>> parser = argparse.ArgumentParser(
421 ... prog='PROG',
422 ... formatter_class=argparse.ArgumentDefaultsHelpFormatter)
423 >>> parser.add_argument('--foo', type=int, default=42, help='FOO!')
424 >>> parser.add_argument('bar', nargs='*', default=[1, 2, 3], help='BAR!')
425 >>> parser.print_help()
426 usage: PROG [-h] [--foo FOO] [bar [bar ...]]
427
428 positional arguments:
429 bar BAR! (default: [1, 2, 3])
430
431 optional arguments:
432 -h, --help show this help message and exit
433 --foo FOO FOO! (default: 42)
434
435
436conflict_handler
437^^^^^^^^^^^^^^^^
438
Benjamin Peterson90c58022010-03-03 01:55:09 +0000439:class:`ArgumentParser` objects do not allow two actions with the same option
440string. By default, :class:`ArgumentParser` objects raises an exception if an
441attempt is made to create an argument with an option string that is already in
442use::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000443
444 >>> parser = argparse.ArgumentParser(prog='PROG')
445 >>> parser.add_argument('-f', '--foo', help='old foo help')
446 >>> parser.add_argument('--foo', help='new foo help')
447 Traceback (most recent call last):
448 ..
449 ArgumentError: argument --foo: conflicting option string(s): --foo
450
451Sometimes (e.g. when using parents_) it may be useful to simply override any
Georg Brandld2decd92010-03-02 22:17:38 +0000452older arguments with the same option string. To get this behavior, the value
Benjamin Petersona39e9662010-03-02 22:05:59 +0000453``'resolve'`` can be supplied to the ``conflict_handler=`` argument of
Benjamin Peterson90c58022010-03-03 01:55:09 +0000454:class:`ArgumentParser`::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000455
456 >>> parser = argparse.ArgumentParser(prog='PROG', conflict_handler='resolve')
457 >>> parser.add_argument('-f', '--foo', help='old foo help')
458 >>> parser.add_argument('--foo', help='new foo help')
459 >>> parser.print_help()
460 usage: PROG [-h] [-f FOO] [--foo FOO]
461
462 optional arguments:
463 -h, --help show this help message and exit
464 -f FOO old foo help
465 --foo FOO new foo help
466
Benjamin Peterson90c58022010-03-03 01:55:09 +0000467Note that :class:`ArgumentParser` objects only remove an action if all of its
468option strings are overridden. So, in the example above, the old ``-f/--foo``
469action is retained as the ``-f`` action, because only the ``--foo`` option
470string was overridden.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000471
472
473prog
474^^^^
475
Benjamin Peterson90c58022010-03-03 01:55:09 +0000476By default, :class:`ArgumentParser` objects uses ``sys.argv[0]`` to determine
477how to display the name of the program in help messages. This default is almost
Ezio Melotti019551f2010-05-19 00:32:52 +0000478always desirable because it will make the help messages match how the program was
Benjamin Peterson90c58022010-03-03 01:55:09 +0000479invoked on the command line. For example, consider a file named
480``myprogram.py`` with the following code::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000481
482 import argparse
483 parser = argparse.ArgumentParser()
484 parser.add_argument('--foo', help='foo help')
485 args = parser.parse_args()
486
487The help for this program will display ``myprogram.py`` as the program name
488(regardless of where the program was invoked from)::
489
490 $ python myprogram.py --help
491 usage: myprogram.py [-h] [--foo FOO]
492
493 optional arguments:
494 -h, --help show this help message and exit
495 --foo FOO foo help
496 $ cd ..
497 $ python subdir\myprogram.py --help
498 usage: myprogram.py [-h] [--foo FOO]
499
500 optional arguments:
501 -h, --help show this help message and exit
502 --foo FOO foo help
503
504To change this default behavior, another value can be supplied using the
Benjamin Peterson90c58022010-03-03 01:55:09 +0000505``prog=`` argument to :class:`ArgumentParser`::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000506
507 >>> parser = argparse.ArgumentParser(prog='myprogram')
508 >>> parser.print_help()
509 usage: myprogram [-h]
510
511 optional arguments:
512 -h, --help show this help message and exit
513
514Note that the program name, whether determined from ``sys.argv[0]`` or from the
515``prog=`` argument, is available to help messages using the ``%(prog)s`` format
516specifier.
517
518::
519
520 >>> parser = argparse.ArgumentParser(prog='myprogram')
521 >>> parser.add_argument('--foo', help='foo of the %(prog)s program')
522 >>> parser.print_help()
523 usage: myprogram [-h] [--foo FOO]
524
525 optional arguments:
526 -h, --help show this help message and exit
527 --foo FOO foo of the myprogram program
528
529
530usage
531^^^^^
532
Benjamin Peterson90c58022010-03-03 01:55:09 +0000533By default, :class:`ArgumentParser` calculates the usage message from the
Benjamin Petersona39e9662010-03-02 22:05:59 +0000534arguments it contains::
535
536 >>> parser = argparse.ArgumentParser(prog='PROG')
537 >>> parser.add_argument('--foo', nargs='?', help='foo help')
538 >>> parser.add_argument('bar', nargs='+', help='bar help')
539 >>> parser.print_help()
540 usage: PROG [-h] [--foo [FOO]] bar [bar ...]
541
542 positional arguments:
543 bar bar help
544
545 optional arguments:
546 -h, --help show this help message and exit
547 --foo [FOO] foo help
548
Benjamin Peterson90c58022010-03-03 01:55:09 +0000549The default message can be overridden with the ``usage=`` keyword argument::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000550
551 >>> parser = argparse.ArgumentParser(prog='PROG', usage='%(prog)s [options]')
552 >>> parser.add_argument('--foo', nargs='?', help='foo help')
553 >>> parser.add_argument('bar', nargs='+', help='bar help')
554 >>> parser.print_help()
555 usage: PROG [options]
556
557 positional arguments:
558 bar bar help
559
560 optional arguments:
561 -h, --help show this help message and exit
562 --foo [FOO] foo help
563
Benjamin Peterson90c58022010-03-03 01:55:09 +0000564The ``%(prog)s`` format specifier is available to fill in the program name in
565your usage messages.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000566
567
568The add_argument() method
569-------------------------
570
Ezio Melotti569083a2011-04-21 23:30:27 +0300571.. method:: ArgumentParser.add_argument(name or flags..., [action], [nargs], [const], [default], [type], [choices], [required], [help], [metavar], [dest])
Benjamin Petersona39e9662010-03-02 22:05:59 +0000572
Ezio Melotti12125822011-04-16 23:04:51 +0300573 Define how a single command-line argument should be parsed. Each parameter
Benjamin Petersona39e9662010-03-02 22:05:59 +0000574 has its own more detailed description below, but in short they are:
575
576 * `name or flags`_ - Either a name or a list of option strings, e.g. ``foo``
Ezio Melottid281f142011-04-21 23:09:27 +0300577 or ``-f, --foo``.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000578
579 * action_ - The basic type of action to be taken when this argument is
Ezio Melotti12125822011-04-16 23:04:51 +0300580 encountered at the command line.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000581
582 * nargs_ - The number of command-line arguments that should be consumed.
583
584 * const_ - A constant value required by some action_ and nargs_ selections.
585
586 * default_ - The value produced if the argument is absent from the
Ezio Melotti12125822011-04-16 23:04:51 +0300587 command line.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000588
Ezio Melotti12125822011-04-16 23:04:51 +0300589 * type_ - The type to which the command-line argument should be converted.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000590
591 * choices_ - A container of the allowable values for the argument.
592
593 * required_ - Whether or not the command-line option may be omitted
594 (optionals only).
595
596 * help_ - A brief description of what the argument does.
597
598 * metavar_ - A name for the argument in usage messages.
599
600 * dest_ - The name of the attribute to be added to the object returned by
601 :meth:`parse_args`.
602
Benjamin Peterson90c58022010-03-03 01:55:09 +0000603The following sections describe how each of these are used.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000604
Georg Brandlb8d0e362010-11-26 07:53:50 +0000605
Benjamin Petersona39e9662010-03-02 22:05:59 +0000606name or flags
607^^^^^^^^^^^^^
608
Benjamin Peterson90c58022010-03-03 01:55:09 +0000609The :meth:`add_argument` method must know whether an optional argument, like
610``-f`` or ``--foo``, or a positional argument, like a list of filenames, is
611expected. The first arguments passed to :meth:`add_argument` must therefore be
612either a series of flags, or a simple argument name. For example, an optional
613argument could be created like::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000614
615 >>> parser.add_argument('-f', '--foo')
616
617while a positional argument could be created like::
618
619 >>> parser.add_argument('bar')
620
621When :meth:`parse_args` is called, optional arguments will be identified by the
622``-`` prefix, and the remaining arguments will be assumed to be positional::
623
624 >>> parser = argparse.ArgumentParser(prog='PROG')
625 >>> parser.add_argument('-f', '--foo')
626 >>> parser.add_argument('bar')
627 >>> parser.parse_args(['BAR'])
628 Namespace(bar='BAR', foo=None)
629 >>> parser.parse_args(['BAR', '--foo', 'FOO'])
630 Namespace(bar='BAR', foo='FOO')
631 >>> parser.parse_args(['--foo', 'FOO'])
632 usage: PROG [-h] [-f FOO] bar
633 PROG: error: too few arguments
634
Georg Brandlb8d0e362010-11-26 07:53:50 +0000635
Benjamin Petersona39e9662010-03-02 22:05:59 +0000636action
637^^^^^^
638
Georg Brandld2decd92010-03-02 22:17:38 +0000639:class:`ArgumentParser` objects associate command-line args with actions. These
Benjamin Petersona39e9662010-03-02 22:05:59 +0000640actions can do just about anything with the command-line args associated with
641them, though most actions simply add an attribute to the object returned by
Benjamin Peterson90c58022010-03-03 01:55:09 +0000642:meth:`parse_args`. The ``action`` keyword argument specifies how the
643command-line args should be handled. The supported actions are:
Benjamin Petersona39e9662010-03-02 22:05:59 +0000644
Georg Brandld2decd92010-03-02 22:17:38 +0000645* ``'store'`` - This just stores the argument's value. This is the default
Ezio Melotti310619c2011-04-21 23:06:48 +0300646 action. For example::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000647
648 >>> parser = argparse.ArgumentParser()
649 >>> parser.add_argument('--foo')
650 >>> parser.parse_args('--foo 1'.split())
651 Namespace(foo='1')
652
653* ``'store_const'`` - This stores the value specified by the const_ keyword
Ezio Melotti310619c2011-04-21 23:06:48 +0300654 argument. (Note that the const_ keyword argument defaults to the rather
655 unhelpful ``None``.) The ``'store_const'`` action is most commonly used with
656 optional arguments that specify some sort of flag. For example::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000657
658 >>> parser = argparse.ArgumentParser()
659 >>> parser.add_argument('--foo', action='store_const', const=42)
660 >>> parser.parse_args('--foo'.split())
661 Namespace(foo=42)
662
663* ``'store_true'`` and ``'store_false'`` - These store the values ``True`` and
Benjamin Peterson90c58022010-03-03 01:55:09 +0000664 ``False`` respectively. These are special cases of ``'store_const'``. For
665 example::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000666
667 >>> parser = argparse.ArgumentParser()
668 >>> parser.add_argument('--foo', action='store_true')
669 >>> parser.add_argument('--bar', action='store_false')
670 >>> parser.parse_args('--foo --bar'.split())
671 Namespace(bar=False, foo=True)
672
673* ``'append'`` - This stores a list, and appends each argument value to the
Benjamin Peterson90c58022010-03-03 01:55:09 +0000674 list. This is useful to allow an option to be specified multiple times.
675 Example usage::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000676
677 >>> parser = argparse.ArgumentParser()
678 >>> parser.add_argument('--foo', action='append')
679 >>> parser.parse_args('--foo 1 --foo 2'.split())
680 Namespace(foo=['1', '2'])
681
682* ``'append_const'`` - This stores a list, and appends the value specified by
Benjamin Peterson90c58022010-03-03 01:55:09 +0000683 the const_ keyword argument to the list. (Note that the const_ keyword
684 argument defaults to ``None``.) The ``'append_const'`` action is typically
685 useful when multiple arguments need to store constants to the same list. For
686 example::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000687
688 >>> parser = argparse.ArgumentParser()
689 >>> parser.add_argument('--str', dest='types', action='append_const', const=str)
690 >>> parser.add_argument('--int', dest='types', action='append_const', const=int)
691 >>> parser.parse_args('--str --int'.split())
692 Namespace(types=[<type 'str'>, <type 'int'>])
693
694* ``'version'`` - This expects a ``version=`` keyword argument in the
695 :meth:`add_argument` call, and prints version information and exits when
696 invoked.
697
698 >>> import argparse
699 >>> parser = argparse.ArgumentParser(prog='PROG')
Steven Bethard74bd9cf2010-05-24 02:38:00 +0000700 >>> parser.add_argument('--version', action='version', version='%(prog)s 2.0')
701 >>> parser.parse_args(['--version'])
Benjamin Petersona39e9662010-03-02 22:05:59 +0000702 PROG 2.0
703
704You can also specify an arbitrary action by passing an object that implements
Benjamin Peterson90c58022010-03-03 01:55:09 +0000705the Action API. The easiest way to do this is to extend
706:class:`argparse.Action`, supplying an appropriate ``__call__`` method. The
707``__call__`` method should accept four parameters:
Benjamin Petersona39e9662010-03-02 22:05:59 +0000708
709* ``parser`` - The ArgumentParser object which contains this action.
710
711* ``namespace`` - The namespace object that will be returned by
Georg Brandld2decd92010-03-02 22:17:38 +0000712 :meth:`parse_args`. Most actions add an attribute to this object.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000713
714* ``values`` - The associated command-line args, with any type-conversions
715 applied. (Type-conversions are specified with the type_ keyword argument to
716 :meth:`add_argument`.
717
718* ``option_string`` - The option string that was used to invoke this action.
719 The ``option_string`` argument is optional, and will be absent if the action
720 is associated with a positional argument.
721
Benjamin Peterson90c58022010-03-03 01:55:09 +0000722An example of a custom action::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000723
724 >>> class FooAction(argparse.Action):
725 ... def __call__(self, parser, namespace, values, option_string=None):
Georg Brandl8891e232010-08-01 21:23:50 +0000726 ... print '%r %r %r' % (namespace, values, option_string)
727 ... setattr(namespace, self.dest, values)
Benjamin Petersona39e9662010-03-02 22:05:59 +0000728 ...
729 >>> parser = argparse.ArgumentParser()
730 >>> parser.add_argument('--foo', action=FooAction)
731 >>> parser.add_argument('bar', action=FooAction)
732 >>> args = parser.parse_args('1 --foo 2'.split())
733 Namespace(bar=None, foo=None) '1' None
734 Namespace(bar='1', foo=None) '2' '--foo'
735 >>> args
736 Namespace(bar='1', foo='2')
737
738
739nargs
740^^^^^
741
742ArgumentParser objects usually associate a single command-line argument with a
Benjamin Peterson90c58022010-03-03 01:55:09 +0000743single action to be taken. The ``nargs`` keyword argument associates a
Ezio Melotti0a43ecc2011-04-21 22:56:51 +0300744different number of command-line arguments with a single action. The supported
Benjamin Peterson90c58022010-03-03 01:55:09 +0000745values are:
Benjamin Petersona39e9662010-03-02 22:05:59 +0000746
Ezio Melotti12125822011-04-16 23:04:51 +0300747* N (an integer). N args from the command line will be gathered together into a
Georg Brandld2decd92010-03-02 22:17:38 +0000748 list. For example::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000749
Georg Brandl35e7a8f2010-10-06 10:41:31 +0000750 >>> parser = argparse.ArgumentParser()
751 >>> parser.add_argument('--foo', nargs=2)
752 >>> parser.add_argument('bar', nargs=1)
753 >>> parser.parse_args('c --foo a b'.split())
754 Namespace(bar=['c'], foo=['a', 'b'])
Benjamin Petersona39e9662010-03-02 22:05:59 +0000755
Georg Brandl35e7a8f2010-10-06 10:41:31 +0000756 Note that ``nargs=1`` produces a list of one item. This is different from
757 the default, in which the item is produced by itself.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000758
Ezio Melotti12125822011-04-16 23:04:51 +0300759* ``'?'``. One arg will be consumed from the command line if possible, and
Benjamin Petersona39e9662010-03-02 22:05:59 +0000760 produced as a single item. If no command-line arg is present, the value from
761 default_ will be produced. Note that for optional arguments, there is an
762 additional case - the option string is present but not followed by a
763 command-line arg. In this case the value from const_ will be produced. Some
764 examples to illustrate this::
765
Georg Brandld2decd92010-03-02 22:17:38 +0000766 >>> parser = argparse.ArgumentParser()
767 >>> parser.add_argument('--foo', nargs='?', const='c', default='d')
768 >>> parser.add_argument('bar', nargs='?', default='d')
769 >>> parser.parse_args('XX --foo YY'.split())
770 Namespace(bar='XX', foo='YY')
771 >>> parser.parse_args('XX --foo'.split())
772 Namespace(bar='XX', foo='c')
773 >>> parser.parse_args(''.split())
774 Namespace(bar='d', foo='d')
Benjamin Petersona39e9662010-03-02 22:05:59 +0000775
Georg Brandld2decd92010-03-02 22:17:38 +0000776 One of the more common uses of ``nargs='?'`` is to allow optional input and
777 output files::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000778
Georg Brandld2decd92010-03-02 22:17:38 +0000779 >>> parser = argparse.ArgumentParser()
Georg Brandlb8d0e362010-11-26 07:53:50 +0000780 >>> parser.add_argument('infile', nargs='?', type=argparse.FileType('r'),
781 ... default=sys.stdin)
782 >>> parser.add_argument('outfile', nargs='?', type=argparse.FileType('w'),
783 ... default=sys.stdout)
Georg Brandld2decd92010-03-02 22:17:38 +0000784 >>> parser.parse_args(['input.txt', 'output.txt'])
Georg Brandl585bbb92011-01-09 09:33:09 +0000785 Namespace(infile=<open file 'input.txt', mode 'r' at 0x...>,
786 outfile=<open file 'output.txt', mode 'w' at 0x...>)
Georg Brandld2decd92010-03-02 22:17:38 +0000787 >>> parser.parse_args([])
Georg Brandl585bbb92011-01-09 09:33:09 +0000788 Namespace(infile=<open file '<stdin>', mode 'r' at 0x...>,
789 outfile=<open file '<stdout>', mode 'w' at 0x...>)
Benjamin Petersona39e9662010-03-02 22:05:59 +0000790
Georg Brandld2decd92010-03-02 22:17:38 +0000791* ``'*'``. All command-line args present are gathered into a list. Note that
792 it generally doesn't make much sense to have more than one positional argument
793 with ``nargs='*'``, but multiple optional arguments with ``nargs='*'`` is
794 possible. For example::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000795
Georg Brandld2decd92010-03-02 22:17:38 +0000796 >>> parser = argparse.ArgumentParser()
797 >>> parser.add_argument('--foo', nargs='*')
798 >>> parser.add_argument('--bar', nargs='*')
799 >>> parser.add_argument('baz', nargs='*')
800 >>> parser.parse_args('a b --foo x y --bar 1 2'.split())
801 Namespace(bar=['1', '2'], baz=['a', 'b'], foo=['x', 'y'])
Benjamin Petersona39e9662010-03-02 22:05:59 +0000802
803* ``'+'``. Just like ``'*'``, all command-line args present are gathered into a
804 list. Additionally, an error message will be generated if there wasn't at
805 least one command-line arg present. For example::
806
Georg Brandld2decd92010-03-02 22:17:38 +0000807 >>> parser = argparse.ArgumentParser(prog='PROG')
808 >>> parser.add_argument('foo', nargs='+')
809 >>> parser.parse_args('a b'.split())
810 Namespace(foo=['a', 'b'])
811 >>> parser.parse_args(''.split())
812 usage: PROG [-h] foo [foo ...]
813 PROG: error: too few arguments
Benjamin Petersona39e9662010-03-02 22:05:59 +0000814
815If the ``nargs`` keyword argument is not provided, the number of args consumed
Georg Brandld2decd92010-03-02 22:17:38 +0000816is determined by the action_. Generally this means a single command-line arg
Benjamin Petersona39e9662010-03-02 22:05:59 +0000817will be consumed and a single item (not a list) will be produced.
818
819
820const
821^^^^^
822
823The ``const`` argument of :meth:`add_argument` is used to hold constant values
824that are not read from the command line but are required for the various
825ArgumentParser actions. The two most common uses of it are:
826
827* When :meth:`add_argument` is called with ``action='store_const'`` or
828 ``action='append_const'``. These actions add the ``const`` value to one of
829 the attributes of the object returned by :meth:`parse_args`. See the action_
830 description for examples.
831
832* When :meth:`add_argument` is called with option strings (like ``-f`` or
Georg Brandld2decd92010-03-02 22:17:38 +0000833 ``--foo``) and ``nargs='?'``. This creates an optional argument that can be
Ezio Melotti12125822011-04-16 23:04:51 +0300834 followed by zero or one command-line args. When parsing the command line, if
Benjamin Petersona39e9662010-03-02 22:05:59 +0000835 the option string is encountered with no command-line arg following it, the
836 value of ``const`` will be assumed instead. See the nargs_ description for
837 examples.
838
839The ``const`` keyword argument defaults to ``None``.
840
841
842default
843^^^^^^^
844
845All optional arguments and some positional arguments may be omitted at the
Ezio Melotti12125822011-04-16 23:04:51 +0300846command line. The ``default`` keyword argument of :meth:`add_argument`, whose
Benjamin Petersona39e9662010-03-02 22:05:59 +0000847value defaults to ``None``, specifies what value should be used if the
848command-line arg is not present. For optional arguments, the ``default`` value
849is used when the option string was not present at the command line::
850
851 >>> parser = argparse.ArgumentParser()
852 >>> parser.add_argument('--foo', default=42)
853 >>> parser.parse_args('--foo 2'.split())
854 Namespace(foo='2')
855 >>> parser.parse_args(''.split())
856 Namespace(foo=42)
857
858For positional arguments with nargs_ ``='?'`` or ``'*'``, the ``default`` value
859is used when no command-line arg was present::
860
861 >>> parser = argparse.ArgumentParser()
862 >>> parser.add_argument('foo', nargs='?', default=42)
863 >>> parser.parse_args('a'.split())
864 Namespace(foo='a')
865 >>> parser.parse_args(''.split())
866 Namespace(foo=42)
867
868
Benjamin Peterson90c58022010-03-03 01:55:09 +0000869Providing ``default=argparse.SUPPRESS`` causes no attribute to be added if the
870command-line argument was not present.::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000871
872 >>> parser = argparse.ArgumentParser()
873 >>> parser.add_argument('--foo', default=argparse.SUPPRESS)
874 >>> parser.parse_args([])
875 Namespace()
876 >>> parser.parse_args(['--foo', '1'])
877 Namespace(foo='1')
878
879
880type
881^^^^
882
883By default, ArgumentParser objects read command-line args in as simple strings.
884However, quite often the command-line string should instead be interpreted as
Benjamin Peterson90c58022010-03-03 01:55:09 +0000885another type, like a :class:`float`, :class:`int` or :class:`file`. The
886``type`` keyword argument of :meth:`add_argument` allows any necessary
Georg Brandl21e99f42010-03-07 15:23:59 +0000887type-checking and type-conversions to be performed. Many common built-in types
Benjamin Peterson90c58022010-03-03 01:55:09 +0000888can be used directly as the value of the ``type`` argument::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000889
890 >>> parser = argparse.ArgumentParser()
891 >>> parser.add_argument('foo', type=int)
892 >>> parser.add_argument('bar', type=file)
893 >>> parser.parse_args('2 temp.txt'.split())
894 Namespace(bar=<open file 'temp.txt', mode 'r' at 0x...>, foo=2)
895
896To ease the use of various types of files, the argparse module provides the
897factory FileType which takes the ``mode=`` and ``bufsize=`` arguments of the
Georg Brandld2decd92010-03-02 22:17:38 +0000898``file`` object. For example, ``FileType('w')`` can be used to create a
Benjamin Petersona39e9662010-03-02 22:05:59 +0000899writable file::
900
901 >>> parser = argparse.ArgumentParser()
902 >>> parser.add_argument('bar', type=argparse.FileType('w'))
903 >>> parser.parse_args(['out.txt'])
904 Namespace(bar=<open file 'out.txt', mode 'w' at 0x...>)
905
Benjamin Peterson90c58022010-03-03 01:55:09 +0000906``type=`` can take any callable that takes a single string argument and returns
907the type-converted value::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000908
909 >>> def perfect_square(string):
910 ... value = int(string)
911 ... sqrt = math.sqrt(value)
912 ... if sqrt != int(sqrt):
913 ... msg = "%r is not a perfect square" % string
914 ... raise argparse.ArgumentTypeError(msg)
915 ... return value
916 ...
917 >>> parser = argparse.ArgumentParser(prog='PROG')
918 >>> parser.add_argument('foo', type=perfect_square)
919 >>> parser.parse_args('9'.split())
920 Namespace(foo=9)
921 >>> parser.parse_args('7'.split())
922 usage: PROG [-h] foo
923 PROG: error: argument foo: '7' is not a perfect square
924
Benjamin Peterson90c58022010-03-03 01:55:09 +0000925The choices_ keyword argument may be more convenient for type checkers that
926simply check against a range of values::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000927
928 >>> parser = argparse.ArgumentParser(prog='PROG')
929 >>> parser.add_argument('foo', type=int, choices=xrange(5, 10))
930 >>> parser.parse_args('7'.split())
931 Namespace(foo=7)
932 >>> parser.parse_args('11'.split())
933 usage: PROG [-h] {5,6,7,8,9}
934 PROG: error: argument foo: invalid choice: 11 (choose from 5, 6, 7, 8, 9)
935
936See the choices_ section for more details.
937
938
939choices
940^^^^^^^
941
942Some command-line args should be selected from a restricted set of values.
Benjamin Peterson90c58022010-03-03 01:55:09 +0000943These can be handled by passing a container object as the ``choices`` keyword
Ezio Melotti12125822011-04-16 23:04:51 +0300944argument to :meth:`add_argument`. When the command line is parsed, arg values
Benjamin Peterson90c58022010-03-03 01:55:09 +0000945will be checked, and an error message will be displayed if the arg was not one
946of the acceptable values::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000947
948 >>> parser = argparse.ArgumentParser(prog='PROG')
949 >>> parser.add_argument('foo', choices='abc')
950 >>> parser.parse_args('c'.split())
951 Namespace(foo='c')
952 >>> parser.parse_args('X'.split())
953 usage: PROG [-h] {a,b,c}
954 PROG: error: argument foo: invalid choice: 'X' (choose from 'a', 'b', 'c')
955
956Note that inclusion in the ``choices`` container is checked after any type_
957conversions have been performed, so the type of the objects in the ``choices``
958container should match the type_ specified::
959
960 >>> parser = argparse.ArgumentParser(prog='PROG')
961 >>> parser.add_argument('foo', type=complex, choices=[1, 1j])
962 >>> parser.parse_args('1j'.split())
963 Namespace(foo=1j)
964 >>> parser.parse_args('-- -4'.split())
965 usage: PROG [-h] {1,1j}
966 PROG: error: argument foo: invalid choice: (-4+0j) (choose from 1, 1j)
967
968Any object that supports the ``in`` operator can be passed as the ``choices``
Georg Brandld2decd92010-03-02 22:17:38 +0000969value, so :class:`dict` objects, :class:`set` objects, custom containers,
970etc. are all supported.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000971
972
973required
974^^^^^^^^
975
Ezio Melotti01b600c2011-04-21 16:12:17 +0300976In general, the :mod:`argparse` module assumes that flags like ``-f`` and ``--bar``
Ezio Melotti12125822011-04-16 23:04:51 +0300977indicate *optional* arguments, which can always be omitted at the command line.
Benjamin Peterson90c58022010-03-03 01:55:09 +0000978To make an option *required*, ``True`` can be specified for the ``required=``
979keyword argument to :meth:`add_argument`::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000980
981 >>> parser = argparse.ArgumentParser()
982 >>> parser.add_argument('--foo', required=True)
983 >>> parser.parse_args(['--foo', 'BAR'])
984 Namespace(foo='BAR')
985 >>> parser.parse_args([])
986 usage: argparse.py [-h] [--foo FOO]
987 argparse.py: error: option --foo is required
988
989As the example shows, if an option is marked as ``required``, :meth:`parse_args`
990will report an error if that option is not present at the command line.
991
Benjamin Peterson90c58022010-03-03 01:55:09 +0000992.. note::
993
994 Required options are generally considered bad form because users expect
995 *options* to be *optional*, and thus they should be avoided when possible.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000996
997
998help
999^^^^
1000
Benjamin Peterson90c58022010-03-03 01:55:09 +00001001The ``help`` value is a string containing a brief description of the argument.
1002When a user requests help (usually by using ``-h`` or ``--help`` at the
Ezio Melotti12125822011-04-16 23:04:51 +03001003command line), these ``help`` descriptions will be displayed with each
Georg Brandld2decd92010-03-02 22:17:38 +00001004argument::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001005
1006 >>> parser = argparse.ArgumentParser(prog='frobble')
1007 >>> parser.add_argument('--foo', action='store_true',
1008 ... help='foo the bars before frobbling')
1009 >>> parser.add_argument('bar', nargs='+',
1010 ... help='one of the bars to be frobbled')
1011 >>> parser.parse_args('-h'.split())
1012 usage: frobble [-h] [--foo] bar [bar ...]
1013
1014 positional arguments:
1015 bar one of the bars to be frobbled
1016
1017 optional arguments:
1018 -h, --help show this help message and exit
1019 --foo foo the bars before frobbling
1020
1021The ``help`` strings can include various format specifiers to avoid repetition
1022of things like the program name or the argument default_. The available
1023specifiers include the program name, ``%(prog)s`` and most keyword arguments to
1024:meth:`add_argument`, e.g. ``%(default)s``, ``%(type)s``, etc.::
1025
1026 >>> parser = argparse.ArgumentParser(prog='frobble')
1027 >>> parser.add_argument('bar', nargs='?', type=int, default=42,
1028 ... help='the bar to %(prog)s (default: %(default)s)')
1029 >>> parser.print_help()
1030 usage: frobble [-h] [bar]
1031
1032 positional arguments:
1033 bar the bar to frobble (default: 42)
1034
1035 optional arguments:
1036 -h, --help show this help message and exit
1037
1038
1039metavar
1040^^^^^^^
1041
Benjamin Peterson90c58022010-03-03 01:55:09 +00001042When :class:`ArgumentParser` generates help messages, it need some way to refer
Georg Brandld2decd92010-03-02 22:17:38 +00001043to each expected argument. By default, ArgumentParser objects use the dest_
Benjamin Petersona39e9662010-03-02 22:05:59 +00001044value as the "name" of each object. By default, for positional argument
1045actions, the dest_ value is used directly, and for optional argument actions,
Benjamin Peterson90c58022010-03-03 01:55:09 +00001046the dest_ value is uppercased. So, a single positional argument with
1047``dest='bar'`` will that argument will be referred to as ``bar``. A single
1048optional argument ``--foo`` that should be followed by a single command-line arg
1049will be referred to as ``FOO``. An example::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001050
1051 >>> parser = argparse.ArgumentParser()
1052 >>> parser.add_argument('--foo')
1053 >>> parser.add_argument('bar')
1054 >>> parser.parse_args('X --foo Y'.split())
1055 Namespace(bar='X', foo='Y')
1056 >>> parser.print_help()
1057 usage: [-h] [--foo FOO] bar
1058
1059 positional arguments:
1060 bar
1061
1062 optional arguments:
1063 -h, --help show this help message and exit
1064 --foo FOO
1065
Benjamin Peterson90c58022010-03-03 01:55:09 +00001066An alternative name can be specified with ``metavar``::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001067
1068 >>> parser = argparse.ArgumentParser()
1069 >>> parser.add_argument('--foo', metavar='YYY')
1070 >>> parser.add_argument('bar', metavar='XXX')
1071 >>> parser.parse_args('X --foo Y'.split())
1072 Namespace(bar='X', foo='Y')
1073 >>> parser.print_help()
1074 usage: [-h] [--foo YYY] XXX
1075
1076 positional arguments:
1077 XXX
1078
1079 optional arguments:
1080 -h, --help show this help message and exit
1081 --foo YYY
1082
1083Note that ``metavar`` only changes the *displayed* name - the name of the
1084attribute on the :meth:`parse_args` object is still determined by the dest_
1085value.
1086
1087Different values of ``nargs`` may cause the metavar to be used multiple times.
Benjamin Peterson90c58022010-03-03 01:55:09 +00001088Providing a tuple to ``metavar`` specifies a different display for each of the
1089arguments::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001090
1091 >>> parser = argparse.ArgumentParser(prog='PROG')
1092 >>> parser.add_argument('-x', nargs=2)
1093 >>> parser.add_argument('--foo', nargs=2, metavar=('bar', 'baz'))
1094 >>> parser.print_help()
1095 usage: PROG [-h] [-x X X] [--foo bar baz]
1096
1097 optional arguments:
1098 -h, --help show this help message and exit
1099 -x X X
1100 --foo bar baz
1101
1102
1103dest
1104^^^^
1105
Benjamin Peterson90c58022010-03-03 01:55:09 +00001106Most :class:`ArgumentParser` actions add some value as an attribute of the
1107object returned by :meth:`parse_args`. The name of this attribute is determined
1108by the ``dest`` keyword argument of :meth:`add_argument`. For positional
1109argument actions, ``dest`` is normally supplied as the first argument to
Benjamin Petersona39e9662010-03-02 22:05:59 +00001110:meth:`add_argument`::
1111
1112 >>> parser = argparse.ArgumentParser()
1113 >>> parser.add_argument('bar')
1114 >>> parser.parse_args('XXX'.split())
1115 Namespace(bar='XXX')
1116
1117For optional argument actions, the value of ``dest`` is normally inferred from
Benjamin Peterson90c58022010-03-03 01:55:09 +00001118the option strings. :class:`ArgumentParser` generates the value of ``dest`` by
Benjamin Petersona39e9662010-03-02 22:05:59 +00001119taking the first long option string and stripping away the initial ``'--'``
1120string. If no long option strings were supplied, ``dest`` will be derived from
1121the first short option string by stripping the initial ``'-'`` character. Any
Georg Brandld2decd92010-03-02 22:17:38 +00001122internal ``'-'`` characters will be converted to ``'_'`` characters to make sure
1123the string is a valid attribute name. The examples below illustrate this
Benjamin Petersona39e9662010-03-02 22:05:59 +00001124behavior::
1125
1126 >>> parser = argparse.ArgumentParser()
1127 >>> parser.add_argument('-f', '--foo-bar', '--foo')
1128 >>> parser.add_argument('-x', '-y')
1129 >>> parser.parse_args('-f 1 -x 2'.split())
1130 Namespace(foo_bar='1', x='2')
1131 >>> parser.parse_args('--foo 1 -y 2'.split())
1132 Namespace(foo_bar='1', x='2')
1133
Benjamin Peterson90c58022010-03-03 01:55:09 +00001134``dest`` allows a custom attribute name to be provided::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001135
1136 >>> parser = argparse.ArgumentParser()
1137 >>> parser.add_argument('--foo', dest='bar')
1138 >>> parser.parse_args('--foo XXX'.split())
1139 Namespace(bar='XXX')
1140
1141
1142The parse_args() method
1143-----------------------
1144
Georg Brandlb8d0e362010-11-26 07:53:50 +00001145.. method:: ArgumentParser.parse_args(args=None, namespace=None)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001146
Benjamin Peterson90c58022010-03-03 01:55:09 +00001147 Convert argument strings to objects and assign them as attributes of the
Georg Brandld2decd92010-03-02 22:17:38 +00001148 namespace. Return the populated namespace.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001149
1150 Previous calls to :meth:`add_argument` determine exactly what objects are
1151 created and how they are assigned. See the documentation for
1152 :meth:`add_argument` for details.
1153
Georg Brandld2decd92010-03-02 22:17:38 +00001154 By default, the arg strings are taken from :data:`sys.argv`, and a new empty
Benjamin Peterson90c58022010-03-03 01:55:09 +00001155 :class:`Namespace` object is created for the attributes.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001156
Georg Brandlb8d0e362010-11-26 07:53:50 +00001157
Benjamin Petersona39e9662010-03-02 22:05:59 +00001158Option value syntax
1159^^^^^^^^^^^^^^^^^^^
1160
1161The :meth:`parse_args` method supports several ways of specifying the value of
Georg Brandld2decd92010-03-02 22:17:38 +00001162an option (if it takes one). In the simplest case, the option and its value are
Benjamin Petersona39e9662010-03-02 22:05:59 +00001163passed as two separate arguments::
1164
1165 >>> parser = argparse.ArgumentParser(prog='PROG')
1166 >>> parser.add_argument('-x')
1167 >>> parser.add_argument('--foo')
1168 >>> parser.parse_args('-x X'.split())
1169 Namespace(foo=None, x='X')
1170 >>> parser.parse_args('--foo FOO'.split())
1171 Namespace(foo='FOO', x=None)
1172
Benjamin Peterson90c58022010-03-03 01:55:09 +00001173For long options (options with names longer than a single character), the option
Ezio Melotti12125822011-04-16 23:04:51 +03001174and value can also be passed as a single command-line argument, using ``=`` to
Georg Brandld2decd92010-03-02 22:17:38 +00001175separate them::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001176
1177 >>> parser.parse_args('--foo=FOO'.split())
1178 Namespace(foo='FOO', x=None)
1179
Benjamin Peterson90c58022010-03-03 01:55:09 +00001180For short options (options only one character long), the option and its value
1181can be concatenated::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001182
1183 >>> parser.parse_args('-xX'.split())
1184 Namespace(foo=None, x='X')
1185
Benjamin Peterson90c58022010-03-03 01:55:09 +00001186Several short options can be joined together, using only a single ``-`` prefix,
1187as long as only the last option (or none of them) requires a value::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001188
1189 >>> parser = argparse.ArgumentParser(prog='PROG')
1190 >>> parser.add_argument('-x', action='store_true')
1191 >>> parser.add_argument('-y', action='store_true')
1192 >>> parser.add_argument('-z')
1193 >>> parser.parse_args('-xyzZ'.split())
1194 Namespace(x=True, y=True, z='Z')
1195
1196
1197Invalid arguments
1198^^^^^^^^^^^^^^^^^
1199
Ezio Melotti12125822011-04-16 23:04:51 +03001200While parsing the command line, ``parse_args`` checks for a variety of errors,
Benjamin Petersona39e9662010-03-02 22:05:59 +00001201including ambiguous options, invalid types, invalid options, wrong number of
Georg Brandld2decd92010-03-02 22:17:38 +00001202positional arguments, etc. When it encounters such an error, it exits and
Benjamin Petersona39e9662010-03-02 22:05:59 +00001203prints the error along with a usage message::
1204
1205 >>> parser = argparse.ArgumentParser(prog='PROG')
1206 >>> parser.add_argument('--foo', type=int)
1207 >>> parser.add_argument('bar', nargs='?')
1208
1209 >>> # invalid type
1210 >>> parser.parse_args(['--foo', 'spam'])
1211 usage: PROG [-h] [--foo FOO] [bar]
1212 PROG: error: argument --foo: invalid int value: 'spam'
1213
1214 >>> # invalid option
1215 >>> parser.parse_args(['--bar'])
1216 usage: PROG [-h] [--foo FOO] [bar]
1217 PROG: error: no such option: --bar
1218
1219 >>> # wrong number of arguments
1220 >>> parser.parse_args(['spam', 'badger'])
1221 usage: PROG [-h] [--foo FOO] [bar]
1222 PROG: error: extra arguments found: badger
1223
1224
1225Arguments containing ``"-"``
1226^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1227
1228The ``parse_args`` method attempts to give errors whenever the user has clearly
Georg Brandld2decd92010-03-02 22:17:38 +00001229made a mistake, but some situations are inherently ambiguous. For example, the
Benjamin Petersona39e9662010-03-02 22:05:59 +00001230command-line arg ``'-1'`` could either be an attempt to specify an option or an
Georg Brandld2decd92010-03-02 22:17:38 +00001231attempt to provide a positional argument. The ``parse_args`` method is cautious
Benjamin Petersona39e9662010-03-02 22:05:59 +00001232here: positional arguments may only begin with ``'-'`` if they look like
1233negative numbers and there are no options in the parser that look like negative
1234numbers::
1235
1236 >>> parser = argparse.ArgumentParser(prog='PROG')
1237 >>> parser.add_argument('-x')
1238 >>> parser.add_argument('foo', nargs='?')
1239
1240 >>> # no negative number options, so -1 is a positional argument
1241 >>> parser.parse_args(['-x', '-1'])
1242 Namespace(foo=None, x='-1')
1243
1244 >>> # no negative number options, so -1 and -5 are positional arguments
1245 >>> parser.parse_args(['-x', '-1', '-5'])
1246 Namespace(foo='-5', x='-1')
1247
1248 >>> parser = argparse.ArgumentParser(prog='PROG')
1249 >>> parser.add_argument('-1', dest='one')
1250 >>> parser.add_argument('foo', nargs='?')
1251
1252 >>> # negative number options present, so -1 is an option
1253 >>> parser.parse_args(['-1', 'X'])
1254 Namespace(foo=None, one='X')
1255
1256 >>> # negative number options present, so -2 is an option
1257 >>> parser.parse_args(['-2'])
1258 usage: PROG [-h] [-1 ONE] [foo]
1259 PROG: error: no such option: -2
1260
1261 >>> # negative number options present, so both -1s are options
1262 >>> parser.parse_args(['-1', '-1'])
1263 usage: PROG [-h] [-1 ONE] [foo]
1264 PROG: error: argument -1: expected one argument
1265
1266If you have positional arguments that must begin with ``'-'`` and don't look
1267like negative numbers, you can insert the pseudo-argument ``'--'`` which tells
1268``parse_args`` that everything after that is a positional argument::
1269
1270 >>> parser.parse_args(['--', '-f'])
1271 Namespace(foo='-f', one=None)
1272
1273
1274Argument abbreviations
1275^^^^^^^^^^^^^^^^^^^^^^
1276
Benjamin Peterson90c58022010-03-03 01:55:09 +00001277The :meth:`parse_args` method allows long options to be abbreviated if the
Benjamin Petersona39e9662010-03-02 22:05:59 +00001278abbreviation is unambiguous::
1279
1280 >>> parser = argparse.ArgumentParser(prog='PROG')
1281 >>> parser.add_argument('-bacon')
1282 >>> parser.add_argument('-badger')
1283 >>> parser.parse_args('-bac MMM'.split())
1284 Namespace(bacon='MMM', badger=None)
1285 >>> parser.parse_args('-bad WOOD'.split())
1286 Namespace(bacon=None, badger='WOOD')
1287 >>> parser.parse_args('-ba BA'.split())
1288 usage: PROG [-h] [-bacon BACON] [-badger BADGER]
1289 PROG: error: ambiguous option: -ba could match -badger, -bacon
1290
Benjamin Peterson90c58022010-03-03 01:55:09 +00001291An error is produced for arguments that could produce more than one options.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001292
1293
1294Beyond ``sys.argv``
1295^^^^^^^^^^^^^^^^^^^
1296
Georg Brandld2decd92010-03-02 22:17:38 +00001297Sometimes it may be useful to have an ArgumentParser parse args other than those
1298of :data:`sys.argv`. This can be accomplished by passing a list of strings to
Benjamin Peterson90c58022010-03-03 01:55:09 +00001299``parse_args``. This is useful for testing at the interactive prompt::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001300
1301 >>> parser = argparse.ArgumentParser()
1302 >>> parser.add_argument(
1303 ... 'integers', metavar='int', type=int, choices=xrange(10),
1304 ... nargs='+', help='an integer in the range 0..9')
1305 >>> parser.add_argument(
1306 ... '--sum', dest='accumulate', action='store_const', const=sum,
1307 ... default=max, help='sum the integers (default: find the max)')
1308 >>> parser.parse_args(['1', '2', '3', '4'])
1309 Namespace(accumulate=<built-in function max>, integers=[1, 2, 3, 4])
1310 >>> parser.parse_args('1 2 3 4 --sum'.split())
1311 Namespace(accumulate=<built-in function sum>, integers=[1, 2, 3, 4])
1312
1313
Steven Bethard3f69a052011-03-26 19:59:02 +01001314The Namespace object
1315^^^^^^^^^^^^^^^^^^^^
1316
1317By default, :meth:`parse_args` will return a new object of type :class:`Namespace`
1318where the necessary attributes have been set. This class is deliberately simple,
1319just an :class:`object` subclass with a readable string representation. If you
1320prefer to have dict-like view of the attributes, you can use the standard Python
1321idiom via :func:`vars`::
1322
1323 >>> parser = argparse.ArgumentParser()
1324 >>> parser.add_argument('--foo')
1325 >>> args = parser.parse_args(['--foo', 'BAR'])
1326 >>> vars(args)
1327 {'foo': 'BAR'}
Benjamin Petersona39e9662010-03-02 22:05:59 +00001328
Benjamin Peterson90c58022010-03-03 01:55:09 +00001329It may also be useful to have an :class:`ArgumentParser` assign attributes to an
Steven Bethard3f69a052011-03-26 19:59:02 +01001330already existing object, rather than a new :class:`Namespace` object. This can
1331be achieved by specifying the ``namespace=`` keyword argument::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001332
1333 >>> class C(object):
1334 ... pass
1335 ...
1336 >>> c = C()
1337 >>> parser = argparse.ArgumentParser()
1338 >>> parser.add_argument('--foo')
1339 >>> parser.parse_args(args=['--foo', 'BAR'], namespace=c)
1340 >>> c.foo
1341 'BAR'
1342
1343
1344Other utilities
1345---------------
1346
1347Sub-commands
1348^^^^^^^^^^^^
1349
Benjamin Peterson90c58022010-03-03 01:55:09 +00001350.. method:: ArgumentParser.add_subparsers()
Benjamin Petersona39e9662010-03-02 22:05:59 +00001351
Benjamin Peterson90c58022010-03-03 01:55:09 +00001352 Many programs split up their functionality into a number of sub-commands,
Georg Brandld2decd92010-03-02 22:17:38 +00001353 for example, the ``svn`` program can invoke sub-commands like ``svn
Benjamin Peterson90c58022010-03-03 01:55:09 +00001354 checkout``, ``svn update``, and ``svn commit``. Splitting up functionality
Georg Brandld2decd92010-03-02 22:17:38 +00001355 this way can be a particularly good idea when a program performs several
1356 different functions which require different kinds of command-line arguments.
Benjamin Peterson90c58022010-03-03 01:55:09 +00001357 :class:`ArgumentParser` supports the creation of such sub-commands with the
Georg Brandld2decd92010-03-02 22:17:38 +00001358 :meth:`add_subparsers` method. The :meth:`add_subparsers` method is normally
1359 called with no arguments and returns an special action object. This object
1360 has a single method, ``add_parser``, which takes a command name and any
Benjamin Peterson90c58022010-03-03 01:55:09 +00001361 :class:`ArgumentParser` constructor arguments, and returns an
1362 :class:`ArgumentParser` object that can be modified as usual.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001363
1364 Some example usage::
1365
1366 >>> # create the top-level parser
1367 >>> parser = argparse.ArgumentParser(prog='PROG')
1368 >>> parser.add_argument('--foo', action='store_true', help='foo help')
1369 >>> subparsers = parser.add_subparsers(help='sub-command help')
1370 >>>
1371 >>> # create the parser for the "a" command
1372 >>> parser_a = subparsers.add_parser('a', help='a help')
1373 >>> parser_a.add_argument('bar', type=int, help='bar help')
1374 >>>
1375 >>> # create the parser for the "b" command
1376 >>> parser_b = subparsers.add_parser('b', help='b help')
1377 >>> parser_b.add_argument('--baz', choices='XYZ', help='baz help')
1378 >>>
1379 >>> # parse some arg lists
1380 >>> parser.parse_args(['a', '12'])
1381 Namespace(bar=12, foo=False)
1382 >>> parser.parse_args(['--foo', 'b', '--baz', 'Z'])
1383 Namespace(baz='Z', foo=True)
1384
1385 Note that the object returned by :meth:`parse_args` will only contain
1386 attributes for the main parser and the subparser that was selected by the
1387 command line (and not any other subparsers). So in the example above, when
Georg Brandld2decd92010-03-02 22:17:38 +00001388 the ``"a"`` command is specified, only the ``foo`` and ``bar`` attributes are
1389 present, and when the ``"b"`` command is specified, only the ``foo`` and
Benjamin Petersona39e9662010-03-02 22:05:59 +00001390 ``baz`` attributes are present.
1391
1392 Similarly, when a help message is requested from a subparser, only the help
Georg Brandld2decd92010-03-02 22:17:38 +00001393 for that particular parser will be printed. The help message will not
Benjamin Peterson90c58022010-03-03 01:55:09 +00001394 include parent parser or sibling parser messages. (A help message for each
1395 subparser command, however, can be given by supplying the ``help=`` argument
1396 to ``add_parser`` as above.)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001397
1398 ::
1399
1400 >>> parser.parse_args(['--help'])
1401 usage: PROG [-h] [--foo] {a,b} ...
1402
1403 positional arguments:
1404 {a,b} sub-command help
1405 a a help
1406 b b help
1407
1408 optional arguments:
1409 -h, --help show this help message and exit
1410 --foo foo help
1411
1412 >>> parser.parse_args(['a', '--help'])
1413 usage: PROG a [-h] bar
1414
1415 positional arguments:
1416 bar bar help
1417
1418 optional arguments:
1419 -h, --help show this help message and exit
1420
1421 >>> parser.parse_args(['b', '--help'])
1422 usage: PROG b [-h] [--baz {X,Y,Z}]
1423
1424 optional arguments:
1425 -h, --help show this help message and exit
1426 --baz {X,Y,Z} baz help
1427
Georg Brandld2decd92010-03-02 22:17:38 +00001428 The :meth:`add_subparsers` method also supports ``title`` and ``description``
1429 keyword arguments. When either is present, the subparser's commands will
1430 appear in their own group in the help output. For example::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001431
1432 >>> parser = argparse.ArgumentParser()
1433 >>> subparsers = parser.add_subparsers(title='subcommands',
1434 ... description='valid subcommands',
1435 ... help='additional help')
1436 >>> subparsers.add_parser('foo')
1437 >>> subparsers.add_parser('bar')
1438 >>> parser.parse_args(['-h'])
1439 usage: [-h] {foo,bar} ...
1440
1441 optional arguments:
1442 -h, --help show this help message and exit
1443
1444 subcommands:
1445 valid subcommands
1446
1447 {foo,bar} additional help
1448
1449
Georg Brandld2decd92010-03-02 22:17:38 +00001450 One particularly effective way of handling sub-commands is to combine the use
1451 of the :meth:`add_subparsers` method with calls to :meth:`set_defaults` so
1452 that each subparser knows which Python function it should execute. For
Benjamin Petersona39e9662010-03-02 22:05:59 +00001453 example::
1454
1455 >>> # sub-command functions
1456 >>> def foo(args):
1457 ... print args.x * args.y
1458 ...
1459 >>> def bar(args):
1460 ... print '((%s))' % args.z
1461 ...
1462 >>> # create the top-level parser
1463 >>> parser = argparse.ArgumentParser()
1464 >>> subparsers = parser.add_subparsers()
1465 >>>
1466 >>> # create the parser for the "foo" command
1467 >>> parser_foo = subparsers.add_parser('foo')
1468 >>> parser_foo.add_argument('-x', type=int, default=1)
1469 >>> parser_foo.add_argument('y', type=float)
1470 >>> parser_foo.set_defaults(func=foo)
1471 >>>
1472 >>> # create the parser for the "bar" command
1473 >>> parser_bar = subparsers.add_parser('bar')
1474 >>> parser_bar.add_argument('z')
1475 >>> parser_bar.set_defaults(func=bar)
1476 >>>
1477 >>> # parse the args and call whatever function was selected
1478 >>> args = parser.parse_args('foo 1 -x 2'.split())
1479 >>> args.func(args)
1480 2.0
1481 >>>
1482 >>> # parse the args and call whatever function was selected
1483 >>> args = parser.parse_args('bar XYZYX'.split())
1484 >>> args.func(args)
1485 ((XYZYX))
1486
Benjamin Peterson90c58022010-03-03 01:55:09 +00001487 This way, you can let :meth:`parse_args` does the job of calling the
1488 appropriate function after argument parsing is complete. Associating
1489 functions with actions like this is typically the easiest way to handle the
1490 different actions for each of your subparsers. However, if it is necessary
1491 to check the name of the subparser that was invoked, the ``dest`` keyword
1492 argument to the :meth:`add_subparsers` call will work::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001493
1494 >>> parser = argparse.ArgumentParser()
1495 >>> subparsers = parser.add_subparsers(dest='subparser_name')
1496 >>> subparser1 = subparsers.add_parser('1')
1497 >>> subparser1.add_argument('-x')
1498 >>> subparser2 = subparsers.add_parser('2')
1499 >>> subparser2.add_argument('y')
1500 >>> parser.parse_args(['2', 'frobble'])
1501 Namespace(subparser_name='2', y='frobble')
1502
1503
1504FileType objects
1505^^^^^^^^^^^^^^^^
1506
1507.. class:: FileType(mode='r', bufsize=None)
1508
1509 The :class:`FileType` factory creates objects that can be passed to the type
Benjamin Peterson90c58022010-03-03 01:55:09 +00001510 argument of :meth:`ArgumentParser.add_argument`. Arguments that have
1511 :class:`FileType` objects as their type will open command-line args as files
1512 with the requested modes and buffer sizes:
Benjamin Petersona39e9662010-03-02 22:05:59 +00001513
1514 >>> parser = argparse.ArgumentParser()
1515 >>> parser.add_argument('--output', type=argparse.FileType('wb', 0))
1516 >>> parser.parse_args(['--output', 'out'])
1517 Namespace(output=<open file 'out', mode 'wb' at 0x...>)
1518
1519 FileType objects understand the pseudo-argument ``'-'`` and automatically
1520 convert this into ``sys.stdin`` for readable :class:`FileType` objects and
1521 ``sys.stdout`` for writable :class:`FileType` objects:
1522
1523 >>> parser = argparse.ArgumentParser()
1524 >>> parser.add_argument('infile', type=argparse.FileType('r'))
1525 >>> parser.parse_args(['-'])
1526 Namespace(infile=<open file '<stdin>', mode 'r' at 0x...>)
1527
1528
1529Argument groups
1530^^^^^^^^^^^^^^^
1531
Georg Brandlb8d0e362010-11-26 07:53:50 +00001532.. method:: ArgumentParser.add_argument_group(title=None, description=None)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001533
Benjamin Peterson90c58022010-03-03 01:55:09 +00001534 By default, :class:`ArgumentParser` groups command-line arguments into
Benjamin Petersona39e9662010-03-02 22:05:59 +00001535 "positional arguments" and "optional arguments" when displaying help
1536 messages. When there is a better conceptual grouping of arguments than this
1537 default one, appropriate groups can be created using the
1538 :meth:`add_argument_group` method::
1539
1540 >>> parser = argparse.ArgumentParser(prog='PROG', add_help=False)
1541 >>> group = parser.add_argument_group('group')
1542 >>> group.add_argument('--foo', help='foo help')
1543 >>> group.add_argument('bar', help='bar help')
1544 >>> parser.print_help()
1545 usage: PROG [--foo FOO] bar
1546
1547 group:
1548 bar bar help
1549 --foo FOO foo help
1550
1551 The :meth:`add_argument_group` method returns an argument group object which
Benjamin Peterson90c58022010-03-03 01:55:09 +00001552 has an :meth:`~ArgumentParser.add_argument` method just like a regular
1553 :class:`ArgumentParser`. When an argument is added to the group, the parser
1554 treats it just like a normal argument, but displays the argument in a
1555 separate group for help messages. The :meth:`add_argument_group` method
Georg Brandlb8d0e362010-11-26 07:53:50 +00001556 accepts *title* and *description* arguments which can be used to
Benjamin Peterson90c58022010-03-03 01:55:09 +00001557 customize this display::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001558
1559 >>> parser = argparse.ArgumentParser(prog='PROG', add_help=False)
1560 >>> group1 = parser.add_argument_group('group1', 'group1 description')
1561 >>> group1.add_argument('foo', help='foo help')
1562 >>> group2 = parser.add_argument_group('group2', 'group2 description')
1563 >>> group2.add_argument('--bar', help='bar help')
1564 >>> parser.print_help()
1565 usage: PROG [--bar BAR] foo
1566
1567 group1:
1568 group1 description
1569
1570 foo foo help
1571
1572 group2:
1573 group2 description
1574
1575 --bar BAR bar help
1576
Benjamin Peterson90c58022010-03-03 01:55:09 +00001577 Note that any arguments not your user defined groups will end up back in the
1578 usual "positional arguments" and "optional arguments" sections.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001579
1580
1581Mutual exclusion
1582^^^^^^^^^^^^^^^^
1583
Georg Brandlb8d0e362010-11-26 07:53:50 +00001584.. method:: add_mutually_exclusive_group(required=False)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001585
Ezio Melotti01b600c2011-04-21 16:12:17 +03001586 Create a mutually exclusive group. :mod:`argparse` will make sure that only
1587 one of the arguments in the mutually exclusive group was present on the
1588 command line::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001589
1590 >>> parser = argparse.ArgumentParser(prog='PROG')
1591 >>> group = parser.add_mutually_exclusive_group()
1592 >>> group.add_argument('--foo', action='store_true')
1593 >>> group.add_argument('--bar', action='store_false')
1594 >>> parser.parse_args(['--foo'])
1595 Namespace(bar=True, foo=True)
1596 >>> parser.parse_args(['--bar'])
1597 Namespace(bar=False, foo=False)
1598 >>> parser.parse_args(['--foo', '--bar'])
1599 usage: PROG [-h] [--foo | --bar]
1600 PROG: error: argument --bar: not allowed with argument --foo
1601
Georg Brandlb8d0e362010-11-26 07:53:50 +00001602 The :meth:`add_mutually_exclusive_group` method also accepts a *required*
Benjamin Petersona39e9662010-03-02 22:05:59 +00001603 argument, to indicate that at least one of the mutually exclusive arguments
1604 is required::
1605
1606 >>> parser = argparse.ArgumentParser(prog='PROG')
1607 >>> group = parser.add_mutually_exclusive_group(required=True)
1608 >>> group.add_argument('--foo', action='store_true')
1609 >>> group.add_argument('--bar', action='store_false')
1610 >>> parser.parse_args([])
1611 usage: PROG [-h] (--foo | --bar)
1612 PROG: error: one of the arguments --foo --bar is required
1613
1614 Note that currently mutually exclusive argument groups do not support the
Georg Brandlb8d0e362010-11-26 07:53:50 +00001615 *title* and *description* arguments of :meth:`add_argument_group`.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001616
1617
1618Parser defaults
1619^^^^^^^^^^^^^^^
1620
Benjamin Peterson90c58022010-03-03 01:55:09 +00001621.. method:: ArgumentParser.set_defaults(**kwargs)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001622
Georg Brandld2decd92010-03-02 22:17:38 +00001623 Most of the time, the attributes of the object returned by :meth:`parse_args`
1624 will be fully determined by inspecting the command-line args and the argument
Benjamin Petersonc516d192010-03-03 02:04:24 +00001625 actions. :meth:`ArgumentParser.set_defaults` allows some additional
Ezio Melotti12125822011-04-16 23:04:51 +03001626 attributes that are determined without any inspection of the command line to
Benjamin Petersonc516d192010-03-03 02:04:24 +00001627 be added::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001628
1629 >>> parser = argparse.ArgumentParser()
1630 >>> parser.add_argument('foo', type=int)
1631 >>> parser.set_defaults(bar=42, baz='badger')
1632 >>> parser.parse_args(['736'])
1633 Namespace(bar=42, baz='badger', foo=736)
1634
Benjamin Peterson90c58022010-03-03 01:55:09 +00001635 Note that parser-level defaults always override argument-level defaults::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001636
1637 >>> parser = argparse.ArgumentParser()
1638 >>> parser.add_argument('--foo', default='bar')
1639 >>> parser.set_defaults(foo='spam')
1640 >>> parser.parse_args([])
1641 Namespace(foo='spam')
1642
Benjamin Peterson90c58022010-03-03 01:55:09 +00001643 Parser-level defaults can be particularly useful when working with multiple
1644 parsers. See the :meth:`~ArgumentParser.add_subparsers` method for an
1645 example of this type.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001646
Benjamin Peterson90c58022010-03-03 01:55:09 +00001647.. method:: ArgumentParser.get_default(dest)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001648
1649 Get the default value for a namespace attribute, as set by either
Benjamin Peterson90c58022010-03-03 01:55:09 +00001650 :meth:`~ArgumentParser.add_argument` or by
1651 :meth:`~ArgumentParser.set_defaults`::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001652
1653 >>> parser = argparse.ArgumentParser()
1654 >>> parser.add_argument('--foo', default='badger')
1655 >>> parser.get_default('foo')
1656 'badger'
1657
1658
1659Printing help
1660^^^^^^^^^^^^^
1661
1662In most typical applications, :meth:`parse_args` will take care of formatting
Benjamin Peterson90c58022010-03-03 01:55:09 +00001663and printing any usage or error messages. However, several formatting methods
1664are available:
Benjamin Petersona39e9662010-03-02 22:05:59 +00001665
Georg Brandlb8d0e362010-11-26 07:53:50 +00001666.. method:: ArgumentParser.print_usage(file=None)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001667
1668 Print a brief description of how the :class:`ArgumentParser` should be
R. David Murray561b96f2011-02-11 17:25:54 +00001669 invoked on the command line. If *file* is ``None``, :data:`sys.stdout` is
Benjamin Petersona39e9662010-03-02 22:05:59 +00001670 assumed.
1671
Georg Brandlb8d0e362010-11-26 07:53:50 +00001672.. method:: ArgumentParser.print_help(file=None)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001673
1674 Print a help message, including the program usage and information about the
Georg Brandlb8d0e362010-11-26 07:53:50 +00001675 arguments registered with the :class:`ArgumentParser`. If *file* is
R. David Murray561b96f2011-02-11 17:25:54 +00001676 ``None``, :data:`sys.stdout` is assumed.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001677
1678There are also variants of these methods that simply return a string instead of
1679printing it:
1680
Georg Brandlb8d0e362010-11-26 07:53:50 +00001681.. method:: ArgumentParser.format_usage()
Benjamin Petersona39e9662010-03-02 22:05:59 +00001682
1683 Return a string containing a brief description of how the
1684 :class:`ArgumentParser` should be invoked on the command line.
1685
Georg Brandlb8d0e362010-11-26 07:53:50 +00001686.. method:: ArgumentParser.format_help()
Benjamin Petersona39e9662010-03-02 22:05:59 +00001687
1688 Return a string containing a help message, including the program usage and
1689 information about the arguments registered with the :class:`ArgumentParser`.
1690
1691
Benjamin Petersona39e9662010-03-02 22:05:59 +00001692Partial parsing
1693^^^^^^^^^^^^^^^
1694
Georg Brandlb8d0e362010-11-26 07:53:50 +00001695.. method:: ArgumentParser.parse_known_args(args=None, namespace=None)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001696
Ezio Melotti12125822011-04-16 23:04:51 +03001697Sometimes a script may only parse a few of the command-line arguments, passing
Benjamin Petersona39e9662010-03-02 22:05:59 +00001698the remaining arguments on to another script or program. In these cases, the
Georg Brandld2decd92010-03-02 22:17:38 +00001699:meth:`parse_known_args` method can be useful. It works much like
Benjamin Peterson90c58022010-03-03 01:55:09 +00001700:meth:`~ArgumentParser.parse_args` except that it does not produce an error when
1701extra arguments are present. Instead, it returns a two item tuple containing
1702the populated namespace and the list of remaining argument strings.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001703
1704::
1705
1706 >>> parser = argparse.ArgumentParser()
1707 >>> parser.add_argument('--foo', action='store_true')
1708 >>> parser.add_argument('bar')
1709 >>> parser.parse_known_args(['--foo', '--badger', 'BAR', 'spam'])
1710 (Namespace(bar='BAR', foo=True), ['--badger', 'spam'])
1711
1712
1713Customizing file parsing
1714^^^^^^^^^^^^^^^^^^^^^^^^
1715
Benjamin Peterson90c58022010-03-03 01:55:09 +00001716.. method:: ArgumentParser.convert_arg_line_to_args(arg_line)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001717
Georg Brandlb8d0e362010-11-26 07:53:50 +00001718 Arguments that are read from a file (see the *fromfile_prefix_chars*
Benjamin Petersona39e9662010-03-02 22:05:59 +00001719 keyword argument to the :class:`ArgumentParser` constructor) are read one
Benjamin Peterson90c58022010-03-03 01:55:09 +00001720 argument per line. :meth:`convert_arg_line_to_args` can be overriden for
1721 fancier reading.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001722
Georg Brandlb8d0e362010-11-26 07:53:50 +00001723 This method takes a single argument *arg_line* which is a string read from
Benjamin Petersona39e9662010-03-02 22:05:59 +00001724 the argument file. It returns a list of arguments parsed from this string.
1725 The method is called once per line read from the argument file, in order.
1726
Georg Brandld2decd92010-03-02 22:17:38 +00001727 A useful override of this method is one that treats each space-separated word
1728 as an argument::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001729
1730 def convert_arg_line_to_args(self, arg_line):
1731 for arg in arg_line.split():
1732 if not arg.strip():
1733 continue
1734 yield arg
1735
1736
Georg Brandlb8d0e362010-11-26 07:53:50 +00001737Exiting methods
1738^^^^^^^^^^^^^^^
1739
1740.. method:: ArgumentParser.exit(status=0, message=None)
1741
1742 This method terminates the program, exiting with the specified *status*
1743 and, if given, it prints a *message* before that.
1744
1745.. method:: ArgumentParser.error(message)
1746
1747 This method prints a usage message including the *message* to the
1748 standard output and terminates the program with a status code of 2.
1749
1750
Georg Brandl58df6792010-07-03 10:25:47 +00001751.. _argparse-from-optparse:
1752
Benjamin Petersona39e9662010-03-02 22:05:59 +00001753Upgrading optparse code
1754-----------------------
1755
Ezio Melotti01b600c2011-04-21 16:12:17 +03001756Originally, the mod:`argparse` module had attempted to maintain compatibility
1757with :mod:`optparse`. However, :mod:`optparse` was difficult to extend
1758transparently, particularly with the changes required to support the new
1759``nargs=`` specifiers and better usage messages. When most everything in
1760:mod:`optparse` had either been copy-pasted over or monkey-patched, it no
1761longer seemed practical to try to maintain the backwards compatibility.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001762
Ezio Melotti01b600c2011-04-21 16:12:17 +03001763A partial upgrade path from :mod:`optparse` to :mod:`argparse`:
Benjamin Petersona39e9662010-03-02 22:05:59 +00001764
Georg Brandl585bbb92011-01-09 09:33:09 +00001765* Replace all ``add_option()`` calls with :meth:`ArgumentParser.add_argument`
1766 calls.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001767
Georg Brandld2decd92010-03-02 22:17:38 +00001768* Replace ``options, args = parser.parse_args()`` with ``args =
Georg Brandl585bbb92011-01-09 09:33:09 +00001769 parser.parse_args()`` and add additional :meth:`ArgumentParser.add_argument`
1770 calls for the positional arguments.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001771
1772* Replace callback actions and the ``callback_*`` keyword arguments with
1773 ``type`` or ``action`` arguments.
1774
1775* Replace string names for ``type`` keyword arguments with the corresponding
1776 type objects (e.g. int, float, complex, etc).
1777
Benjamin Peterson90c58022010-03-03 01:55:09 +00001778* Replace :class:`optparse.Values` with :class:`Namespace` and
1779 :exc:`optparse.OptionError` and :exc:`optparse.OptionValueError` with
1780 :exc:`ArgumentError`.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001781
Georg Brandld2decd92010-03-02 22:17:38 +00001782* Replace strings with implicit arguments such as ``%default`` or ``%prog`` with
Ezio Melotti2eab88e2011-04-21 15:26:46 +03001783 the standard Python syntax to use dictionaries to format strings, that is,
Georg Brandld2decd92010-03-02 22:17:38 +00001784 ``%(default)s`` and ``%(prog)s``.
Steven Bethard74bd9cf2010-05-24 02:38:00 +00001785
1786* Replace the OptionParser constructor ``version`` argument with a call to
1787 ``parser.add_argument('--version', action='version', version='<the version>')``