blob: e151c97ce51dbb5176d9eddbaa0b335916ac6aaf [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
Georg Brandl585bbb92011-01-09 09:33:09 +0000123.. class:: ArgumentParser([description], [epilog], [prog], [usage], [add_help], \
124 [argument_default], [parents], [prefix_chars], \
125 [conflict_handler], [formatter_class])
Benjamin Petersona39e9662010-03-02 22:05:59 +0000126
Georg Brandld2decd92010-03-02 22:17:38 +0000127 Create a new :class:`ArgumentParser` object. Each parameter has its own more
Benjamin Petersona39e9662010-03-02 22:05:59 +0000128 detailed description below, but in short they are:
129
130 * description_ - Text to display before the argument help.
131
132 * epilog_ - Text to display after the argument help.
133
Benjamin Peterson90c58022010-03-03 01:55:09 +0000134 * add_help_ - Add a -h/--help option to the parser. (default: ``True``)
Benjamin Petersona39e9662010-03-02 22:05:59 +0000135
136 * argument_default_ - Set the global default value for arguments.
Benjamin Peterson90c58022010-03-03 01:55:09 +0000137 (default: ``None``)
Benjamin Petersona39e9662010-03-02 22:05:59 +0000138
Benjamin Peterson90c58022010-03-03 01:55:09 +0000139 * parents_ - A list of :class:`ArgumentParser` objects whose arguments should
Benjamin Petersona39e9662010-03-02 22:05:59 +0000140 also be included.
141
142 * prefix_chars_ - The set of characters that prefix optional arguments.
143 (default: '-')
144
145 * fromfile_prefix_chars_ - The set of characters that prefix files from
Benjamin Peterson90c58022010-03-03 01:55:09 +0000146 which additional arguments should be read. (default: ``None``)
Benjamin Petersona39e9662010-03-02 22:05:59 +0000147
148 * formatter_class_ - A class for customizing the help output.
149
150 * conflict_handler_ - Usually unnecessary, defines strategy for resolving
151 conflicting optionals.
152
Benjamin Peterson90c58022010-03-03 01:55:09 +0000153 * prog_ - The name of the program (default:
154 :data:`sys.argv[0]`)
Benjamin Petersona39e9662010-03-02 22:05:59 +0000155
Benjamin Peterson90c58022010-03-03 01:55:09 +0000156 * usage_ - The string describing the program usage (default: generated)
Benjamin Petersona39e9662010-03-02 22:05:59 +0000157
Benjamin Peterson90c58022010-03-03 01:55:09 +0000158The following sections describe how each of these are used.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000159
160
161description
162^^^^^^^^^^^
163
Benjamin Peterson90c58022010-03-03 01:55:09 +0000164Most calls to the :class:`ArgumentParser` constructor will use the
165``description=`` keyword argument. This argument gives a brief description of
166what the program does and how it works. In help messages, the description is
167displayed between the command-line usage string and the help messages for the
168various arguments::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000169
170 >>> parser = argparse.ArgumentParser(description='A foo that bars')
171 >>> parser.print_help()
172 usage: argparse.py [-h]
173
174 A foo that bars
175
176 optional arguments:
177 -h, --help show this help message and exit
178
179By default, the description will be line-wrapped so that it fits within the
Georg Brandld2decd92010-03-02 22:17:38 +0000180given space. To change this behavior, see the formatter_class_ argument.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000181
182
183epilog
184^^^^^^
185
186Some programs like to display additional description of the program after the
Georg Brandld2decd92010-03-02 22:17:38 +0000187description of the arguments. Such text can be specified using the ``epilog=``
188argument to :class:`ArgumentParser`::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000189
190 >>> parser = argparse.ArgumentParser(
191 ... description='A foo that bars',
192 ... epilog="And that's how you'd foo a bar")
193 >>> parser.print_help()
194 usage: argparse.py [-h]
195
196 A foo that bars
197
198 optional arguments:
199 -h, --help show this help message and exit
200
201 And that's how you'd foo a bar
202
203As with the description_ argument, the ``epilog=`` text is by default
204line-wrapped, but this behavior can be adjusted with the formatter_class_
Benjamin Peterson90c58022010-03-03 01:55:09 +0000205argument to :class:`ArgumentParser`.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000206
207
208add_help
209^^^^^^^^
210
R. David Murray1cbf78e2010-08-03 18:14:01 +0000211By default, ArgumentParser objects add an option which simply displays
212the parser's help message. For example, consider a file named
Benjamin Petersona39e9662010-03-02 22:05:59 +0000213``myprogram.py`` containing the following code::
214
215 import argparse
216 parser = argparse.ArgumentParser()
217 parser.add_argument('--foo', help='foo help')
218 args = parser.parse_args()
219
Ezio Melotti12125822011-04-16 23:04:51 +0300220If ``-h`` or ``--help`` is supplied at the command line, the ArgumentParser
Benjamin Petersona39e9662010-03-02 22:05:59 +0000221help will be printed::
222
223 $ python myprogram.py --help
224 usage: myprogram.py [-h] [--foo FOO]
225
226 optional arguments:
227 -h, --help show this help message and exit
228 --foo FOO foo help
229
230Occasionally, it may be useful to disable the addition of this help option.
231This can be achieved by passing ``False`` as the ``add_help=`` argument to
Benjamin Peterson90c58022010-03-03 01:55:09 +0000232:class:`ArgumentParser`::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000233
234 >>> parser = argparse.ArgumentParser(prog='PROG', add_help=False)
235 >>> parser.add_argument('--foo', help='foo help')
236 >>> parser.print_help()
237 usage: PROG [--foo FOO]
238
239 optional arguments:
240 --foo FOO foo help
241
R. David Murray1cbf78e2010-08-03 18:14:01 +0000242The help option is typically ``-h/--help``. The exception to this is
243if the ``prefix_chars=`` is specified and does not include ``'-'``, in
244which case ``-h`` and ``--help`` are not valid options. In
245this case, the first character in ``prefix_chars`` is used to prefix
246the help options::
247
248 >>> parser = argparse.ArgumentParser(prog='PROG', prefix_chars='+/')
249 >>> parser.print_help()
250 usage: PROG [+h]
251
252 optional arguments:
253 +h, ++help show this help message and exit
254
255
Benjamin Petersona39e9662010-03-02 22:05:59 +0000256prefix_chars
257^^^^^^^^^^^^
258
259Most command-line options will use ``'-'`` as the prefix, e.g. ``-f/--foo``.
R. David Murray1cbf78e2010-08-03 18:14:01 +0000260Parsers that need to support different or additional prefix
261characters, e.g. for options
Benjamin Petersona39e9662010-03-02 22:05:59 +0000262like ``+f`` or ``/foo``, may specify them using the ``prefix_chars=`` argument
263to the ArgumentParser constructor::
264
265 >>> parser = argparse.ArgumentParser(prog='PROG', prefix_chars='-+')
266 >>> parser.add_argument('+f')
267 >>> parser.add_argument('++bar')
268 >>> parser.parse_args('+f X ++bar Y'.split())
269 Namespace(bar='Y', f='X')
270
271The ``prefix_chars=`` argument defaults to ``'-'``. Supplying a set of
272characters that does not include ``'-'`` will cause ``-f/--foo`` options to be
273disallowed.
274
275
276fromfile_prefix_chars
277^^^^^^^^^^^^^^^^^^^^^
278
Benjamin Peterson90c58022010-03-03 01:55:09 +0000279Sometimes, for example when dealing with a particularly long argument lists, it
280may make sense to keep the list of arguments in a file rather than typing it out
281at the command line. If the ``fromfile_prefix_chars=`` argument is given to the
282:class:`ArgumentParser` constructor, then arguments that start with any of the
283specified characters will be treated as files, and will be replaced by the
284arguments they contain. For example::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000285
Benjamin Peterson90c58022010-03-03 01:55:09 +0000286 >>> with open('args.txt', 'w') as fp:
287 ... fp.write('-f\nbar')
Benjamin Petersona39e9662010-03-02 22:05:59 +0000288 >>> parser = argparse.ArgumentParser(fromfile_prefix_chars='@')
289 >>> parser.add_argument('-f')
290 >>> parser.parse_args(['-f', 'foo', '@args.txt'])
291 Namespace(f='bar')
292
293Arguments read from a file must by default be one per line (but see also
294:meth:`convert_arg_line_to_args`) and are treated as if they were in the same
Georg Brandld2decd92010-03-02 22:17:38 +0000295place as the original file referencing argument on the command line. So in the
Benjamin Petersona39e9662010-03-02 22:05:59 +0000296example above, the expression ``['-f', 'foo', '@args.txt']`` is considered
297equivalent to the expression ``['-f', 'foo', '-f', 'bar']``.
298
299The ``fromfile_prefix_chars=`` argument defaults to ``None``, meaning that
300arguments will never be treated as file references.
301
Georg Brandlb8d0e362010-11-26 07:53:50 +0000302
Benjamin Petersona39e9662010-03-02 22:05:59 +0000303argument_default
304^^^^^^^^^^^^^^^^
305
306Generally, argument defaults are specified either by passing a default to
307:meth:`add_argument` or by calling the :meth:`set_defaults` methods with a
Georg Brandld2decd92010-03-02 22:17:38 +0000308specific set of name-value pairs. Sometimes however, it may be useful to
309specify a single parser-wide default for arguments. This can be accomplished by
Benjamin Peterson90c58022010-03-03 01:55:09 +0000310passing the ``argument_default=`` keyword argument to :class:`ArgumentParser`.
311For example, to globally suppress attribute creation on :meth:`parse_args`
312calls, we supply ``argument_default=SUPPRESS``::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000313
314 >>> parser = argparse.ArgumentParser(argument_default=argparse.SUPPRESS)
315 >>> parser.add_argument('--foo')
316 >>> parser.add_argument('bar', nargs='?')
317 >>> parser.parse_args(['--foo', '1', 'BAR'])
318 Namespace(bar='BAR', foo='1')
319 >>> parser.parse_args([])
320 Namespace()
321
322
323parents
324^^^^^^^
325
326Sometimes, several parsers share a common set of arguments. Rather than
Benjamin Peterson90c58022010-03-03 01:55:09 +0000327repeating the definitions of these arguments, a single parser with all the
328shared arguments and passed to ``parents=`` argument to :class:`ArgumentParser`
329can be used. The ``parents=`` argument takes a list of :class:`ArgumentParser`
330objects, collects all the positional and optional actions from them, and adds
331these actions to the :class:`ArgumentParser` object being constructed::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000332
333 >>> parent_parser = argparse.ArgumentParser(add_help=False)
334 >>> parent_parser.add_argument('--parent', type=int)
335
336 >>> foo_parser = argparse.ArgumentParser(parents=[parent_parser])
337 >>> foo_parser.add_argument('foo')
338 >>> foo_parser.parse_args(['--parent', '2', 'XXX'])
339 Namespace(foo='XXX', parent=2)
340
341 >>> bar_parser = argparse.ArgumentParser(parents=[parent_parser])
342 >>> bar_parser.add_argument('--bar')
343 >>> bar_parser.parse_args(['--bar', 'YYY'])
344 Namespace(bar='YYY', parent=None)
345
Georg Brandld2decd92010-03-02 22:17:38 +0000346Note that most parent parsers will specify ``add_help=False``. Otherwise, the
Benjamin Peterson90c58022010-03-03 01:55:09 +0000347:class:`ArgumentParser` will see two ``-h/--help`` options (one in the parent
348and one in the child) and raise an error.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000349
Steven Bethard5e0062d2011-03-26 21:50:38 +0100350.. note::
351 You must fully initialize the parsers before passing them via ``parents=``.
352 If you change the parent parsers after the child parser, those changes will
353 not be reflected in the child.
354
Benjamin Petersona39e9662010-03-02 22:05:59 +0000355
356formatter_class
357^^^^^^^^^^^^^^^
358
Benjamin Peterson90c58022010-03-03 01:55:09 +0000359:class:`ArgumentParser` objects allow the help formatting to be customized by
360specifying an alternate formatting class. Currently, there are three such
361classes: :class:`argparse.RawDescriptionHelpFormatter`,
Georg Brandld2decd92010-03-02 22:17:38 +0000362:class:`argparse.RawTextHelpFormatter` and
363:class:`argparse.ArgumentDefaultsHelpFormatter`. The first two allow more
364control over how textual descriptions are displayed, while the last
365automatically adds information about argument default values.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000366
Benjamin Peterson90c58022010-03-03 01:55:09 +0000367By default, :class:`ArgumentParser` objects line-wrap the description_ and
368epilog_ texts in command-line help messages::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000369
370 >>> parser = argparse.ArgumentParser(
371 ... prog='PROG',
372 ... description='''this description
373 ... was indented weird
374 ... but that is okay''',
375 ... epilog='''
376 ... likewise for this epilog whose whitespace will
377 ... be cleaned up and whose words will be wrapped
378 ... across a couple lines''')
379 >>> parser.print_help()
380 usage: PROG [-h]
381
382 this description was indented weird but that is okay
383
384 optional arguments:
385 -h, --help show this help message and exit
386
387 likewise for this epilog whose whitespace will be cleaned up and whose words
388 will be wrapped across a couple lines
389
Benjamin Peterson90c58022010-03-03 01:55:09 +0000390Passing :class:`argparse.RawDescriptionHelpFormatter` as ``formatter_class=``
Benjamin Petersonc516d192010-03-03 02:04:24 +0000391indicates that description_ and epilog_ are already correctly formatted and
Benjamin Peterson90c58022010-03-03 01:55:09 +0000392should not be line-wrapped::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000393
394 >>> parser = argparse.ArgumentParser(
395 ... prog='PROG',
396 ... formatter_class=argparse.RawDescriptionHelpFormatter,
397 ... description=textwrap.dedent('''\
398 ... Please do not mess up this text!
399 ... --------------------------------
400 ... I have indented it
401 ... exactly the way
402 ... I want it
403 ... '''))
404 >>> parser.print_help()
405 usage: PROG [-h]
406
407 Please do not mess up this text!
408 --------------------------------
409 I have indented it
410 exactly the way
411 I want it
412
413 optional arguments:
414 -h, --help show this help message and exit
415
Benjamin Peterson90c58022010-03-03 01:55:09 +0000416:class:`RawTextHelpFormatter` maintains whitespace for all sorts of help text
417including argument descriptions.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000418
Benjamin Peterson90c58022010-03-03 01:55:09 +0000419The other formatter class available, :class:`ArgumentDefaultsHelpFormatter`,
Georg Brandld2decd92010-03-02 22:17:38 +0000420will add information about the default value of each of the arguments::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000421
422 >>> parser = argparse.ArgumentParser(
423 ... prog='PROG',
424 ... formatter_class=argparse.ArgumentDefaultsHelpFormatter)
425 >>> parser.add_argument('--foo', type=int, default=42, help='FOO!')
426 >>> parser.add_argument('bar', nargs='*', default=[1, 2, 3], help='BAR!')
427 >>> parser.print_help()
428 usage: PROG [-h] [--foo FOO] [bar [bar ...]]
429
430 positional arguments:
431 bar BAR! (default: [1, 2, 3])
432
433 optional arguments:
434 -h, --help show this help message and exit
435 --foo FOO FOO! (default: 42)
436
437
438conflict_handler
439^^^^^^^^^^^^^^^^
440
Benjamin Peterson90c58022010-03-03 01:55:09 +0000441:class:`ArgumentParser` objects do not allow two actions with the same option
442string. By default, :class:`ArgumentParser` objects raises an exception if an
443attempt is made to create an argument with an option string that is already in
444use::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000445
446 >>> parser = argparse.ArgumentParser(prog='PROG')
447 >>> parser.add_argument('-f', '--foo', help='old foo help')
448 >>> parser.add_argument('--foo', help='new foo help')
449 Traceback (most recent call last):
450 ..
451 ArgumentError: argument --foo: conflicting option string(s): --foo
452
453Sometimes (e.g. when using parents_) it may be useful to simply override any
Georg Brandld2decd92010-03-02 22:17:38 +0000454older arguments with the same option string. To get this behavior, the value
Benjamin Petersona39e9662010-03-02 22:05:59 +0000455``'resolve'`` can be supplied to the ``conflict_handler=`` argument of
Benjamin Peterson90c58022010-03-03 01:55:09 +0000456:class:`ArgumentParser`::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000457
458 >>> parser = argparse.ArgumentParser(prog='PROG', conflict_handler='resolve')
459 >>> parser.add_argument('-f', '--foo', help='old foo help')
460 >>> parser.add_argument('--foo', help='new foo help')
461 >>> parser.print_help()
462 usage: PROG [-h] [-f FOO] [--foo FOO]
463
464 optional arguments:
465 -h, --help show this help message and exit
466 -f FOO old foo help
467 --foo FOO new foo help
468
Benjamin Peterson90c58022010-03-03 01:55:09 +0000469Note that :class:`ArgumentParser` objects only remove an action if all of its
470option strings are overridden. So, in the example above, the old ``-f/--foo``
471action is retained as the ``-f`` action, because only the ``--foo`` option
472string was overridden.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000473
474
475prog
476^^^^
477
Benjamin Peterson90c58022010-03-03 01:55:09 +0000478By default, :class:`ArgumentParser` objects uses ``sys.argv[0]`` to determine
479how to display the name of the program in help messages. This default is almost
Ezio Melotti019551f2010-05-19 00:32:52 +0000480always desirable because it will make the help messages match how the program was
Benjamin Peterson90c58022010-03-03 01:55:09 +0000481invoked on the command line. For example, consider a file named
482``myprogram.py`` with the following code::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000483
484 import argparse
485 parser = argparse.ArgumentParser()
486 parser.add_argument('--foo', help='foo help')
487 args = parser.parse_args()
488
489The help for this program will display ``myprogram.py`` as the program name
490(regardless of where the program was invoked from)::
491
492 $ python myprogram.py --help
493 usage: myprogram.py [-h] [--foo FOO]
494
495 optional arguments:
496 -h, --help show this help message and exit
497 --foo FOO foo help
498 $ cd ..
499 $ python subdir\myprogram.py --help
500 usage: myprogram.py [-h] [--foo FOO]
501
502 optional arguments:
503 -h, --help show this help message and exit
504 --foo FOO foo help
505
506To change this default behavior, another value can be supplied using the
Benjamin Peterson90c58022010-03-03 01:55:09 +0000507``prog=`` argument to :class:`ArgumentParser`::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000508
509 >>> parser = argparse.ArgumentParser(prog='myprogram')
510 >>> parser.print_help()
511 usage: myprogram [-h]
512
513 optional arguments:
514 -h, --help show this help message and exit
515
516Note that the program name, whether determined from ``sys.argv[0]`` or from the
517``prog=`` argument, is available to help messages using the ``%(prog)s`` format
518specifier.
519
520::
521
522 >>> parser = argparse.ArgumentParser(prog='myprogram')
523 >>> parser.add_argument('--foo', help='foo of the %(prog)s program')
524 >>> parser.print_help()
525 usage: myprogram [-h] [--foo FOO]
526
527 optional arguments:
528 -h, --help show this help message and exit
529 --foo FOO foo of the myprogram program
530
531
532usage
533^^^^^
534
Benjamin Peterson90c58022010-03-03 01:55:09 +0000535By default, :class:`ArgumentParser` calculates the usage message from the
Benjamin Petersona39e9662010-03-02 22:05:59 +0000536arguments it contains::
537
538 >>> parser = argparse.ArgumentParser(prog='PROG')
539 >>> parser.add_argument('--foo', nargs='?', help='foo help')
540 >>> parser.add_argument('bar', nargs='+', help='bar help')
541 >>> parser.print_help()
542 usage: PROG [-h] [--foo [FOO]] bar [bar ...]
543
544 positional arguments:
545 bar bar help
546
547 optional arguments:
548 -h, --help show this help message and exit
549 --foo [FOO] foo help
550
Benjamin Peterson90c58022010-03-03 01:55:09 +0000551The default message can be overridden with the ``usage=`` keyword argument::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000552
553 >>> parser = argparse.ArgumentParser(prog='PROG', usage='%(prog)s [options]')
554 >>> parser.add_argument('--foo', nargs='?', help='foo help')
555 >>> parser.add_argument('bar', nargs='+', help='bar help')
556 >>> parser.print_help()
557 usage: PROG [options]
558
559 positional arguments:
560 bar bar help
561
562 optional arguments:
563 -h, --help show this help message and exit
564 --foo [FOO] foo help
565
Benjamin Peterson90c58022010-03-03 01:55:09 +0000566The ``%(prog)s`` format specifier is available to fill in the program name in
567your usage messages.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000568
569
570The add_argument() method
571-------------------------
572
Georg Brandl585bbb92011-01-09 09:33:09 +0000573.. method:: ArgumentParser.add_argument(name or flags..., [action], [nargs], \
574 [const], [default], [type], [choices], [required], \
575 [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
Benjamin Peterson90c58022010-03-03 01:55:09 +0000613The :meth:`add_argument` method must know whether an optional argument, like
614``-f`` or ``--foo``, or a positional argument, like a list of filenames, is
615expected. The first arguments passed to :meth:`add_argument` must therefore be
616either a series of flags, or a simple argument name. For example, an optional
617argument could be created like::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000618
619 >>> parser.add_argument('-f', '--foo')
620
621while a positional argument could be created like::
622
623 >>> parser.add_argument('bar')
624
625When :meth:`parse_args` is called, optional arguments will be identified by the
626``-`` prefix, and the remaining arguments will be assumed to be positional::
627
628 >>> parser = argparse.ArgumentParser(prog='PROG')
629 >>> parser.add_argument('-f', '--foo')
630 >>> parser.add_argument('bar')
631 >>> parser.parse_args(['BAR'])
632 Namespace(bar='BAR', foo=None)
633 >>> parser.parse_args(['BAR', '--foo', 'FOO'])
634 Namespace(bar='BAR', foo='FOO')
635 >>> parser.parse_args(['--foo', 'FOO'])
636 usage: PROG [-h] [-f FOO] bar
637 PROG: error: too few arguments
638
Georg Brandlb8d0e362010-11-26 07:53:50 +0000639
Benjamin Petersona39e9662010-03-02 22:05:59 +0000640action
641^^^^^^
642
Georg Brandld2decd92010-03-02 22:17:38 +0000643:class:`ArgumentParser` objects associate command-line args with actions. These
Benjamin Petersona39e9662010-03-02 22:05:59 +0000644actions can do just about anything with the command-line args associated with
645them, though most actions simply add an attribute to the object returned by
Benjamin Peterson90c58022010-03-03 01:55:09 +0000646:meth:`parse_args`. The ``action`` keyword argument specifies how the
647command-line args should be handled. The supported actions are:
Benjamin Petersona39e9662010-03-02 22:05:59 +0000648
Georg Brandld2decd92010-03-02 22:17:38 +0000649* ``'store'`` - This just stores the argument's value. This is the default
Ezio Melotti310619c2011-04-21 23:06:48 +0300650 action. For example::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000651
652 >>> parser = argparse.ArgumentParser()
653 >>> parser.add_argument('--foo')
654 >>> parser.parse_args('--foo 1'.split())
655 Namespace(foo='1')
656
657* ``'store_const'`` - This stores the value specified by the const_ keyword
Ezio Melotti310619c2011-04-21 23:06:48 +0300658 argument. (Note that the const_ keyword argument defaults to the rather
659 unhelpful ``None``.) The ``'store_const'`` action is most commonly used with
660 optional arguments that specify some sort of flag. For example::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000661
662 >>> parser = argparse.ArgumentParser()
663 >>> parser.add_argument('--foo', action='store_const', const=42)
664 >>> parser.parse_args('--foo'.split())
665 Namespace(foo=42)
666
667* ``'store_true'`` and ``'store_false'`` - These store the values ``True`` and
Benjamin Peterson90c58022010-03-03 01:55:09 +0000668 ``False`` respectively. These are special cases of ``'store_const'``. For
669 example::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000670
671 >>> parser = argparse.ArgumentParser()
672 >>> parser.add_argument('--foo', action='store_true')
673 >>> parser.add_argument('--bar', action='store_false')
674 >>> parser.parse_args('--foo --bar'.split())
675 Namespace(bar=False, foo=True)
676
677* ``'append'`` - This stores a list, and appends each argument value to the
Benjamin Peterson90c58022010-03-03 01:55:09 +0000678 list. This is useful to allow an option to be specified multiple times.
679 Example usage::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000680
681 >>> parser = argparse.ArgumentParser()
682 >>> parser.add_argument('--foo', action='append')
683 >>> parser.parse_args('--foo 1 --foo 2'.split())
684 Namespace(foo=['1', '2'])
685
686* ``'append_const'`` - This stores a list, and appends the value specified by
Benjamin Peterson90c58022010-03-03 01:55:09 +0000687 the const_ keyword argument to the list. (Note that the const_ keyword
688 argument defaults to ``None``.) The ``'append_const'`` action is typically
689 useful when multiple arguments need to store constants to the same list. For
690 example::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000691
692 >>> parser = argparse.ArgumentParser()
693 >>> parser.add_argument('--str', dest='types', action='append_const', const=str)
694 >>> parser.add_argument('--int', dest='types', action='append_const', const=int)
695 >>> parser.parse_args('--str --int'.split())
696 Namespace(types=[<type 'str'>, <type 'int'>])
697
698* ``'version'`` - This expects a ``version=`` keyword argument in the
699 :meth:`add_argument` call, and prints version information and exits when
700 invoked.
701
702 >>> import argparse
703 >>> parser = argparse.ArgumentParser(prog='PROG')
Steven Bethard74bd9cf2010-05-24 02:38:00 +0000704 >>> parser.add_argument('--version', action='version', version='%(prog)s 2.0')
705 >>> parser.parse_args(['--version'])
Benjamin Petersona39e9662010-03-02 22:05:59 +0000706 PROG 2.0
707
708You can also specify an arbitrary action by passing an object that implements
Benjamin Peterson90c58022010-03-03 01:55:09 +0000709the Action API. The easiest way to do this is to extend
710:class:`argparse.Action`, supplying an appropriate ``__call__`` method. The
711``__call__`` method should accept four parameters:
Benjamin Petersona39e9662010-03-02 22:05:59 +0000712
713* ``parser`` - The ArgumentParser object which contains this action.
714
715* ``namespace`` - The namespace object that will be returned by
Georg Brandld2decd92010-03-02 22:17:38 +0000716 :meth:`parse_args`. Most actions add an attribute to this object.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000717
718* ``values`` - The associated command-line args, with any type-conversions
719 applied. (Type-conversions are specified with the type_ keyword argument to
720 :meth:`add_argument`.
721
722* ``option_string`` - The option string that was used to invoke this action.
723 The ``option_string`` argument is optional, and will be absent if the action
724 is associated with a positional argument.
725
Benjamin Peterson90c58022010-03-03 01:55:09 +0000726An example of a custom action::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000727
728 >>> class FooAction(argparse.Action):
729 ... def __call__(self, parser, namespace, values, option_string=None):
Georg Brandl8891e232010-08-01 21:23:50 +0000730 ... print '%r %r %r' % (namespace, values, option_string)
731 ... setattr(namespace, self.dest, values)
Benjamin Petersona39e9662010-03-02 22:05:59 +0000732 ...
733 >>> parser = argparse.ArgumentParser()
734 >>> parser.add_argument('--foo', action=FooAction)
735 >>> parser.add_argument('bar', action=FooAction)
736 >>> args = parser.parse_args('1 --foo 2'.split())
737 Namespace(bar=None, foo=None) '1' None
738 Namespace(bar='1', foo=None) '2' '--foo'
739 >>> args
740 Namespace(bar='1', foo='2')
741
742
743nargs
744^^^^^
745
746ArgumentParser objects usually associate a single command-line argument with a
Benjamin Peterson90c58022010-03-03 01:55:09 +0000747single action to be taken. The ``nargs`` keyword argument associates a
Ezio Melotti0a43ecc2011-04-21 22:56:51 +0300748different number of command-line arguments with a single action. The supported
Benjamin Peterson90c58022010-03-03 01:55:09 +0000749values are:
Benjamin Petersona39e9662010-03-02 22:05:59 +0000750
Ezio Melotti12125822011-04-16 23:04:51 +0300751* N (an integer). N args from the command line will be gathered together into a
Georg Brandld2decd92010-03-02 22:17:38 +0000752 list. For example::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000753
Georg Brandl35e7a8f2010-10-06 10:41:31 +0000754 >>> parser = argparse.ArgumentParser()
755 >>> parser.add_argument('--foo', nargs=2)
756 >>> parser.add_argument('bar', nargs=1)
757 >>> parser.parse_args('c --foo a b'.split())
758 Namespace(bar=['c'], foo=['a', 'b'])
Benjamin Petersona39e9662010-03-02 22:05:59 +0000759
Georg Brandl35e7a8f2010-10-06 10:41:31 +0000760 Note that ``nargs=1`` produces a list of one item. This is different from
761 the default, in which the item is produced by itself.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000762
Ezio Melotti12125822011-04-16 23:04:51 +0300763* ``'?'``. One arg will be consumed from the command line if possible, and
Benjamin Petersona39e9662010-03-02 22:05:59 +0000764 produced as a single item. If no command-line arg is present, the value from
765 default_ will be produced. Note that for optional arguments, there is an
766 additional case - the option string is present but not followed by a
767 command-line arg. In this case the value from const_ will be produced. Some
768 examples to illustrate this::
769
Georg Brandld2decd92010-03-02 22:17:38 +0000770 >>> parser = argparse.ArgumentParser()
771 >>> parser.add_argument('--foo', nargs='?', const='c', default='d')
772 >>> parser.add_argument('bar', nargs='?', default='d')
773 >>> parser.parse_args('XX --foo YY'.split())
774 Namespace(bar='XX', foo='YY')
775 >>> parser.parse_args('XX --foo'.split())
776 Namespace(bar='XX', foo='c')
777 >>> parser.parse_args(''.split())
778 Namespace(bar='d', foo='d')
Benjamin Petersona39e9662010-03-02 22:05:59 +0000779
Georg Brandld2decd92010-03-02 22:17:38 +0000780 One of the more common uses of ``nargs='?'`` is to allow optional input and
781 output files::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000782
Georg Brandld2decd92010-03-02 22:17:38 +0000783 >>> parser = argparse.ArgumentParser()
Georg Brandlb8d0e362010-11-26 07:53:50 +0000784 >>> parser.add_argument('infile', nargs='?', type=argparse.FileType('r'),
785 ... default=sys.stdin)
786 >>> parser.add_argument('outfile', nargs='?', type=argparse.FileType('w'),
787 ... default=sys.stdout)
Georg Brandld2decd92010-03-02 22:17:38 +0000788 >>> parser.parse_args(['input.txt', 'output.txt'])
Georg Brandl585bbb92011-01-09 09:33:09 +0000789 Namespace(infile=<open file 'input.txt', mode 'r' at 0x...>,
790 outfile=<open file 'output.txt', mode 'w' at 0x...>)
Georg Brandld2decd92010-03-02 22:17:38 +0000791 >>> parser.parse_args([])
Georg Brandl585bbb92011-01-09 09:33:09 +0000792 Namespace(infile=<open file '<stdin>', mode 'r' at 0x...>,
793 outfile=<open file '<stdout>', mode 'w' at 0x...>)
Benjamin Petersona39e9662010-03-02 22:05:59 +0000794
Georg Brandld2decd92010-03-02 22:17:38 +0000795* ``'*'``. All command-line args present are gathered into a list. Note that
796 it generally doesn't make much sense to have more than one positional argument
797 with ``nargs='*'``, but multiple optional arguments with ``nargs='*'`` is
798 possible. For example::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000799
Georg Brandld2decd92010-03-02 22:17:38 +0000800 >>> parser = argparse.ArgumentParser()
801 >>> parser.add_argument('--foo', nargs='*')
802 >>> parser.add_argument('--bar', nargs='*')
803 >>> parser.add_argument('baz', nargs='*')
804 >>> parser.parse_args('a b --foo x y --bar 1 2'.split())
805 Namespace(bar=['1', '2'], baz=['a', 'b'], foo=['x', 'y'])
Benjamin Petersona39e9662010-03-02 22:05:59 +0000806
807* ``'+'``. Just like ``'*'``, all command-line args present are gathered into a
808 list. Additionally, an error message will be generated if there wasn't at
809 least one command-line arg present. For example::
810
Georg Brandld2decd92010-03-02 22:17:38 +0000811 >>> parser = argparse.ArgumentParser(prog='PROG')
812 >>> parser.add_argument('foo', nargs='+')
813 >>> parser.parse_args('a b'.split())
814 Namespace(foo=['a', 'b'])
815 >>> parser.parse_args(''.split())
816 usage: PROG [-h] foo [foo ...]
817 PROG: error: too few arguments
Benjamin Petersona39e9662010-03-02 22:05:59 +0000818
819If the ``nargs`` keyword argument is not provided, the number of args consumed
Georg Brandld2decd92010-03-02 22:17:38 +0000820is determined by the action_. Generally this means a single command-line arg
Benjamin Petersona39e9662010-03-02 22:05:59 +0000821will be consumed and a single item (not a list) will be produced.
822
823
824const
825^^^^^
826
827The ``const`` argument of :meth:`add_argument` is used to hold constant values
828that are not read from the command line but are required for the various
829ArgumentParser actions. The two most common uses of it are:
830
831* When :meth:`add_argument` is called with ``action='store_const'`` or
832 ``action='append_const'``. These actions add the ``const`` value to one of
833 the attributes of the object returned by :meth:`parse_args`. See the action_
834 description for examples.
835
836* When :meth:`add_argument` is called with option strings (like ``-f`` or
Georg Brandld2decd92010-03-02 22:17:38 +0000837 ``--foo``) and ``nargs='?'``. This creates an optional argument that can be
Ezio Melotti12125822011-04-16 23:04:51 +0300838 followed by zero or one command-line args. When parsing the command line, if
Benjamin Petersona39e9662010-03-02 22:05:59 +0000839 the option string is encountered with no command-line arg following it, the
840 value of ``const`` will be assumed instead. See the nargs_ description for
841 examples.
842
843The ``const`` keyword argument defaults to ``None``.
844
845
846default
847^^^^^^^
848
849All optional arguments and some positional arguments may be omitted at the
Ezio Melotti12125822011-04-16 23:04:51 +0300850command line. The ``default`` keyword argument of :meth:`add_argument`, whose
Benjamin Petersona39e9662010-03-02 22:05:59 +0000851value defaults to ``None``, specifies what value should be used if the
852command-line arg is not present. For optional arguments, the ``default`` value
853is used when the option string was not present at the command line::
854
855 >>> parser = argparse.ArgumentParser()
856 >>> parser.add_argument('--foo', default=42)
857 >>> parser.parse_args('--foo 2'.split())
858 Namespace(foo='2')
859 >>> parser.parse_args(''.split())
860 Namespace(foo=42)
861
862For positional arguments with nargs_ ``='?'`` or ``'*'``, the ``default`` value
863is used when no command-line arg was present::
864
865 >>> parser = argparse.ArgumentParser()
866 >>> parser.add_argument('foo', nargs='?', default=42)
867 >>> parser.parse_args('a'.split())
868 Namespace(foo='a')
869 >>> parser.parse_args(''.split())
870 Namespace(foo=42)
871
872
Benjamin Peterson90c58022010-03-03 01:55:09 +0000873Providing ``default=argparse.SUPPRESS`` causes no attribute to be added if the
874command-line argument was not present.::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000875
876 >>> parser = argparse.ArgumentParser()
877 >>> parser.add_argument('--foo', default=argparse.SUPPRESS)
878 >>> parser.parse_args([])
879 Namespace()
880 >>> parser.parse_args(['--foo', '1'])
881 Namespace(foo='1')
882
883
884type
885^^^^
886
887By default, ArgumentParser objects read command-line args in as simple strings.
888However, quite often the command-line string should instead be interpreted as
Benjamin Peterson90c58022010-03-03 01:55:09 +0000889another type, like a :class:`float`, :class:`int` or :class:`file`. The
890``type`` keyword argument of :meth:`add_argument` allows any necessary
Georg Brandl21e99f42010-03-07 15:23:59 +0000891type-checking and type-conversions to be performed. Many common built-in types
Benjamin Peterson90c58022010-03-03 01:55:09 +0000892can be used directly as the value of the ``type`` argument::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000893
894 >>> parser = argparse.ArgumentParser()
895 >>> parser.add_argument('foo', type=int)
896 >>> parser.add_argument('bar', type=file)
897 >>> parser.parse_args('2 temp.txt'.split())
898 Namespace(bar=<open file 'temp.txt', mode 'r' at 0x...>, foo=2)
899
900To ease the use of various types of files, the argparse module provides the
901factory FileType which takes the ``mode=`` and ``bufsize=`` arguments of the
Georg Brandld2decd92010-03-02 22:17:38 +0000902``file`` object. For example, ``FileType('w')`` can be used to create a
Benjamin Petersona39e9662010-03-02 22:05:59 +0000903writable file::
904
905 >>> parser = argparse.ArgumentParser()
906 >>> parser.add_argument('bar', type=argparse.FileType('w'))
907 >>> parser.parse_args(['out.txt'])
908 Namespace(bar=<open file 'out.txt', mode 'w' at 0x...>)
909
Benjamin Peterson90c58022010-03-03 01:55:09 +0000910``type=`` can take any callable that takes a single string argument and returns
911the type-converted value::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000912
913 >>> def perfect_square(string):
914 ... value = int(string)
915 ... sqrt = math.sqrt(value)
916 ... if sqrt != int(sqrt):
917 ... msg = "%r is not a perfect square" % string
918 ... raise argparse.ArgumentTypeError(msg)
919 ... return value
920 ...
921 >>> parser = argparse.ArgumentParser(prog='PROG')
922 >>> parser.add_argument('foo', type=perfect_square)
923 >>> parser.parse_args('9'.split())
924 Namespace(foo=9)
925 >>> parser.parse_args('7'.split())
926 usage: PROG [-h] foo
927 PROG: error: argument foo: '7' is not a perfect square
928
Benjamin Peterson90c58022010-03-03 01:55:09 +0000929The choices_ keyword argument may be more convenient for type checkers that
930simply check against a range of values::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000931
932 >>> parser = argparse.ArgumentParser(prog='PROG')
933 >>> parser.add_argument('foo', type=int, choices=xrange(5, 10))
934 >>> parser.parse_args('7'.split())
935 Namespace(foo=7)
936 >>> parser.parse_args('11'.split())
937 usage: PROG [-h] {5,6,7,8,9}
938 PROG: error: argument foo: invalid choice: 11 (choose from 5, 6, 7, 8, 9)
939
940See the choices_ section for more details.
941
942
943choices
944^^^^^^^
945
946Some command-line args should be selected from a restricted set of values.
Benjamin Peterson90c58022010-03-03 01:55:09 +0000947These can be handled by passing a container object as the ``choices`` keyword
Ezio Melotti12125822011-04-16 23:04:51 +0300948argument to :meth:`add_argument`. When the command line is parsed, arg values
Benjamin Peterson90c58022010-03-03 01:55:09 +0000949will be checked, and an error message will be displayed if the arg was not one
950of the acceptable values::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000951
952 >>> parser = argparse.ArgumentParser(prog='PROG')
953 >>> parser.add_argument('foo', choices='abc')
954 >>> parser.parse_args('c'.split())
955 Namespace(foo='c')
956 >>> parser.parse_args('X'.split())
957 usage: PROG [-h] {a,b,c}
958 PROG: error: argument foo: invalid choice: 'X' (choose from 'a', 'b', 'c')
959
960Note that inclusion in the ``choices`` container is checked after any type_
961conversions have been performed, so the type of the objects in the ``choices``
962container should match the type_ specified::
963
964 >>> parser = argparse.ArgumentParser(prog='PROG')
965 >>> parser.add_argument('foo', type=complex, choices=[1, 1j])
966 >>> parser.parse_args('1j'.split())
967 Namespace(foo=1j)
968 >>> parser.parse_args('-- -4'.split())
969 usage: PROG [-h] {1,1j}
970 PROG: error: argument foo: invalid choice: (-4+0j) (choose from 1, 1j)
971
972Any object that supports the ``in`` operator can be passed as the ``choices``
Georg Brandld2decd92010-03-02 22:17:38 +0000973value, so :class:`dict` objects, :class:`set` objects, custom containers,
974etc. are all supported.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000975
976
977required
978^^^^^^^^
979
Ezio Melotti01b600c2011-04-21 16:12:17 +0300980In general, the :mod:`argparse` module assumes that flags like ``-f`` and ``--bar``
Ezio Melotti12125822011-04-16 23:04:51 +0300981indicate *optional* arguments, which can always be omitted at the command line.
Benjamin Peterson90c58022010-03-03 01:55:09 +0000982To make an option *required*, ``True`` can be specified for the ``required=``
983keyword argument to :meth:`add_argument`::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000984
985 >>> parser = argparse.ArgumentParser()
986 >>> parser.add_argument('--foo', required=True)
987 >>> parser.parse_args(['--foo', 'BAR'])
988 Namespace(foo='BAR')
989 >>> parser.parse_args([])
990 usage: argparse.py [-h] [--foo FOO]
991 argparse.py: error: option --foo is required
992
993As the example shows, if an option is marked as ``required``, :meth:`parse_args`
994will report an error if that option is not present at the command line.
995
Benjamin Peterson90c58022010-03-03 01:55:09 +0000996.. note::
997
998 Required options are generally considered bad form because users expect
999 *options* to be *optional*, and thus they should be avoided when possible.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001000
1001
1002help
1003^^^^
1004
Benjamin Peterson90c58022010-03-03 01:55:09 +00001005The ``help`` value is a string containing a brief description of the argument.
1006When a user requests help (usually by using ``-h`` or ``--help`` at the
Ezio Melotti12125822011-04-16 23:04:51 +03001007command line), these ``help`` descriptions will be displayed with each
Georg Brandld2decd92010-03-02 22:17:38 +00001008argument::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001009
1010 >>> parser = argparse.ArgumentParser(prog='frobble')
1011 >>> parser.add_argument('--foo', action='store_true',
1012 ... help='foo the bars before frobbling')
1013 >>> parser.add_argument('bar', nargs='+',
1014 ... help='one of the bars to be frobbled')
1015 >>> parser.parse_args('-h'.split())
1016 usage: frobble [-h] [--foo] bar [bar ...]
1017
1018 positional arguments:
1019 bar one of the bars to be frobbled
1020
1021 optional arguments:
1022 -h, --help show this help message and exit
1023 --foo foo the bars before frobbling
1024
1025The ``help`` strings can include various format specifiers to avoid repetition
1026of things like the program name or the argument default_. The available
1027specifiers include the program name, ``%(prog)s`` and most keyword arguments to
1028:meth:`add_argument`, e.g. ``%(default)s``, ``%(type)s``, etc.::
1029
1030 >>> parser = argparse.ArgumentParser(prog='frobble')
1031 >>> parser.add_argument('bar', nargs='?', type=int, default=42,
1032 ... help='the bar to %(prog)s (default: %(default)s)')
1033 >>> parser.print_help()
1034 usage: frobble [-h] [bar]
1035
1036 positional arguments:
1037 bar the bar to frobble (default: 42)
1038
1039 optional arguments:
1040 -h, --help show this help message and exit
1041
1042
1043metavar
1044^^^^^^^
1045
Benjamin Peterson90c58022010-03-03 01:55:09 +00001046When :class:`ArgumentParser` generates help messages, it need some way to refer
Georg Brandld2decd92010-03-02 22:17:38 +00001047to each expected argument. By default, ArgumentParser objects use the dest_
Benjamin Petersona39e9662010-03-02 22:05:59 +00001048value as the "name" of each object. By default, for positional argument
1049actions, the dest_ value is used directly, and for optional argument actions,
Benjamin Peterson90c58022010-03-03 01:55:09 +00001050the dest_ value is uppercased. So, a single positional argument with
1051``dest='bar'`` will that argument will be referred to as ``bar``. A single
1052optional argument ``--foo`` that should be followed by a single command-line arg
1053will be referred to as ``FOO``. An example::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001054
1055 >>> parser = argparse.ArgumentParser()
1056 >>> parser.add_argument('--foo')
1057 >>> parser.add_argument('bar')
1058 >>> parser.parse_args('X --foo Y'.split())
1059 Namespace(bar='X', foo='Y')
1060 >>> parser.print_help()
1061 usage: [-h] [--foo FOO] bar
1062
1063 positional arguments:
1064 bar
1065
1066 optional arguments:
1067 -h, --help show this help message and exit
1068 --foo FOO
1069
Benjamin Peterson90c58022010-03-03 01:55:09 +00001070An alternative name can be specified with ``metavar``::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001071
1072 >>> parser = argparse.ArgumentParser()
1073 >>> parser.add_argument('--foo', metavar='YYY')
1074 >>> parser.add_argument('bar', metavar='XXX')
1075 >>> parser.parse_args('X --foo Y'.split())
1076 Namespace(bar='X', foo='Y')
1077 >>> parser.print_help()
1078 usage: [-h] [--foo YYY] XXX
1079
1080 positional arguments:
1081 XXX
1082
1083 optional arguments:
1084 -h, --help show this help message and exit
1085 --foo YYY
1086
1087Note that ``metavar`` only changes the *displayed* name - the name of the
1088attribute on the :meth:`parse_args` object is still determined by the dest_
1089value.
1090
1091Different values of ``nargs`` may cause the metavar to be used multiple times.
Benjamin Peterson90c58022010-03-03 01:55:09 +00001092Providing a tuple to ``metavar`` specifies a different display for each of the
1093arguments::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001094
1095 >>> parser = argparse.ArgumentParser(prog='PROG')
1096 >>> parser.add_argument('-x', nargs=2)
1097 >>> parser.add_argument('--foo', nargs=2, metavar=('bar', 'baz'))
1098 >>> parser.print_help()
1099 usage: PROG [-h] [-x X X] [--foo bar baz]
1100
1101 optional arguments:
1102 -h, --help show this help message and exit
1103 -x X X
1104 --foo bar baz
1105
1106
1107dest
1108^^^^
1109
Benjamin Peterson90c58022010-03-03 01:55:09 +00001110Most :class:`ArgumentParser` actions add some value as an attribute of the
1111object returned by :meth:`parse_args`. The name of this attribute is determined
1112by the ``dest`` keyword argument of :meth:`add_argument`. For positional
1113argument actions, ``dest`` is normally supplied as the first argument to
Benjamin Petersona39e9662010-03-02 22:05:59 +00001114:meth:`add_argument`::
1115
1116 >>> parser = argparse.ArgumentParser()
1117 >>> parser.add_argument('bar')
1118 >>> parser.parse_args('XXX'.split())
1119 Namespace(bar='XXX')
1120
1121For optional argument actions, the value of ``dest`` is normally inferred from
Benjamin Peterson90c58022010-03-03 01:55:09 +00001122the option strings. :class:`ArgumentParser` generates the value of ``dest`` by
Benjamin Petersona39e9662010-03-02 22:05:59 +00001123taking the first long option string and stripping away the initial ``'--'``
1124string. If no long option strings were supplied, ``dest`` will be derived from
1125the first short option string by stripping the initial ``'-'`` character. Any
Georg Brandld2decd92010-03-02 22:17:38 +00001126internal ``'-'`` characters will be converted to ``'_'`` characters to make sure
1127the string is a valid attribute name. The examples below illustrate this
Benjamin Petersona39e9662010-03-02 22:05:59 +00001128behavior::
1129
1130 >>> parser = argparse.ArgumentParser()
1131 >>> parser.add_argument('-f', '--foo-bar', '--foo')
1132 >>> parser.add_argument('-x', '-y')
1133 >>> parser.parse_args('-f 1 -x 2'.split())
1134 Namespace(foo_bar='1', x='2')
1135 >>> parser.parse_args('--foo 1 -y 2'.split())
1136 Namespace(foo_bar='1', x='2')
1137
Benjamin Peterson90c58022010-03-03 01:55:09 +00001138``dest`` allows a custom attribute name to be provided::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001139
1140 >>> parser = argparse.ArgumentParser()
1141 >>> parser.add_argument('--foo', dest='bar')
1142 >>> parser.parse_args('--foo XXX'.split())
1143 Namespace(bar='XXX')
1144
1145
1146The parse_args() method
1147-----------------------
1148
Georg Brandlb8d0e362010-11-26 07:53:50 +00001149.. method:: ArgumentParser.parse_args(args=None, namespace=None)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001150
Benjamin Peterson90c58022010-03-03 01:55:09 +00001151 Convert argument strings to objects and assign them as attributes of the
Georg Brandld2decd92010-03-02 22:17:38 +00001152 namespace. Return the populated namespace.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001153
1154 Previous calls to :meth:`add_argument` determine exactly what objects are
1155 created and how they are assigned. See the documentation for
1156 :meth:`add_argument` for details.
1157
Georg Brandld2decd92010-03-02 22:17:38 +00001158 By default, the arg strings are taken from :data:`sys.argv`, and a new empty
Benjamin Peterson90c58022010-03-03 01:55:09 +00001159 :class:`Namespace` object is created for the attributes.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001160
Georg Brandlb8d0e362010-11-26 07:53:50 +00001161
Benjamin Petersona39e9662010-03-02 22:05:59 +00001162Option value syntax
1163^^^^^^^^^^^^^^^^^^^
1164
1165The :meth:`parse_args` method supports several ways of specifying the value of
Georg Brandld2decd92010-03-02 22:17:38 +00001166an option (if it takes one). In the simplest case, the option and its value are
Benjamin Petersona39e9662010-03-02 22:05:59 +00001167passed as two separate arguments::
1168
1169 >>> parser = argparse.ArgumentParser(prog='PROG')
1170 >>> parser.add_argument('-x')
1171 >>> parser.add_argument('--foo')
1172 >>> parser.parse_args('-x X'.split())
1173 Namespace(foo=None, x='X')
1174 >>> parser.parse_args('--foo FOO'.split())
1175 Namespace(foo='FOO', x=None)
1176
Benjamin Peterson90c58022010-03-03 01:55:09 +00001177For long options (options with names longer than a single character), the option
Ezio Melotti12125822011-04-16 23:04:51 +03001178and value can also be passed as a single command-line argument, using ``=`` to
Georg Brandld2decd92010-03-02 22:17:38 +00001179separate them::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001180
1181 >>> parser.parse_args('--foo=FOO'.split())
1182 Namespace(foo='FOO', x=None)
1183
Benjamin Peterson90c58022010-03-03 01:55:09 +00001184For short options (options only one character long), the option and its value
1185can be concatenated::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001186
1187 >>> parser.parse_args('-xX'.split())
1188 Namespace(foo=None, x='X')
1189
Benjamin Peterson90c58022010-03-03 01:55:09 +00001190Several short options can be joined together, using only a single ``-`` prefix,
1191as long as only the last option (or none of them) requires a value::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001192
1193 >>> parser = argparse.ArgumentParser(prog='PROG')
1194 >>> parser.add_argument('-x', action='store_true')
1195 >>> parser.add_argument('-y', action='store_true')
1196 >>> parser.add_argument('-z')
1197 >>> parser.parse_args('-xyzZ'.split())
1198 Namespace(x=True, y=True, z='Z')
1199
1200
1201Invalid arguments
1202^^^^^^^^^^^^^^^^^
1203
Ezio Melotti12125822011-04-16 23:04:51 +03001204While parsing the command line, ``parse_args`` checks for a variety of errors,
Benjamin Petersona39e9662010-03-02 22:05:59 +00001205including ambiguous options, invalid types, invalid options, wrong number of
Georg Brandld2decd92010-03-02 22:17:38 +00001206positional arguments, etc. When it encounters such an error, it exits and
Benjamin Petersona39e9662010-03-02 22:05:59 +00001207prints the error along with a usage message::
1208
1209 >>> parser = argparse.ArgumentParser(prog='PROG')
1210 >>> parser.add_argument('--foo', type=int)
1211 >>> parser.add_argument('bar', nargs='?')
1212
1213 >>> # invalid type
1214 >>> parser.parse_args(['--foo', 'spam'])
1215 usage: PROG [-h] [--foo FOO] [bar]
1216 PROG: error: argument --foo: invalid int value: 'spam'
1217
1218 >>> # invalid option
1219 >>> parser.parse_args(['--bar'])
1220 usage: PROG [-h] [--foo FOO] [bar]
1221 PROG: error: no such option: --bar
1222
1223 >>> # wrong number of arguments
1224 >>> parser.parse_args(['spam', 'badger'])
1225 usage: PROG [-h] [--foo FOO] [bar]
1226 PROG: error: extra arguments found: badger
1227
1228
1229Arguments containing ``"-"``
1230^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1231
1232The ``parse_args`` method attempts to give errors whenever the user has clearly
Georg Brandld2decd92010-03-02 22:17:38 +00001233made a mistake, but some situations are inherently ambiguous. For example, the
Benjamin Petersona39e9662010-03-02 22:05:59 +00001234command-line arg ``'-1'`` could either be an attempt to specify an option or an
Georg Brandld2decd92010-03-02 22:17:38 +00001235attempt to provide a positional argument. The ``parse_args`` method is cautious
Benjamin Petersona39e9662010-03-02 22:05:59 +00001236here: positional arguments may only begin with ``'-'`` if they look like
1237negative numbers and there are no options in the parser that look like negative
1238numbers::
1239
1240 >>> parser = argparse.ArgumentParser(prog='PROG')
1241 >>> parser.add_argument('-x')
1242 >>> parser.add_argument('foo', nargs='?')
1243
1244 >>> # no negative number options, so -1 is a positional argument
1245 >>> parser.parse_args(['-x', '-1'])
1246 Namespace(foo=None, x='-1')
1247
1248 >>> # no negative number options, so -1 and -5 are positional arguments
1249 >>> parser.parse_args(['-x', '-1', '-5'])
1250 Namespace(foo='-5', x='-1')
1251
1252 >>> parser = argparse.ArgumentParser(prog='PROG')
1253 >>> parser.add_argument('-1', dest='one')
1254 >>> parser.add_argument('foo', nargs='?')
1255
1256 >>> # negative number options present, so -1 is an option
1257 >>> parser.parse_args(['-1', 'X'])
1258 Namespace(foo=None, one='X')
1259
1260 >>> # negative number options present, so -2 is an option
1261 >>> parser.parse_args(['-2'])
1262 usage: PROG [-h] [-1 ONE] [foo]
1263 PROG: error: no such option: -2
1264
1265 >>> # negative number options present, so both -1s are options
1266 >>> parser.parse_args(['-1', '-1'])
1267 usage: PROG [-h] [-1 ONE] [foo]
1268 PROG: error: argument -1: expected one argument
1269
1270If you have positional arguments that must begin with ``'-'`` and don't look
1271like negative numbers, you can insert the pseudo-argument ``'--'`` which tells
1272``parse_args`` that everything after that is a positional argument::
1273
1274 >>> parser.parse_args(['--', '-f'])
1275 Namespace(foo='-f', one=None)
1276
1277
1278Argument abbreviations
1279^^^^^^^^^^^^^^^^^^^^^^
1280
Benjamin Peterson90c58022010-03-03 01:55:09 +00001281The :meth:`parse_args` method allows long options to be abbreviated if the
Benjamin Petersona39e9662010-03-02 22:05:59 +00001282abbreviation is unambiguous::
1283
1284 >>> parser = argparse.ArgumentParser(prog='PROG')
1285 >>> parser.add_argument('-bacon')
1286 >>> parser.add_argument('-badger')
1287 >>> parser.parse_args('-bac MMM'.split())
1288 Namespace(bacon='MMM', badger=None)
1289 >>> parser.parse_args('-bad WOOD'.split())
1290 Namespace(bacon=None, badger='WOOD')
1291 >>> parser.parse_args('-ba BA'.split())
1292 usage: PROG [-h] [-bacon BACON] [-badger BADGER]
1293 PROG: error: ambiguous option: -ba could match -badger, -bacon
1294
Benjamin Peterson90c58022010-03-03 01:55:09 +00001295An error is produced for arguments that could produce more than one options.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001296
1297
1298Beyond ``sys.argv``
1299^^^^^^^^^^^^^^^^^^^
1300
Georg Brandld2decd92010-03-02 22:17:38 +00001301Sometimes it may be useful to have an ArgumentParser parse args other than those
1302of :data:`sys.argv`. This can be accomplished by passing a list of strings to
Benjamin Peterson90c58022010-03-03 01:55:09 +00001303``parse_args``. This is useful for testing at the interactive prompt::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001304
1305 >>> parser = argparse.ArgumentParser()
1306 >>> parser.add_argument(
1307 ... 'integers', metavar='int', type=int, choices=xrange(10),
1308 ... nargs='+', help='an integer in the range 0..9')
1309 >>> parser.add_argument(
1310 ... '--sum', dest='accumulate', action='store_const', const=sum,
1311 ... default=max, help='sum the integers (default: find the max)')
1312 >>> parser.parse_args(['1', '2', '3', '4'])
1313 Namespace(accumulate=<built-in function max>, integers=[1, 2, 3, 4])
1314 >>> parser.parse_args('1 2 3 4 --sum'.split())
1315 Namespace(accumulate=<built-in function sum>, integers=[1, 2, 3, 4])
1316
1317
Steven Bethard3f69a052011-03-26 19:59:02 +01001318The Namespace object
1319^^^^^^^^^^^^^^^^^^^^
1320
1321By default, :meth:`parse_args` will return a new object of type :class:`Namespace`
1322where the necessary attributes have been set. This class is deliberately simple,
1323just an :class:`object` subclass with a readable string representation. If you
1324prefer to have dict-like view of the attributes, you can use the standard Python
1325idiom via :func:`vars`::
1326
1327 >>> parser = argparse.ArgumentParser()
1328 >>> parser.add_argument('--foo')
1329 >>> args = parser.parse_args(['--foo', 'BAR'])
1330 >>> vars(args)
1331 {'foo': 'BAR'}
Benjamin Petersona39e9662010-03-02 22:05:59 +00001332
Benjamin Peterson90c58022010-03-03 01:55:09 +00001333It may also be useful to have an :class:`ArgumentParser` assign attributes to an
Steven Bethard3f69a052011-03-26 19:59:02 +01001334already existing object, rather than a new :class:`Namespace` object. This can
1335be achieved by specifying the ``namespace=`` keyword argument::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001336
1337 >>> class C(object):
1338 ... pass
1339 ...
1340 >>> c = C()
1341 >>> parser = argparse.ArgumentParser()
1342 >>> parser.add_argument('--foo')
1343 >>> parser.parse_args(args=['--foo', 'BAR'], namespace=c)
1344 >>> c.foo
1345 'BAR'
1346
1347
1348Other utilities
1349---------------
1350
1351Sub-commands
1352^^^^^^^^^^^^
1353
Benjamin Peterson90c58022010-03-03 01:55:09 +00001354.. method:: ArgumentParser.add_subparsers()
Benjamin Petersona39e9662010-03-02 22:05:59 +00001355
Benjamin Peterson90c58022010-03-03 01:55:09 +00001356 Many programs split up their functionality into a number of sub-commands,
Georg Brandld2decd92010-03-02 22:17:38 +00001357 for example, the ``svn`` program can invoke sub-commands like ``svn
Benjamin Peterson90c58022010-03-03 01:55:09 +00001358 checkout``, ``svn update``, and ``svn commit``. Splitting up functionality
Georg Brandld2decd92010-03-02 22:17:38 +00001359 this way can be a particularly good idea when a program performs several
1360 different functions which require different kinds of command-line arguments.
Benjamin Peterson90c58022010-03-03 01:55:09 +00001361 :class:`ArgumentParser` supports the creation of such sub-commands with the
Georg Brandld2decd92010-03-02 22:17:38 +00001362 :meth:`add_subparsers` method. The :meth:`add_subparsers` method is normally
1363 called with no arguments and returns an special action object. This object
1364 has a single method, ``add_parser``, which takes a command name and any
Benjamin Peterson90c58022010-03-03 01:55:09 +00001365 :class:`ArgumentParser` constructor arguments, and returns an
1366 :class:`ArgumentParser` object that can be modified as usual.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001367
1368 Some example usage::
1369
1370 >>> # create the top-level parser
1371 >>> parser = argparse.ArgumentParser(prog='PROG')
1372 >>> parser.add_argument('--foo', action='store_true', help='foo help')
1373 >>> subparsers = parser.add_subparsers(help='sub-command help')
1374 >>>
1375 >>> # create the parser for the "a" command
1376 >>> parser_a = subparsers.add_parser('a', help='a help')
1377 >>> parser_a.add_argument('bar', type=int, help='bar help')
1378 >>>
1379 >>> # create the parser for the "b" command
1380 >>> parser_b = subparsers.add_parser('b', help='b help')
1381 >>> parser_b.add_argument('--baz', choices='XYZ', help='baz help')
1382 >>>
1383 >>> # parse some arg lists
1384 >>> parser.parse_args(['a', '12'])
1385 Namespace(bar=12, foo=False)
1386 >>> parser.parse_args(['--foo', 'b', '--baz', 'Z'])
1387 Namespace(baz='Z', foo=True)
1388
1389 Note that the object returned by :meth:`parse_args` will only contain
1390 attributes for the main parser and the subparser that was selected by the
1391 command line (and not any other subparsers). So in the example above, when
Georg Brandld2decd92010-03-02 22:17:38 +00001392 the ``"a"`` command is specified, only the ``foo`` and ``bar`` attributes are
1393 present, and when the ``"b"`` command is specified, only the ``foo`` and
Benjamin Petersona39e9662010-03-02 22:05:59 +00001394 ``baz`` attributes are present.
1395
1396 Similarly, when a help message is requested from a subparser, only the help
Georg Brandld2decd92010-03-02 22:17:38 +00001397 for that particular parser will be printed. The help message will not
Benjamin Peterson90c58022010-03-03 01:55:09 +00001398 include parent parser or sibling parser messages. (A help message for each
1399 subparser command, however, can be given by supplying the ``help=`` argument
1400 to ``add_parser`` as above.)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001401
1402 ::
1403
1404 >>> parser.parse_args(['--help'])
1405 usage: PROG [-h] [--foo] {a,b} ...
1406
1407 positional arguments:
1408 {a,b} sub-command help
1409 a a help
1410 b b help
1411
1412 optional arguments:
1413 -h, --help show this help message and exit
1414 --foo foo help
1415
1416 >>> parser.parse_args(['a', '--help'])
1417 usage: PROG a [-h] bar
1418
1419 positional arguments:
1420 bar bar help
1421
1422 optional arguments:
1423 -h, --help show this help message and exit
1424
1425 >>> parser.parse_args(['b', '--help'])
1426 usage: PROG b [-h] [--baz {X,Y,Z}]
1427
1428 optional arguments:
1429 -h, --help show this help message and exit
1430 --baz {X,Y,Z} baz help
1431
Georg Brandld2decd92010-03-02 22:17:38 +00001432 The :meth:`add_subparsers` method also supports ``title`` and ``description``
1433 keyword arguments. When either is present, the subparser's commands will
1434 appear in their own group in the help output. For example::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001435
1436 >>> parser = argparse.ArgumentParser()
1437 >>> subparsers = parser.add_subparsers(title='subcommands',
1438 ... description='valid subcommands',
1439 ... help='additional help')
1440 >>> subparsers.add_parser('foo')
1441 >>> subparsers.add_parser('bar')
1442 >>> parser.parse_args(['-h'])
1443 usage: [-h] {foo,bar} ...
1444
1445 optional arguments:
1446 -h, --help show this help message and exit
1447
1448 subcommands:
1449 valid subcommands
1450
1451 {foo,bar} additional help
1452
1453
Georg Brandld2decd92010-03-02 22:17:38 +00001454 One particularly effective way of handling sub-commands is to combine the use
1455 of the :meth:`add_subparsers` method with calls to :meth:`set_defaults` so
1456 that each subparser knows which Python function it should execute. For
Benjamin Petersona39e9662010-03-02 22:05:59 +00001457 example::
1458
1459 >>> # sub-command functions
1460 >>> def foo(args):
1461 ... print args.x * args.y
1462 ...
1463 >>> def bar(args):
1464 ... print '((%s))' % args.z
1465 ...
1466 >>> # create the top-level parser
1467 >>> parser = argparse.ArgumentParser()
1468 >>> subparsers = parser.add_subparsers()
1469 >>>
1470 >>> # create the parser for the "foo" command
1471 >>> parser_foo = subparsers.add_parser('foo')
1472 >>> parser_foo.add_argument('-x', type=int, default=1)
1473 >>> parser_foo.add_argument('y', type=float)
1474 >>> parser_foo.set_defaults(func=foo)
1475 >>>
1476 >>> # create the parser for the "bar" command
1477 >>> parser_bar = subparsers.add_parser('bar')
1478 >>> parser_bar.add_argument('z')
1479 >>> parser_bar.set_defaults(func=bar)
1480 >>>
1481 >>> # parse the args and call whatever function was selected
1482 >>> args = parser.parse_args('foo 1 -x 2'.split())
1483 >>> args.func(args)
1484 2.0
1485 >>>
1486 >>> # parse the args and call whatever function was selected
1487 >>> args = parser.parse_args('bar XYZYX'.split())
1488 >>> args.func(args)
1489 ((XYZYX))
1490
Benjamin Peterson90c58022010-03-03 01:55:09 +00001491 This way, you can let :meth:`parse_args` does the job of calling the
1492 appropriate function after argument parsing is complete. Associating
1493 functions with actions like this is typically the easiest way to handle the
1494 different actions for each of your subparsers. However, if it is necessary
1495 to check the name of the subparser that was invoked, the ``dest`` keyword
1496 argument to the :meth:`add_subparsers` call will work::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001497
1498 >>> parser = argparse.ArgumentParser()
1499 >>> subparsers = parser.add_subparsers(dest='subparser_name')
1500 >>> subparser1 = subparsers.add_parser('1')
1501 >>> subparser1.add_argument('-x')
1502 >>> subparser2 = subparsers.add_parser('2')
1503 >>> subparser2.add_argument('y')
1504 >>> parser.parse_args(['2', 'frobble'])
1505 Namespace(subparser_name='2', y='frobble')
1506
1507
1508FileType objects
1509^^^^^^^^^^^^^^^^
1510
1511.. class:: FileType(mode='r', bufsize=None)
1512
1513 The :class:`FileType` factory creates objects that can be passed to the type
Benjamin Peterson90c58022010-03-03 01:55:09 +00001514 argument of :meth:`ArgumentParser.add_argument`. Arguments that have
1515 :class:`FileType` objects as their type will open command-line args as files
1516 with the requested modes and buffer sizes:
Benjamin Petersona39e9662010-03-02 22:05:59 +00001517
1518 >>> parser = argparse.ArgumentParser()
1519 >>> parser.add_argument('--output', type=argparse.FileType('wb', 0))
1520 >>> parser.parse_args(['--output', 'out'])
1521 Namespace(output=<open file 'out', mode 'wb' at 0x...>)
1522
1523 FileType objects understand the pseudo-argument ``'-'`` and automatically
1524 convert this into ``sys.stdin`` for readable :class:`FileType` objects and
1525 ``sys.stdout`` for writable :class:`FileType` objects:
1526
1527 >>> parser = argparse.ArgumentParser()
1528 >>> parser.add_argument('infile', type=argparse.FileType('r'))
1529 >>> parser.parse_args(['-'])
1530 Namespace(infile=<open file '<stdin>', mode 'r' at 0x...>)
1531
1532
1533Argument groups
1534^^^^^^^^^^^^^^^
1535
Georg Brandlb8d0e362010-11-26 07:53:50 +00001536.. method:: ArgumentParser.add_argument_group(title=None, description=None)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001537
Benjamin Peterson90c58022010-03-03 01:55:09 +00001538 By default, :class:`ArgumentParser` groups command-line arguments into
Benjamin Petersona39e9662010-03-02 22:05:59 +00001539 "positional arguments" and "optional arguments" when displaying help
1540 messages. When there is a better conceptual grouping of arguments than this
1541 default one, appropriate groups can be created using the
1542 :meth:`add_argument_group` method::
1543
1544 >>> parser = argparse.ArgumentParser(prog='PROG', add_help=False)
1545 >>> group = parser.add_argument_group('group')
1546 >>> group.add_argument('--foo', help='foo help')
1547 >>> group.add_argument('bar', help='bar help')
1548 >>> parser.print_help()
1549 usage: PROG [--foo FOO] bar
1550
1551 group:
1552 bar bar help
1553 --foo FOO foo help
1554
1555 The :meth:`add_argument_group` method returns an argument group object which
Benjamin Peterson90c58022010-03-03 01:55:09 +00001556 has an :meth:`~ArgumentParser.add_argument` method just like a regular
1557 :class:`ArgumentParser`. When an argument is added to the group, the parser
1558 treats it just like a normal argument, but displays the argument in a
1559 separate group for help messages. The :meth:`add_argument_group` method
Georg Brandlb8d0e362010-11-26 07:53:50 +00001560 accepts *title* and *description* arguments which can be used to
Benjamin Peterson90c58022010-03-03 01:55:09 +00001561 customize this display::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001562
1563 >>> parser = argparse.ArgumentParser(prog='PROG', add_help=False)
1564 >>> group1 = parser.add_argument_group('group1', 'group1 description')
1565 >>> group1.add_argument('foo', help='foo help')
1566 >>> group2 = parser.add_argument_group('group2', 'group2 description')
1567 >>> group2.add_argument('--bar', help='bar help')
1568 >>> parser.print_help()
1569 usage: PROG [--bar BAR] foo
1570
1571 group1:
1572 group1 description
1573
1574 foo foo help
1575
1576 group2:
1577 group2 description
1578
1579 --bar BAR bar help
1580
Benjamin Peterson90c58022010-03-03 01:55:09 +00001581 Note that any arguments not your user defined groups will end up back in the
1582 usual "positional arguments" and "optional arguments" sections.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001583
1584
1585Mutual exclusion
1586^^^^^^^^^^^^^^^^
1587
Georg Brandlb8d0e362010-11-26 07:53:50 +00001588.. method:: add_mutually_exclusive_group(required=False)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001589
Ezio Melotti01b600c2011-04-21 16:12:17 +03001590 Create a mutually exclusive group. :mod:`argparse` will make sure that only
1591 one of the arguments in the mutually exclusive group was present on the
1592 command line::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001593
1594 >>> parser = argparse.ArgumentParser(prog='PROG')
1595 >>> group = parser.add_mutually_exclusive_group()
1596 >>> group.add_argument('--foo', action='store_true')
1597 >>> group.add_argument('--bar', action='store_false')
1598 >>> parser.parse_args(['--foo'])
1599 Namespace(bar=True, foo=True)
1600 >>> parser.parse_args(['--bar'])
1601 Namespace(bar=False, foo=False)
1602 >>> parser.parse_args(['--foo', '--bar'])
1603 usage: PROG [-h] [--foo | --bar]
1604 PROG: error: argument --bar: not allowed with argument --foo
1605
Georg Brandlb8d0e362010-11-26 07:53:50 +00001606 The :meth:`add_mutually_exclusive_group` method also accepts a *required*
Benjamin Petersona39e9662010-03-02 22:05:59 +00001607 argument, to indicate that at least one of the mutually exclusive arguments
1608 is required::
1609
1610 >>> parser = argparse.ArgumentParser(prog='PROG')
1611 >>> group = parser.add_mutually_exclusive_group(required=True)
1612 >>> group.add_argument('--foo', action='store_true')
1613 >>> group.add_argument('--bar', action='store_false')
1614 >>> parser.parse_args([])
1615 usage: PROG [-h] (--foo | --bar)
1616 PROG: error: one of the arguments --foo --bar is required
1617
1618 Note that currently mutually exclusive argument groups do not support the
Georg Brandlb8d0e362010-11-26 07:53:50 +00001619 *title* and *description* arguments of :meth:`add_argument_group`.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001620
1621
1622Parser defaults
1623^^^^^^^^^^^^^^^
1624
Benjamin Peterson90c58022010-03-03 01:55:09 +00001625.. method:: ArgumentParser.set_defaults(**kwargs)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001626
Georg Brandld2decd92010-03-02 22:17:38 +00001627 Most of the time, the attributes of the object returned by :meth:`parse_args`
1628 will be fully determined by inspecting the command-line args and the argument
Benjamin Petersonc516d192010-03-03 02:04:24 +00001629 actions. :meth:`ArgumentParser.set_defaults` allows some additional
Ezio Melotti12125822011-04-16 23:04:51 +03001630 attributes that are determined without any inspection of the command line to
Benjamin Petersonc516d192010-03-03 02:04:24 +00001631 be added::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001632
1633 >>> parser = argparse.ArgumentParser()
1634 >>> parser.add_argument('foo', type=int)
1635 >>> parser.set_defaults(bar=42, baz='badger')
1636 >>> parser.parse_args(['736'])
1637 Namespace(bar=42, baz='badger', foo=736)
1638
Benjamin Peterson90c58022010-03-03 01:55:09 +00001639 Note that parser-level defaults always override argument-level defaults::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001640
1641 >>> parser = argparse.ArgumentParser()
1642 >>> parser.add_argument('--foo', default='bar')
1643 >>> parser.set_defaults(foo='spam')
1644 >>> parser.parse_args([])
1645 Namespace(foo='spam')
1646
Benjamin Peterson90c58022010-03-03 01:55:09 +00001647 Parser-level defaults can be particularly useful when working with multiple
1648 parsers. See the :meth:`~ArgumentParser.add_subparsers` method for an
1649 example of this type.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001650
Benjamin Peterson90c58022010-03-03 01:55:09 +00001651.. method:: ArgumentParser.get_default(dest)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001652
1653 Get the default value for a namespace attribute, as set by either
Benjamin Peterson90c58022010-03-03 01:55:09 +00001654 :meth:`~ArgumentParser.add_argument` or by
1655 :meth:`~ArgumentParser.set_defaults`::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001656
1657 >>> parser = argparse.ArgumentParser()
1658 >>> parser.add_argument('--foo', default='badger')
1659 >>> parser.get_default('foo')
1660 'badger'
1661
1662
1663Printing help
1664^^^^^^^^^^^^^
1665
1666In most typical applications, :meth:`parse_args` will take care of formatting
Benjamin Peterson90c58022010-03-03 01:55:09 +00001667and printing any usage or error messages. However, several formatting methods
1668are available:
Benjamin Petersona39e9662010-03-02 22:05:59 +00001669
Georg Brandlb8d0e362010-11-26 07:53:50 +00001670.. method:: ArgumentParser.print_usage(file=None)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001671
1672 Print a brief description of how the :class:`ArgumentParser` should be
R. David Murray561b96f2011-02-11 17:25:54 +00001673 invoked on the command line. If *file* is ``None``, :data:`sys.stdout` is
Benjamin Petersona39e9662010-03-02 22:05:59 +00001674 assumed.
1675
Georg Brandlb8d0e362010-11-26 07:53:50 +00001676.. method:: ArgumentParser.print_help(file=None)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001677
1678 Print a help message, including the program usage and information about the
Georg Brandlb8d0e362010-11-26 07:53:50 +00001679 arguments registered with the :class:`ArgumentParser`. If *file* is
R. David Murray561b96f2011-02-11 17:25:54 +00001680 ``None``, :data:`sys.stdout` is assumed.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001681
1682There are also variants of these methods that simply return a string instead of
1683printing it:
1684
Georg Brandlb8d0e362010-11-26 07:53:50 +00001685.. method:: ArgumentParser.format_usage()
Benjamin Petersona39e9662010-03-02 22:05:59 +00001686
1687 Return a string containing a brief description of how the
1688 :class:`ArgumentParser` should be invoked on the command line.
1689
Georg Brandlb8d0e362010-11-26 07:53:50 +00001690.. method:: ArgumentParser.format_help()
Benjamin Petersona39e9662010-03-02 22:05:59 +00001691
1692 Return a string containing a help message, including the program usage and
1693 information about the arguments registered with the :class:`ArgumentParser`.
1694
1695
Benjamin Petersona39e9662010-03-02 22:05:59 +00001696Partial parsing
1697^^^^^^^^^^^^^^^
1698
Georg Brandlb8d0e362010-11-26 07:53:50 +00001699.. method:: ArgumentParser.parse_known_args(args=None, namespace=None)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001700
Ezio Melotti12125822011-04-16 23:04:51 +03001701Sometimes a script may only parse a few of the command-line arguments, passing
Benjamin Petersona39e9662010-03-02 22:05:59 +00001702the remaining arguments on to another script or program. In these cases, the
Georg Brandld2decd92010-03-02 22:17:38 +00001703:meth:`parse_known_args` method can be useful. It works much like
Benjamin Peterson90c58022010-03-03 01:55:09 +00001704:meth:`~ArgumentParser.parse_args` except that it does not produce an error when
1705extra arguments are present. Instead, it returns a two item tuple containing
1706the populated namespace and the list of remaining argument strings.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001707
1708::
1709
1710 >>> parser = argparse.ArgumentParser()
1711 >>> parser.add_argument('--foo', action='store_true')
1712 >>> parser.add_argument('bar')
1713 >>> parser.parse_known_args(['--foo', '--badger', 'BAR', 'spam'])
1714 (Namespace(bar='BAR', foo=True), ['--badger', 'spam'])
1715
1716
1717Customizing file parsing
1718^^^^^^^^^^^^^^^^^^^^^^^^
1719
Benjamin Peterson90c58022010-03-03 01:55:09 +00001720.. method:: ArgumentParser.convert_arg_line_to_args(arg_line)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001721
Georg Brandlb8d0e362010-11-26 07:53:50 +00001722 Arguments that are read from a file (see the *fromfile_prefix_chars*
Benjamin Petersona39e9662010-03-02 22:05:59 +00001723 keyword argument to the :class:`ArgumentParser` constructor) are read one
Benjamin Peterson90c58022010-03-03 01:55:09 +00001724 argument per line. :meth:`convert_arg_line_to_args` can be overriden for
1725 fancier reading.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001726
Georg Brandlb8d0e362010-11-26 07:53:50 +00001727 This method takes a single argument *arg_line* which is a string read from
Benjamin Petersona39e9662010-03-02 22:05:59 +00001728 the argument file. It returns a list of arguments parsed from this string.
1729 The method is called once per line read from the argument file, in order.
1730
Georg Brandld2decd92010-03-02 22:17:38 +00001731 A useful override of this method is one that treats each space-separated word
1732 as an argument::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001733
1734 def convert_arg_line_to_args(self, arg_line):
1735 for arg in arg_line.split():
1736 if not arg.strip():
1737 continue
1738 yield arg
1739
1740
Georg Brandlb8d0e362010-11-26 07:53:50 +00001741Exiting methods
1742^^^^^^^^^^^^^^^
1743
1744.. method:: ArgumentParser.exit(status=0, message=None)
1745
1746 This method terminates the program, exiting with the specified *status*
1747 and, if given, it prints a *message* before that.
1748
1749.. method:: ArgumentParser.error(message)
1750
1751 This method prints a usage message including the *message* to the
1752 standard output and terminates the program with a status code of 2.
1753
1754
Georg Brandl58df6792010-07-03 10:25:47 +00001755.. _argparse-from-optparse:
1756
Benjamin Petersona39e9662010-03-02 22:05:59 +00001757Upgrading optparse code
1758-----------------------
1759
Ezio Melotti01b600c2011-04-21 16:12:17 +03001760Originally, the mod:`argparse` module had attempted to maintain compatibility
1761with :mod:`optparse`. However, :mod:`optparse` was difficult to extend
1762transparently, particularly with the changes required to support the new
1763``nargs=`` specifiers and better usage messages. When most everything in
1764:mod:`optparse` had either been copy-pasted over or monkey-patched, it no
1765longer seemed practical to try to maintain the backwards compatibility.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001766
Ezio Melotti01b600c2011-04-21 16:12:17 +03001767A partial upgrade path from :mod:`optparse` to :mod:`argparse`:
Benjamin Petersona39e9662010-03-02 22:05:59 +00001768
Georg Brandl585bbb92011-01-09 09:33:09 +00001769* Replace all ``add_option()`` calls with :meth:`ArgumentParser.add_argument`
1770 calls.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001771
Georg Brandld2decd92010-03-02 22:17:38 +00001772* Replace ``options, args = parser.parse_args()`` with ``args =
Georg Brandl585bbb92011-01-09 09:33:09 +00001773 parser.parse_args()`` and add additional :meth:`ArgumentParser.add_argument`
1774 calls for the positional arguments.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001775
1776* Replace callback actions and the ``callback_*`` keyword arguments with
1777 ``type`` or ``action`` arguments.
1778
1779* Replace string names for ``type`` keyword arguments with the corresponding
1780 type objects (e.g. int, float, complex, etc).
1781
Benjamin Peterson90c58022010-03-03 01:55:09 +00001782* Replace :class:`optparse.Values` with :class:`Namespace` and
1783 :exc:`optparse.OptionError` and :exc:`optparse.OptionValueError` with
1784 :exc:`ArgumentError`.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001785
Georg Brandld2decd92010-03-02 22:17:38 +00001786* Replace strings with implicit arguments such as ``%default`` or ``%prog`` with
Ezio Melotti2eab88e2011-04-21 15:26:46 +03001787 the standard Python syntax to use dictionaries to format strings, that is,
Georg Brandld2decd92010-03-02 22:17:38 +00001788 ``%(default)s`` and ``%(prog)s``.
Steven Bethard74bd9cf2010-05-24 02:38:00 +00001789
1790* Replace the OptionParser constructor ``version`` argument with a call to
1791 ``parser.add_argument('--version', action='version', version='<the version>')``