blob: d149d7aec1395bd35fd69bbf40f6d39cd49693c7 [file] [log] [blame]
Georg Brandlb8d0e362010-11-26 07:53:50 +00001:mod:`argparse` --- Parser for command line options, arguments and sub-commands
2===============================================================================
Benjamin Petersona39e9662010-03-02 22:05:59 +00003
4.. module:: argparse
5 :synopsis: Command-line option and argument parsing library.
6.. moduleauthor:: Steven Bethard <steven.bethard@gmail.com>
7.. versionadded:: 2.7
8.. sectionauthor:: Steven Bethard <steven.bethard@gmail.com>
9
10
11The :mod:`argparse` module makes it easy to write user friendly command line
Benjamin Peterson90c58022010-03-03 01:55:09 +000012interfaces. The program defines what arguments it requires, and :mod:`argparse`
Georg Brandld2decd92010-03-02 22:17:38 +000013will figure out how to parse those out of :data:`sys.argv`. The :mod:`argparse`
Benjamin Peterson90c58022010-03-03 01:55:09 +000014module also automatically generates help and usage messages and issues errors
15when users give the program invalid arguments.
Benjamin Petersona39e9662010-03-02 22:05:59 +000016
Georg Brandlb8d0e362010-11-26 07:53:50 +000017
Benjamin Petersona39e9662010-03-02 22:05:59 +000018Example
19-------
20
Benjamin Peterson90c58022010-03-03 01:55:09 +000021The following code is a Python program that takes a list of integers and
22produces either the sum or the max::
Benjamin Petersona39e9662010-03-02 22:05:59 +000023
24 import argparse
25
26 parser = argparse.ArgumentParser(description='Process some integers.')
27 parser.add_argument('integers', metavar='N', type=int, nargs='+',
28 help='an integer for the accumulator')
29 parser.add_argument('--sum', dest='accumulate', action='store_const',
30 const=sum, default=max,
31 help='sum the integers (default: find the max)')
32
33 args = parser.parse_args()
34 print args.accumulate(args.integers)
35
36Assuming the Python code above is saved into a file called ``prog.py``, it can
37be run at the command line and provides useful help messages::
38
39 $ prog.py -h
40 usage: prog.py [-h] [--sum] N [N ...]
41
42 Process some integers.
43
44 positional arguments:
45 N an integer for the accumulator
46
47 optional arguments:
48 -h, --help show this help message and exit
49 --sum sum the integers (default: find the max)
50
51When run with the appropriate arguments, it prints either the sum or the max of
52the command-line integers::
53
54 $ prog.py 1 2 3 4
55 4
56
57 $ prog.py 1 2 3 4 --sum
58 10
59
60If invalid arguments are passed in, it will issue an error::
61
62 $ prog.py a b c
63 usage: prog.py [-h] [--sum] N [N ...]
64 prog.py: error: argument N: invalid int value: 'a'
65
66The following sections walk you through this example.
67
Georg Brandlb8d0e362010-11-26 07:53:50 +000068
Benjamin Petersona39e9662010-03-02 22:05:59 +000069Creating a parser
70^^^^^^^^^^^^^^^^^
71
Benjamin Petersonac80c152010-03-03 21:28:25 +000072The first step in using the :mod:`argparse` is creating an
Benjamin Peterson90c58022010-03-03 01:55:09 +000073:class:`ArgumentParser` object::
Benjamin Petersona39e9662010-03-02 22:05:59 +000074
75 >>> parser = argparse.ArgumentParser(description='Process some integers.')
76
77The :class:`ArgumentParser` object will hold all the information necessary to
Benjamin Peterson90c58022010-03-03 01:55:09 +000078parse the command line into python data types.
Benjamin Petersona39e9662010-03-02 22:05:59 +000079
80
81Adding arguments
82^^^^^^^^^^^^^^^^
83
Benjamin Peterson90c58022010-03-03 01:55:09 +000084Filling an :class:`ArgumentParser` with information about program arguments is
85done by making calls to the :meth:`~ArgumentParser.add_argument` method.
86Generally, these calls tell the :class:`ArgumentParser` how to take the strings
87on the command line and turn them into objects. This information is stored and
88used when :meth:`~ArgumentParser.parse_args` is called. For example::
Benjamin Petersona39e9662010-03-02 22:05:59 +000089
90 >>> parser.add_argument('integers', metavar='N', type=int, nargs='+',
91 ... help='an integer for the accumulator')
92 >>> parser.add_argument('--sum', dest='accumulate', action='store_const',
93 ... const=sum, default=max,
94 ... help='sum the integers (default: find the max)')
95
Benjamin Peterson90c58022010-03-03 01:55:09 +000096Later, calling :meth:`parse_args` will return an object with
Georg Brandld2decd92010-03-02 22:17:38 +000097two attributes, ``integers`` and ``accumulate``. The ``integers`` attribute
98will be a list of one or more ints, and the ``accumulate`` attribute will be
99either the :func:`sum` function, if ``--sum`` was specified at the command line,
100or the :func:`max` function if it was not.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000101
Georg Brandlb8d0e362010-11-26 07:53:50 +0000102
Benjamin Petersona39e9662010-03-02 22:05:59 +0000103Parsing arguments
104^^^^^^^^^^^^^^^^^
105
Benjamin Peterson90c58022010-03-03 01:55:09 +0000106:class:`ArgumentParser` parses args through the
107:meth:`~ArgumentParser.parse_args` method. This will inspect the command-line,
Georg Brandld2decd92010-03-02 22:17:38 +0000108convert each arg to the appropriate type and then invoke the appropriate action.
109In most cases, this means a simple namespace object will be built up from
110attributes parsed out of the command-line::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000111
112 >>> parser.parse_args(['--sum', '7', '-1', '42'])
113 Namespace(accumulate=<built-in function sum>, integers=[7, -1, 42])
114
Benjamin Peterson90c58022010-03-03 01:55:09 +0000115In a script, :meth:`~ArgumentParser.parse_args` will typically be called with no
116arguments, and the :class:`ArgumentParser` will automatically determine the
117command-line args from :data:`sys.argv`.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000118
119
120ArgumentParser objects
121----------------------
122
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
220If ``-h`` or ``--help`` is supplied is at the command-line, the ArgumentParser
221help 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
350
351formatter_class
352^^^^^^^^^^^^^^^
353
Benjamin Peterson90c58022010-03-03 01:55:09 +0000354:class:`ArgumentParser` objects allow the help formatting to be customized by
355specifying an alternate formatting class. Currently, there are three such
356classes: :class:`argparse.RawDescriptionHelpFormatter`,
Georg Brandld2decd92010-03-02 22:17:38 +0000357:class:`argparse.RawTextHelpFormatter` and
358:class:`argparse.ArgumentDefaultsHelpFormatter`. The first two allow more
359control over how textual descriptions are displayed, while the last
360automatically adds information about argument default values.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000361
Benjamin Peterson90c58022010-03-03 01:55:09 +0000362By default, :class:`ArgumentParser` objects line-wrap the description_ and
363epilog_ texts in command-line help messages::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000364
365 >>> parser = argparse.ArgumentParser(
366 ... prog='PROG',
367 ... description='''this description
368 ... was indented weird
369 ... but that is okay''',
370 ... epilog='''
371 ... likewise for this epilog whose whitespace will
372 ... be cleaned up and whose words will be wrapped
373 ... across a couple lines''')
374 >>> parser.print_help()
375 usage: PROG [-h]
376
377 this description was indented weird but that is okay
378
379 optional arguments:
380 -h, --help show this help message and exit
381
382 likewise for this epilog whose whitespace will be cleaned up and whose words
383 will be wrapped across a couple lines
384
Benjamin Peterson90c58022010-03-03 01:55:09 +0000385Passing :class:`argparse.RawDescriptionHelpFormatter` as ``formatter_class=``
Benjamin Petersonc516d192010-03-03 02:04:24 +0000386indicates that description_ and epilog_ are already correctly formatted and
Benjamin Peterson90c58022010-03-03 01:55:09 +0000387should not be line-wrapped::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000388
389 >>> parser = argparse.ArgumentParser(
390 ... prog='PROG',
391 ... formatter_class=argparse.RawDescriptionHelpFormatter,
392 ... description=textwrap.dedent('''\
393 ... Please do not mess up this text!
394 ... --------------------------------
395 ... I have indented it
396 ... exactly the way
397 ... I want it
398 ... '''))
399 >>> parser.print_help()
400 usage: PROG [-h]
401
402 Please do not mess up this text!
403 --------------------------------
404 I have indented it
405 exactly the way
406 I want it
407
408 optional arguments:
409 -h, --help show this help message and exit
410
Benjamin Peterson90c58022010-03-03 01:55:09 +0000411:class:`RawTextHelpFormatter` maintains whitespace for all sorts of help text
412including argument descriptions.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000413
Benjamin Peterson90c58022010-03-03 01:55:09 +0000414The other formatter class available, :class:`ArgumentDefaultsHelpFormatter`,
Georg Brandld2decd92010-03-02 22:17:38 +0000415will add information about the default value of each of the arguments::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000416
417 >>> parser = argparse.ArgumentParser(
418 ... prog='PROG',
419 ... formatter_class=argparse.ArgumentDefaultsHelpFormatter)
420 >>> parser.add_argument('--foo', type=int, default=42, help='FOO!')
421 >>> parser.add_argument('bar', nargs='*', default=[1, 2, 3], help='BAR!')
422 >>> parser.print_help()
423 usage: PROG [-h] [--foo FOO] [bar [bar ...]]
424
425 positional arguments:
426 bar BAR! (default: [1, 2, 3])
427
428 optional arguments:
429 -h, --help show this help message and exit
430 --foo FOO FOO! (default: 42)
431
432
433conflict_handler
434^^^^^^^^^^^^^^^^
435
Benjamin Peterson90c58022010-03-03 01:55:09 +0000436:class:`ArgumentParser` objects do not allow two actions with the same option
437string. By default, :class:`ArgumentParser` objects raises an exception if an
438attempt is made to create an argument with an option string that is already in
439use::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000440
441 >>> parser = argparse.ArgumentParser(prog='PROG')
442 >>> parser.add_argument('-f', '--foo', help='old foo help')
443 >>> parser.add_argument('--foo', help='new foo help')
444 Traceback (most recent call last):
445 ..
446 ArgumentError: argument --foo: conflicting option string(s): --foo
447
448Sometimes (e.g. when using parents_) it may be useful to simply override any
Georg Brandld2decd92010-03-02 22:17:38 +0000449older arguments with the same option string. To get this behavior, the value
Benjamin Petersona39e9662010-03-02 22:05:59 +0000450``'resolve'`` can be supplied to the ``conflict_handler=`` argument of
Benjamin Peterson90c58022010-03-03 01:55:09 +0000451:class:`ArgumentParser`::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000452
453 >>> parser = argparse.ArgumentParser(prog='PROG', conflict_handler='resolve')
454 >>> parser.add_argument('-f', '--foo', help='old foo help')
455 >>> parser.add_argument('--foo', help='new foo help')
456 >>> parser.print_help()
457 usage: PROG [-h] [-f FOO] [--foo FOO]
458
459 optional arguments:
460 -h, --help show this help message and exit
461 -f FOO old foo help
462 --foo FOO new foo help
463
Benjamin Peterson90c58022010-03-03 01:55:09 +0000464Note that :class:`ArgumentParser` objects only remove an action if all of its
465option strings are overridden. So, in the example above, the old ``-f/--foo``
466action is retained as the ``-f`` action, because only the ``--foo`` option
467string was overridden.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000468
469
470prog
471^^^^
472
Benjamin Peterson90c58022010-03-03 01:55:09 +0000473By default, :class:`ArgumentParser` objects uses ``sys.argv[0]`` to determine
474how to display the name of the program in help messages. This default is almost
Ezio Melotti019551f2010-05-19 00:32:52 +0000475always desirable because it will make the help messages match how the program was
Benjamin Peterson90c58022010-03-03 01:55:09 +0000476invoked on the command line. For example, consider a file named
477``myprogram.py`` with the following code::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000478
479 import argparse
480 parser = argparse.ArgumentParser()
481 parser.add_argument('--foo', help='foo help')
482 args = parser.parse_args()
483
484The help for this program will display ``myprogram.py`` as the program name
485(regardless of where the program was invoked from)::
486
487 $ python myprogram.py --help
488 usage: myprogram.py [-h] [--foo FOO]
489
490 optional arguments:
491 -h, --help show this help message and exit
492 --foo FOO foo help
493 $ cd ..
494 $ python subdir\myprogram.py --help
495 usage: myprogram.py [-h] [--foo FOO]
496
497 optional arguments:
498 -h, --help show this help message and exit
499 --foo FOO foo help
500
501To change this default behavior, another value can be supplied using the
Benjamin Peterson90c58022010-03-03 01:55:09 +0000502``prog=`` argument to :class:`ArgumentParser`::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000503
504 >>> parser = argparse.ArgumentParser(prog='myprogram')
505 >>> parser.print_help()
506 usage: myprogram [-h]
507
508 optional arguments:
509 -h, --help show this help message and exit
510
511Note that the program name, whether determined from ``sys.argv[0]`` or from the
512``prog=`` argument, is available to help messages using the ``%(prog)s`` format
513specifier.
514
515::
516
517 >>> parser = argparse.ArgumentParser(prog='myprogram')
518 >>> parser.add_argument('--foo', help='foo of the %(prog)s program')
519 >>> parser.print_help()
520 usage: myprogram [-h] [--foo FOO]
521
522 optional arguments:
523 -h, --help show this help message and exit
524 --foo FOO foo of the myprogram program
525
526
527usage
528^^^^^
529
Benjamin Peterson90c58022010-03-03 01:55:09 +0000530By default, :class:`ArgumentParser` calculates the usage message from the
Benjamin Petersona39e9662010-03-02 22:05:59 +0000531arguments it contains::
532
533 >>> parser = argparse.ArgumentParser(prog='PROG')
534 >>> parser.add_argument('--foo', nargs='?', help='foo help')
535 >>> parser.add_argument('bar', nargs='+', help='bar help')
536 >>> parser.print_help()
537 usage: PROG [-h] [--foo [FOO]] bar [bar ...]
538
539 positional arguments:
540 bar bar help
541
542 optional arguments:
543 -h, --help show this help message and exit
544 --foo [FOO] foo help
545
Benjamin Peterson90c58022010-03-03 01:55:09 +0000546The default message can be overridden with the ``usage=`` keyword argument::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000547
548 >>> parser = argparse.ArgumentParser(prog='PROG', usage='%(prog)s [options]')
549 >>> parser.add_argument('--foo', nargs='?', help='foo help')
550 >>> parser.add_argument('bar', nargs='+', help='bar help')
551 >>> parser.print_help()
552 usage: PROG [options]
553
554 positional arguments:
555 bar bar help
556
557 optional arguments:
558 -h, --help show this help message and exit
559 --foo [FOO] foo help
560
Benjamin Peterson90c58022010-03-03 01:55:09 +0000561The ``%(prog)s`` format specifier is available to fill in the program name in
562your usage messages.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000563
564
565The add_argument() method
566-------------------------
567
Georg Brandl585bbb92011-01-09 09:33:09 +0000568.. method:: ArgumentParser.add_argument(name or flags..., [action], [nargs], \
569 [const], [default], [type], [choices], [required], \
570 [help], [metavar], [dest])
Benjamin Petersona39e9662010-03-02 22:05:59 +0000571
Georg Brandld2decd92010-03-02 22:17:38 +0000572 Define how a single command line argument should be parsed. Each parameter
Benjamin Petersona39e9662010-03-02 22:05:59 +0000573 has its own more detailed description below, but in short they are:
574
575 * `name or flags`_ - Either a name or a list of option strings, e.g. ``foo``
576 or ``-f, --foo``
577
578 * action_ - The basic type of action to be taken when this argument is
579 encountered at the command-line.
580
581 * nargs_ - The number of command-line arguments that should be consumed.
582
583 * const_ - A constant value required by some action_ and nargs_ selections.
584
585 * default_ - The value produced if the argument is absent from the
586 command-line.
587
588 * type_ - The type to which the command-line arg should be converted.
589
590 * choices_ - A container of the allowable values for the argument.
591
592 * required_ - Whether or not the command-line option may be omitted
593 (optionals only).
594
595 * help_ - A brief description of what the argument does.
596
597 * metavar_ - A name for the argument in usage messages.
598
599 * dest_ - The name of the attribute to be added to the object returned by
600 :meth:`parse_args`.
601
Benjamin Peterson90c58022010-03-03 01:55:09 +0000602The following sections describe how each of these are used.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000603
Georg Brandlb8d0e362010-11-26 07:53:50 +0000604
Benjamin Petersona39e9662010-03-02 22:05:59 +0000605name or flags
606^^^^^^^^^^^^^
607
Benjamin Peterson90c58022010-03-03 01:55:09 +0000608The :meth:`add_argument` method must know whether an optional argument, like
609``-f`` or ``--foo``, or a positional argument, like a list of filenames, is
610expected. The first arguments passed to :meth:`add_argument` must therefore be
611either a series of flags, or a simple argument name. For example, an optional
612argument could be created like::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000613
614 >>> parser.add_argument('-f', '--foo')
615
616while a positional argument could be created like::
617
618 >>> parser.add_argument('bar')
619
620When :meth:`parse_args` is called, optional arguments will be identified by the
621``-`` prefix, and the remaining arguments will be assumed to be positional::
622
623 >>> parser = argparse.ArgumentParser(prog='PROG')
624 >>> parser.add_argument('-f', '--foo')
625 >>> parser.add_argument('bar')
626 >>> parser.parse_args(['BAR'])
627 Namespace(bar='BAR', foo=None)
628 >>> parser.parse_args(['BAR', '--foo', 'FOO'])
629 Namespace(bar='BAR', foo='FOO')
630 >>> parser.parse_args(['--foo', 'FOO'])
631 usage: PROG [-h] [-f FOO] bar
632 PROG: error: too few arguments
633
Georg Brandlb8d0e362010-11-26 07:53:50 +0000634
Benjamin Petersona39e9662010-03-02 22:05:59 +0000635action
636^^^^^^
637
Georg Brandld2decd92010-03-02 22:17:38 +0000638:class:`ArgumentParser` objects associate command-line args with actions. These
Benjamin Petersona39e9662010-03-02 22:05:59 +0000639actions can do just about anything with the command-line args associated with
640them, though most actions simply add an attribute to the object returned by
Benjamin Peterson90c58022010-03-03 01:55:09 +0000641:meth:`parse_args`. The ``action`` keyword argument specifies how the
642command-line args should be handled. The supported actions are:
Benjamin Petersona39e9662010-03-02 22:05:59 +0000643
Georg Brandld2decd92010-03-02 22:17:38 +0000644* ``'store'`` - This just stores the argument's value. This is the default
Benjamin Petersona39e9662010-03-02 22:05:59 +0000645 action. For example::
646
647 >>> parser = argparse.ArgumentParser()
648 >>> parser.add_argument('--foo')
649 >>> parser.parse_args('--foo 1'.split())
650 Namespace(foo='1')
651
652* ``'store_const'`` - This stores the value specified by the const_ keyword
Benjamin Peterson90c58022010-03-03 01:55:09 +0000653 argument. (Note that the const_ keyword argument defaults to the rather
654 unhelpful ``None``.) The ``'store_const'`` action is most commonly used with
655 optional arguments that specify some sort of flag. For example::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000656
657 >>> parser = argparse.ArgumentParser()
658 >>> parser.add_argument('--foo', action='store_const', const=42)
659 >>> parser.parse_args('--foo'.split())
660 Namespace(foo=42)
661
662* ``'store_true'`` and ``'store_false'`` - These store the values ``True`` and
Benjamin Peterson90c58022010-03-03 01:55:09 +0000663 ``False`` respectively. These are special cases of ``'store_const'``. For
664 example::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000665
666 >>> parser = argparse.ArgumentParser()
667 >>> parser.add_argument('--foo', action='store_true')
668 >>> parser.add_argument('--bar', action='store_false')
669 >>> parser.parse_args('--foo --bar'.split())
670 Namespace(bar=False, foo=True)
671
672* ``'append'`` - This stores a list, and appends each argument value to the
Benjamin Peterson90c58022010-03-03 01:55:09 +0000673 list. This is useful to allow an option to be specified multiple times.
674 Example usage::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000675
676 >>> parser = argparse.ArgumentParser()
677 >>> parser.add_argument('--foo', action='append')
678 >>> parser.parse_args('--foo 1 --foo 2'.split())
679 Namespace(foo=['1', '2'])
680
681* ``'append_const'`` - This stores a list, and appends the value specified by
Benjamin Peterson90c58022010-03-03 01:55:09 +0000682 the const_ keyword argument to the list. (Note that the const_ keyword
683 argument defaults to ``None``.) The ``'append_const'`` action is typically
684 useful when multiple arguments need to store constants to the same list. For
685 example::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000686
687 >>> parser = argparse.ArgumentParser()
688 >>> parser.add_argument('--str', dest='types', action='append_const', const=str)
689 >>> parser.add_argument('--int', dest='types', action='append_const', const=int)
690 >>> parser.parse_args('--str --int'.split())
691 Namespace(types=[<type 'str'>, <type 'int'>])
692
693* ``'version'`` - This expects a ``version=`` keyword argument in the
694 :meth:`add_argument` call, and prints version information and exits when
695 invoked.
696
697 >>> import argparse
698 >>> parser = argparse.ArgumentParser(prog='PROG')
Steven Bethard74bd9cf2010-05-24 02:38:00 +0000699 >>> parser.add_argument('--version', action='version', version='%(prog)s 2.0')
700 >>> parser.parse_args(['--version'])
Benjamin Petersona39e9662010-03-02 22:05:59 +0000701 PROG 2.0
702
703You can also specify an arbitrary action by passing an object that implements
Benjamin Peterson90c58022010-03-03 01:55:09 +0000704the Action API. The easiest way to do this is to extend
705:class:`argparse.Action`, supplying an appropriate ``__call__`` method. The
706``__call__`` method should accept four parameters:
Benjamin Petersona39e9662010-03-02 22:05:59 +0000707
708* ``parser`` - The ArgumentParser object which contains this action.
709
710* ``namespace`` - The namespace object that will be returned by
Georg Brandld2decd92010-03-02 22:17:38 +0000711 :meth:`parse_args`. Most actions add an attribute to this object.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000712
713* ``values`` - The associated command-line args, with any type-conversions
714 applied. (Type-conversions are specified with the type_ keyword argument to
715 :meth:`add_argument`.
716
717* ``option_string`` - The option string that was used to invoke this action.
718 The ``option_string`` argument is optional, and will be absent if the action
719 is associated with a positional argument.
720
Benjamin Peterson90c58022010-03-03 01:55:09 +0000721An example of a custom action::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000722
723 >>> class FooAction(argparse.Action):
724 ... def __call__(self, parser, namespace, values, option_string=None):
Georg Brandl8891e232010-08-01 21:23:50 +0000725 ... print '%r %r %r' % (namespace, values, option_string)
726 ... setattr(namespace, self.dest, values)
Benjamin Petersona39e9662010-03-02 22:05:59 +0000727 ...
728 >>> parser = argparse.ArgumentParser()
729 >>> parser.add_argument('--foo', action=FooAction)
730 >>> parser.add_argument('bar', action=FooAction)
731 >>> args = parser.parse_args('1 --foo 2'.split())
732 Namespace(bar=None, foo=None) '1' None
733 Namespace(bar='1', foo=None) '2' '--foo'
734 >>> args
735 Namespace(bar='1', foo='2')
736
737
738nargs
739^^^^^
740
741ArgumentParser objects usually associate a single command-line argument with a
Benjamin Peterson90c58022010-03-03 01:55:09 +0000742single action to be taken. The ``nargs`` keyword argument associates a
743different number of command-line arguments with a single action.. The supported
744values are:
Benjamin Petersona39e9662010-03-02 22:05:59 +0000745
Georg Brandld2decd92010-03-02 22:17:38 +0000746* N (an integer). N args from the command-line will be gathered together into a
747 list. For example::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000748
Georg Brandl35e7a8f2010-10-06 10:41:31 +0000749 >>> parser = argparse.ArgumentParser()
750 >>> parser.add_argument('--foo', nargs=2)
751 >>> parser.add_argument('bar', nargs=1)
752 >>> parser.parse_args('c --foo a b'.split())
753 Namespace(bar=['c'], foo=['a', 'b'])
Benjamin Petersona39e9662010-03-02 22:05:59 +0000754
Georg Brandl35e7a8f2010-10-06 10:41:31 +0000755 Note that ``nargs=1`` produces a list of one item. This is different from
756 the default, in which the item is produced by itself.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000757
758* ``'?'``. One arg will be consumed from the command-line if possible, and
759 produced as a single item. If no command-line arg is present, the value from
760 default_ will be produced. Note that for optional arguments, there is an
761 additional case - the option string is present but not followed by a
762 command-line arg. In this case the value from const_ will be produced. Some
763 examples to illustrate this::
764
Georg Brandld2decd92010-03-02 22:17:38 +0000765 >>> parser = argparse.ArgumentParser()
766 >>> parser.add_argument('--foo', nargs='?', const='c', default='d')
767 >>> parser.add_argument('bar', nargs='?', default='d')
768 >>> parser.parse_args('XX --foo YY'.split())
769 Namespace(bar='XX', foo='YY')
770 >>> parser.parse_args('XX --foo'.split())
771 Namespace(bar='XX', foo='c')
772 >>> parser.parse_args(''.split())
773 Namespace(bar='d', foo='d')
Benjamin Petersona39e9662010-03-02 22:05:59 +0000774
Georg Brandld2decd92010-03-02 22:17:38 +0000775 One of the more common uses of ``nargs='?'`` is to allow optional input and
776 output files::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000777
Georg Brandld2decd92010-03-02 22:17:38 +0000778 >>> parser = argparse.ArgumentParser()
Georg Brandlb8d0e362010-11-26 07:53:50 +0000779 >>> parser.add_argument('infile', nargs='?', type=argparse.FileType('r'),
780 ... default=sys.stdin)
781 >>> parser.add_argument('outfile', nargs='?', type=argparse.FileType('w'),
782 ... default=sys.stdout)
Georg Brandld2decd92010-03-02 22:17:38 +0000783 >>> parser.parse_args(['input.txt', 'output.txt'])
Georg Brandl585bbb92011-01-09 09:33:09 +0000784 Namespace(infile=<open file 'input.txt', mode 'r' at 0x...>,
785 outfile=<open file 'output.txt', mode 'w' at 0x...>)
Georg Brandld2decd92010-03-02 22:17:38 +0000786 >>> parser.parse_args([])
Georg Brandl585bbb92011-01-09 09:33:09 +0000787 Namespace(infile=<open file '<stdin>', mode 'r' at 0x...>,
788 outfile=<open file '<stdout>', mode 'w' at 0x...>)
Benjamin Petersona39e9662010-03-02 22:05:59 +0000789
Georg Brandld2decd92010-03-02 22:17:38 +0000790* ``'*'``. All command-line args present are gathered into a list. Note that
791 it generally doesn't make much sense to have more than one positional argument
792 with ``nargs='*'``, but multiple optional arguments with ``nargs='*'`` is
793 possible. For example::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000794
Georg Brandld2decd92010-03-02 22:17:38 +0000795 >>> parser = argparse.ArgumentParser()
796 >>> parser.add_argument('--foo', nargs='*')
797 >>> parser.add_argument('--bar', nargs='*')
798 >>> parser.add_argument('baz', nargs='*')
799 >>> parser.parse_args('a b --foo x y --bar 1 2'.split())
800 Namespace(bar=['1', '2'], baz=['a', 'b'], foo=['x', 'y'])
Benjamin Petersona39e9662010-03-02 22:05:59 +0000801
802* ``'+'``. Just like ``'*'``, all command-line args present are gathered into a
803 list. Additionally, an error message will be generated if there wasn't at
804 least one command-line arg present. For example::
805
Georg Brandld2decd92010-03-02 22:17:38 +0000806 >>> parser = argparse.ArgumentParser(prog='PROG')
807 >>> parser.add_argument('foo', nargs='+')
808 >>> parser.parse_args('a b'.split())
809 Namespace(foo=['a', 'b'])
810 >>> parser.parse_args(''.split())
811 usage: PROG [-h] foo [foo ...]
812 PROG: error: too few arguments
Benjamin Petersona39e9662010-03-02 22:05:59 +0000813
814If the ``nargs`` keyword argument is not provided, the number of args consumed
Georg Brandld2decd92010-03-02 22:17:38 +0000815is determined by the action_. Generally this means a single command-line arg
Benjamin Petersona39e9662010-03-02 22:05:59 +0000816will be consumed and a single item (not a list) will be produced.
817
818
819const
820^^^^^
821
822The ``const`` argument of :meth:`add_argument` is used to hold constant values
823that are not read from the command line but are required for the various
824ArgumentParser actions. The two most common uses of it are:
825
826* When :meth:`add_argument` is called with ``action='store_const'`` or
827 ``action='append_const'``. These actions add the ``const`` value to one of
828 the attributes of the object returned by :meth:`parse_args`. See the action_
829 description for examples.
830
831* When :meth:`add_argument` is called with option strings (like ``-f`` or
Georg Brandld2decd92010-03-02 22:17:38 +0000832 ``--foo``) and ``nargs='?'``. This creates an optional argument that can be
Benjamin Petersona39e9662010-03-02 22:05:59 +0000833 followed by zero or one command-line args. When parsing the command-line, if
834 the option string is encountered with no command-line arg following it, the
835 value of ``const`` will be assumed instead. See the nargs_ description for
836 examples.
837
838The ``const`` keyword argument defaults to ``None``.
839
840
841default
842^^^^^^^
843
844All optional arguments and some positional arguments may be omitted at the
845command-line. The ``default`` keyword argument of :meth:`add_argument`, whose
846value defaults to ``None``, specifies what value should be used if the
847command-line arg is not present. For optional arguments, the ``default`` value
848is used when the option string was not present at the command line::
849
850 >>> parser = argparse.ArgumentParser()
851 >>> parser.add_argument('--foo', default=42)
852 >>> parser.parse_args('--foo 2'.split())
853 Namespace(foo='2')
854 >>> parser.parse_args(''.split())
855 Namespace(foo=42)
856
857For positional arguments with nargs_ ``='?'`` or ``'*'``, the ``default`` value
858is used when no command-line arg was present::
859
860 >>> parser = argparse.ArgumentParser()
861 >>> parser.add_argument('foo', nargs='?', default=42)
862 >>> parser.parse_args('a'.split())
863 Namespace(foo='a')
864 >>> parser.parse_args(''.split())
865 Namespace(foo=42)
866
867
Benjamin Peterson90c58022010-03-03 01:55:09 +0000868Providing ``default=argparse.SUPPRESS`` causes no attribute to be added if the
869command-line argument was not present.::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000870
871 >>> parser = argparse.ArgumentParser()
872 >>> parser.add_argument('--foo', default=argparse.SUPPRESS)
873 >>> parser.parse_args([])
874 Namespace()
875 >>> parser.parse_args(['--foo', '1'])
876 Namespace(foo='1')
877
878
879type
880^^^^
881
882By default, ArgumentParser objects read command-line args in as simple strings.
883However, quite often the command-line string should instead be interpreted as
Benjamin Peterson90c58022010-03-03 01:55:09 +0000884another type, like a :class:`float`, :class:`int` or :class:`file`. The
885``type`` keyword argument of :meth:`add_argument` allows any necessary
Georg Brandl21e99f42010-03-07 15:23:59 +0000886type-checking and type-conversions to be performed. Many common built-in types
Benjamin Peterson90c58022010-03-03 01:55:09 +0000887can be used directly as the value of the ``type`` argument::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000888
889 >>> parser = argparse.ArgumentParser()
890 >>> parser.add_argument('foo', type=int)
891 >>> parser.add_argument('bar', type=file)
892 >>> parser.parse_args('2 temp.txt'.split())
893 Namespace(bar=<open file 'temp.txt', mode 'r' at 0x...>, foo=2)
894
895To ease the use of various types of files, the argparse module provides the
896factory FileType which takes the ``mode=`` and ``bufsize=`` arguments of the
Georg Brandld2decd92010-03-02 22:17:38 +0000897``file`` object. For example, ``FileType('w')`` can be used to create a
Benjamin Petersona39e9662010-03-02 22:05:59 +0000898writable file::
899
900 >>> parser = argparse.ArgumentParser()
901 >>> parser.add_argument('bar', type=argparse.FileType('w'))
902 >>> parser.parse_args(['out.txt'])
903 Namespace(bar=<open file 'out.txt', mode 'w' at 0x...>)
904
Benjamin Peterson90c58022010-03-03 01:55:09 +0000905``type=`` can take any callable that takes a single string argument and returns
906the type-converted value::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000907
908 >>> def perfect_square(string):
909 ... value = int(string)
910 ... sqrt = math.sqrt(value)
911 ... if sqrt != int(sqrt):
912 ... msg = "%r is not a perfect square" % string
913 ... raise argparse.ArgumentTypeError(msg)
914 ... return value
915 ...
916 >>> parser = argparse.ArgumentParser(prog='PROG')
917 >>> parser.add_argument('foo', type=perfect_square)
918 >>> parser.parse_args('9'.split())
919 Namespace(foo=9)
920 >>> parser.parse_args('7'.split())
921 usage: PROG [-h] foo
922 PROG: error: argument foo: '7' is not a perfect square
923
Benjamin Peterson90c58022010-03-03 01:55:09 +0000924The choices_ keyword argument may be more convenient for type checkers that
925simply check against a range of values::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000926
927 >>> parser = argparse.ArgumentParser(prog='PROG')
928 >>> parser.add_argument('foo', type=int, choices=xrange(5, 10))
929 >>> parser.parse_args('7'.split())
930 Namespace(foo=7)
931 >>> parser.parse_args('11'.split())
932 usage: PROG [-h] {5,6,7,8,9}
933 PROG: error: argument foo: invalid choice: 11 (choose from 5, 6, 7, 8, 9)
934
935See the choices_ section for more details.
936
937
938choices
939^^^^^^^
940
941Some command-line args should be selected from a restricted set of values.
Benjamin Peterson90c58022010-03-03 01:55:09 +0000942These can be handled by passing a container object as the ``choices`` keyword
943argument to :meth:`add_argument`. When the command-line is parsed, arg values
944will be checked, and an error message will be displayed if the arg was not one
945of the acceptable values::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000946
947 >>> parser = argparse.ArgumentParser(prog='PROG')
948 >>> parser.add_argument('foo', choices='abc')
949 >>> parser.parse_args('c'.split())
950 Namespace(foo='c')
951 >>> parser.parse_args('X'.split())
952 usage: PROG [-h] {a,b,c}
953 PROG: error: argument foo: invalid choice: 'X' (choose from 'a', 'b', 'c')
954
955Note that inclusion in the ``choices`` container is checked after any type_
956conversions have been performed, so the type of the objects in the ``choices``
957container should match the type_ specified::
958
959 >>> parser = argparse.ArgumentParser(prog='PROG')
960 >>> parser.add_argument('foo', type=complex, choices=[1, 1j])
961 >>> parser.parse_args('1j'.split())
962 Namespace(foo=1j)
963 >>> parser.parse_args('-- -4'.split())
964 usage: PROG [-h] {1,1j}
965 PROG: error: argument foo: invalid choice: (-4+0j) (choose from 1, 1j)
966
967Any object that supports the ``in`` operator can be passed as the ``choices``
Georg Brandld2decd92010-03-02 22:17:38 +0000968value, so :class:`dict` objects, :class:`set` objects, custom containers,
969etc. are all supported.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000970
971
972required
973^^^^^^^^
974
975In general, the argparse module assumes that flags like ``-f`` and ``--bar``
976indicate *optional* arguments, which can always be omitted at the command-line.
Benjamin Peterson90c58022010-03-03 01:55:09 +0000977To make an option *required*, ``True`` can be specified for the ``required=``
978keyword argument to :meth:`add_argument`::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000979
980 >>> parser = argparse.ArgumentParser()
981 >>> parser.add_argument('--foo', required=True)
982 >>> parser.parse_args(['--foo', 'BAR'])
983 Namespace(foo='BAR')
984 >>> parser.parse_args([])
985 usage: argparse.py [-h] [--foo FOO]
986 argparse.py: error: option --foo is required
987
988As the example shows, if an option is marked as ``required``, :meth:`parse_args`
989will report an error if that option is not present at the command line.
990
Benjamin Peterson90c58022010-03-03 01:55:09 +0000991.. note::
992
993 Required options are generally considered bad form because users expect
994 *options* to be *optional*, and thus they should be avoided when possible.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000995
996
997help
998^^^^
999
Benjamin Peterson90c58022010-03-03 01:55:09 +00001000The ``help`` value is a string containing a brief description of the argument.
1001When a user requests help (usually by using ``-h`` or ``--help`` at the
1002command-line), these ``help`` descriptions will be displayed with each
Georg Brandld2decd92010-03-02 22:17:38 +00001003argument::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001004
1005 >>> parser = argparse.ArgumentParser(prog='frobble')
1006 >>> parser.add_argument('--foo', action='store_true',
1007 ... help='foo the bars before frobbling')
1008 >>> parser.add_argument('bar', nargs='+',
1009 ... help='one of the bars to be frobbled')
1010 >>> parser.parse_args('-h'.split())
1011 usage: frobble [-h] [--foo] bar [bar ...]
1012
1013 positional arguments:
1014 bar one of the bars to be frobbled
1015
1016 optional arguments:
1017 -h, --help show this help message and exit
1018 --foo foo the bars before frobbling
1019
1020The ``help`` strings can include various format specifiers to avoid repetition
1021of things like the program name or the argument default_. The available
1022specifiers include the program name, ``%(prog)s`` and most keyword arguments to
1023:meth:`add_argument`, e.g. ``%(default)s``, ``%(type)s``, etc.::
1024
1025 >>> parser = argparse.ArgumentParser(prog='frobble')
1026 >>> parser.add_argument('bar', nargs='?', type=int, default=42,
1027 ... help='the bar to %(prog)s (default: %(default)s)')
1028 >>> parser.print_help()
1029 usage: frobble [-h] [bar]
1030
1031 positional arguments:
1032 bar the bar to frobble (default: 42)
1033
1034 optional arguments:
1035 -h, --help show this help message and exit
1036
1037
1038metavar
1039^^^^^^^
1040
Benjamin Peterson90c58022010-03-03 01:55:09 +00001041When :class:`ArgumentParser` generates help messages, it need some way to refer
Georg Brandld2decd92010-03-02 22:17:38 +00001042to each expected argument. By default, ArgumentParser objects use the dest_
Benjamin Petersona39e9662010-03-02 22:05:59 +00001043value as the "name" of each object. By default, for positional argument
1044actions, the dest_ value is used directly, and for optional argument actions,
Benjamin Peterson90c58022010-03-03 01:55:09 +00001045the dest_ value is uppercased. So, a single positional argument with
1046``dest='bar'`` will that argument will be referred to as ``bar``. A single
1047optional argument ``--foo`` that should be followed by a single command-line arg
1048will be referred to as ``FOO``. An example::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001049
1050 >>> parser = argparse.ArgumentParser()
1051 >>> parser.add_argument('--foo')
1052 >>> parser.add_argument('bar')
1053 >>> parser.parse_args('X --foo Y'.split())
1054 Namespace(bar='X', foo='Y')
1055 >>> parser.print_help()
1056 usage: [-h] [--foo FOO] bar
1057
1058 positional arguments:
1059 bar
1060
1061 optional arguments:
1062 -h, --help show this help message and exit
1063 --foo FOO
1064
Benjamin Peterson90c58022010-03-03 01:55:09 +00001065An alternative name can be specified with ``metavar``::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001066
1067 >>> parser = argparse.ArgumentParser()
1068 >>> parser.add_argument('--foo', metavar='YYY')
1069 >>> parser.add_argument('bar', metavar='XXX')
1070 >>> parser.parse_args('X --foo Y'.split())
1071 Namespace(bar='X', foo='Y')
1072 >>> parser.print_help()
1073 usage: [-h] [--foo YYY] XXX
1074
1075 positional arguments:
1076 XXX
1077
1078 optional arguments:
1079 -h, --help show this help message and exit
1080 --foo YYY
1081
1082Note that ``metavar`` only changes the *displayed* name - the name of the
1083attribute on the :meth:`parse_args` object is still determined by the dest_
1084value.
1085
1086Different values of ``nargs`` may cause the metavar to be used multiple times.
Benjamin Peterson90c58022010-03-03 01:55:09 +00001087Providing a tuple to ``metavar`` specifies a different display for each of the
1088arguments::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001089
1090 >>> parser = argparse.ArgumentParser(prog='PROG')
1091 >>> parser.add_argument('-x', nargs=2)
1092 >>> parser.add_argument('--foo', nargs=2, metavar=('bar', 'baz'))
1093 >>> parser.print_help()
1094 usage: PROG [-h] [-x X X] [--foo bar baz]
1095
1096 optional arguments:
1097 -h, --help show this help message and exit
1098 -x X X
1099 --foo bar baz
1100
1101
1102dest
1103^^^^
1104
Benjamin Peterson90c58022010-03-03 01:55:09 +00001105Most :class:`ArgumentParser` actions add some value as an attribute of the
1106object returned by :meth:`parse_args`. The name of this attribute is determined
1107by the ``dest`` keyword argument of :meth:`add_argument`. For positional
1108argument actions, ``dest`` is normally supplied as the first argument to
Benjamin Petersona39e9662010-03-02 22:05:59 +00001109:meth:`add_argument`::
1110
1111 >>> parser = argparse.ArgumentParser()
1112 >>> parser.add_argument('bar')
1113 >>> parser.parse_args('XXX'.split())
1114 Namespace(bar='XXX')
1115
1116For optional argument actions, the value of ``dest`` is normally inferred from
Benjamin Peterson90c58022010-03-03 01:55:09 +00001117the option strings. :class:`ArgumentParser` generates the value of ``dest`` by
Benjamin Petersona39e9662010-03-02 22:05:59 +00001118taking the first long option string and stripping away the initial ``'--'``
1119string. If no long option strings were supplied, ``dest`` will be derived from
1120the first short option string by stripping the initial ``'-'`` character. Any
Georg Brandld2decd92010-03-02 22:17:38 +00001121internal ``'-'`` characters will be converted to ``'_'`` characters to make sure
1122the string is a valid attribute name. The examples below illustrate this
Benjamin Petersona39e9662010-03-02 22:05:59 +00001123behavior::
1124
1125 >>> parser = argparse.ArgumentParser()
1126 >>> parser.add_argument('-f', '--foo-bar', '--foo')
1127 >>> parser.add_argument('-x', '-y')
1128 >>> parser.parse_args('-f 1 -x 2'.split())
1129 Namespace(foo_bar='1', x='2')
1130 >>> parser.parse_args('--foo 1 -y 2'.split())
1131 Namespace(foo_bar='1', x='2')
1132
Benjamin Peterson90c58022010-03-03 01:55:09 +00001133``dest`` allows a custom attribute name to be provided::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001134
1135 >>> parser = argparse.ArgumentParser()
1136 >>> parser.add_argument('--foo', dest='bar')
1137 >>> parser.parse_args('--foo XXX'.split())
1138 Namespace(bar='XXX')
1139
1140
1141The parse_args() method
1142-----------------------
1143
Georg Brandlb8d0e362010-11-26 07:53:50 +00001144.. method:: ArgumentParser.parse_args(args=None, namespace=None)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001145
Benjamin Peterson90c58022010-03-03 01:55:09 +00001146 Convert argument strings to objects and assign them as attributes of the
Georg Brandld2decd92010-03-02 22:17:38 +00001147 namespace. Return the populated namespace.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001148
1149 Previous calls to :meth:`add_argument` determine exactly what objects are
1150 created and how they are assigned. See the documentation for
1151 :meth:`add_argument` for details.
1152
Georg Brandld2decd92010-03-02 22:17:38 +00001153 By default, the arg strings are taken from :data:`sys.argv`, and a new empty
Benjamin Peterson90c58022010-03-03 01:55:09 +00001154 :class:`Namespace` object is created for the attributes.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001155
Georg Brandlb8d0e362010-11-26 07:53:50 +00001156
Benjamin Petersona39e9662010-03-02 22:05:59 +00001157Option value syntax
1158^^^^^^^^^^^^^^^^^^^
1159
1160The :meth:`parse_args` method supports several ways of specifying the value of
Georg Brandld2decd92010-03-02 22:17:38 +00001161an option (if it takes one). In the simplest case, the option and its value are
Benjamin Petersona39e9662010-03-02 22:05:59 +00001162passed as two separate arguments::
1163
1164 >>> parser = argparse.ArgumentParser(prog='PROG')
1165 >>> parser.add_argument('-x')
1166 >>> parser.add_argument('--foo')
1167 >>> parser.parse_args('-x X'.split())
1168 Namespace(foo=None, x='X')
1169 >>> parser.parse_args('--foo FOO'.split())
1170 Namespace(foo='FOO', x=None)
1171
Benjamin Peterson90c58022010-03-03 01:55:09 +00001172For long options (options with names longer than a single character), the option
1173and value can also be passed as a single command line argument, using ``=`` to
Georg Brandld2decd92010-03-02 22:17:38 +00001174separate them::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001175
1176 >>> parser.parse_args('--foo=FOO'.split())
1177 Namespace(foo='FOO', x=None)
1178
Benjamin Peterson90c58022010-03-03 01:55:09 +00001179For short options (options only one character long), the option and its value
1180can be concatenated::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001181
1182 >>> parser.parse_args('-xX'.split())
1183 Namespace(foo=None, x='X')
1184
Benjamin Peterson90c58022010-03-03 01:55:09 +00001185Several short options can be joined together, using only a single ``-`` prefix,
1186as long as only the last option (or none of them) requires a value::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001187
1188 >>> parser = argparse.ArgumentParser(prog='PROG')
1189 >>> parser.add_argument('-x', action='store_true')
1190 >>> parser.add_argument('-y', action='store_true')
1191 >>> parser.add_argument('-z')
1192 >>> parser.parse_args('-xyzZ'.split())
1193 Namespace(x=True, y=True, z='Z')
1194
1195
1196Invalid arguments
1197^^^^^^^^^^^^^^^^^
1198
1199While parsing the command-line, ``parse_args`` checks for a variety of errors,
1200including ambiguous options, invalid types, invalid options, wrong number of
Georg Brandld2decd92010-03-02 22:17:38 +00001201positional arguments, etc. When it encounters such an error, it exits and
Benjamin Petersona39e9662010-03-02 22:05:59 +00001202prints the error along with a usage message::
1203
1204 >>> parser = argparse.ArgumentParser(prog='PROG')
1205 >>> parser.add_argument('--foo', type=int)
1206 >>> parser.add_argument('bar', nargs='?')
1207
1208 >>> # invalid type
1209 >>> parser.parse_args(['--foo', 'spam'])
1210 usage: PROG [-h] [--foo FOO] [bar]
1211 PROG: error: argument --foo: invalid int value: 'spam'
1212
1213 >>> # invalid option
1214 >>> parser.parse_args(['--bar'])
1215 usage: PROG [-h] [--foo FOO] [bar]
1216 PROG: error: no such option: --bar
1217
1218 >>> # wrong number of arguments
1219 >>> parser.parse_args(['spam', 'badger'])
1220 usage: PROG [-h] [--foo FOO] [bar]
1221 PROG: error: extra arguments found: badger
1222
1223
1224Arguments containing ``"-"``
1225^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1226
1227The ``parse_args`` method attempts to give errors whenever the user has clearly
Georg Brandld2decd92010-03-02 22:17:38 +00001228made a mistake, but some situations are inherently ambiguous. For example, the
Benjamin Petersona39e9662010-03-02 22:05:59 +00001229command-line arg ``'-1'`` could either be an attempt to specify an option or an
Georg Brandld2decd92010-03-02 22:17:38 +00001230attempt to provide a positional argument. The ``parse_args`` method is cautious
Benjamin Petersona39e9662010-03-02 22:05:59 +00001231here: positional arguments may only begin with ``'-'`` if they look like
1232negative numbers and there are no options in the parser that look like negative
1233numbers::
1234
1235 >>> parser = argparse.ArgumentParser(prog='PROG')
1236 >>> parser.add_argument('-x')
1237 >>> parser.add_argument('foo', nargs='?')
1238
1239 >>> # no negative number options, so -1 is a positional argument
1240 >>> parser.parse_args(['-x', '-1'])
1241 Namespace(foo=None, x='-1')
1242
1243 >>> # no negative number options, so -1 and -5 are positional arguments
1244 >>> parser.parse_args(['-x', '-1', '-5'])
1245 Namespace(foo='-5', x='-1')
1246
1247 >>> parser = argparse.ArgumentParser(prog='PROG')
1248 >>> parser.add_argument('-1', dest='one')
1249 >>> parser.add_argument('foo', nargs='?')
1250
1251 >>> # negative number options present, so -1 is an option
1252 >>> parser.parse_args(['-1', 'X'])
1253 Namespace(foo=None, one='X')
1254
1255 >>> # negative number options present, so -2 is an option
1256 >>> parser.parse_args(['-2'])
1257 usage: PROG [-h] [-1 ONE] [foo]
1258 PROG: error: no such option: -2
1259
1260 >>> # negative number options present, so both -1s are options
1261 >>> parser.parse_args(['-1', '-1'])
1262 usage: PROG [-h] [-1 ONE] [foo]
1263 PROG: error: argument -1: expected one argument
1264
1265If you have positional arguments that must begin with ``'-'`` and don't look
1266like negative numbers, you can insert the pseudo-argument ``'--'`` which tells
1267``parse_args`` that everything after that is a positional argument::
1268
1269 >>> parser.parse_args(['--', '-f'])
1270 Namespace(foo='-f', one=None)
1271
1272
1273Argument abbreviations
1274^^^^^^^^^^^^^^^^^^^^^^
1275
Benjamin Peterson90c58022010-03-03 01:55:09 +00001276The :meth:`parse_args` method allows long options to be abbreviated if the
Benjamin Petersona39e9662010-03-02 22:05:59 +00001277abbreviation is unambiguous::
1278
1279 >>> parser = argparse.ArgumentParser(prog='PROG')
1280 >>> parser.add_argument('-bacon')
1281 >>> parser.add_argument('-badger')
1282 >>> parser.parse_args('-bac MMM'.split())
1283 Namespace(bacon='MMM', badger=None)
1284 >>> parser.parse_args('-bad WOOD'.split())
1285 Namespace(bacon=None, badger='WOOD')
1286 >>> parser.parse_args('-ba BA'.split())
1287 usage: PROG [-h] [-bacon BACON] [-badger BADGER]
1288 PROG: error: ambiguous option: -ba could match -badger, -bacon
1289
Benjamin Peterson90c58022010-03-03 01:55:09 +00001290An error is produced for arguments that could produce more than one options.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001291
1292
1293Beyond ``sys.argv``
1294^^^^^^^^^^^^^^^^^^^
1295
Georg Brandld2decd92010-03-02 22:17:38 +00001296Sometimes it may be useful to have an ArgumentParser parse args other than those
1297of :data:`sys.argv`. This can be accomplished by passing a list of strings to
Benjamin Peterson90c58022010-03-03 01:55:09 +00001298``parse_args``. This is useful for testing at the interactive prompt::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001299
1300 >>> parser = argparse.ArgumentParser()
1301 >>> parser.add_argument(
1302 ... 'integers', metavar='int', type=int, choices=xrange(10),
1303 ... nargs='+', help='an integer in the range 0..9')
1304 >>> parser.add_argument(
1305 ... '--sum', dest='accumulate', action='store_const', const=sum,
1306 ... default=max, help='sum the integers (default: find the max)')
1307 >>> parser.parse_args(['1', '2', '3', '4'])
1308 Namespace(accumulate=<built-in function max>, integers=[1, 2, 3, 4])
1309 >>> parser.parse_args('1 2 3 4 --sum'.split())
1310 Namespace(accumulate=<built-in function sum>, integers=[1, 2, 3, 4])
1311
1312
1313Custom namespaces
1314^^^^^^^^^^^^^^^^^
1315
Benjamin Peterson90c58022010-03-03 01:55:09 +00001316It may also be useful to have an :class:`ArgumentParser` assign attributes to an
1317already existing object, rather than the newly-created :class:`Namespace` object
1318that is normally used. This can be achieved by specifying the ``namespace=``
1319keyword argument::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001320
1321 >>> class C(object):
1322 ... pass
1323 ...
1324 >>> c = C()
1325 >>> parser = argparse.ArgumentParser()
1326 >>> parser.add_argument('--foo')
1327 >>> parser.parse_args(args=['--foo', 'BAR'], namespace=c)
1328 >>> c.foo
1329 'BAR'
1330
1331
1332Other utilities
1333---------------
1334
1335Sub-commands
1336^^^^^^^^^^^^
1337
Benjamin Peterson90c58022010-03-03 01:55:09 +00001338.. method:: ArgumentParser.add_subparsers()
Benjamin Petersona39e9662010-03-02 22:05:59 +00001339
Benjamin Peterson90c58022010-03-03 01:55:09 +00001340 Many programs split up their functionality into a number of sub-commands,
Georg Brandld2decd92010-03-02 22:17:38 +00001341 for example, the ``svn`` program can invoke sub-commands like ``svn
Benjamin Peterson90c58022010-03-03 01:55:09 +00001342 checkout``, ``svn update``, and ``svn commit``. Splitting up functionality
Georg Brandld2decd92010-03-02 22:17:38 +00001343 this way can be a particularly good idea when a program performs several
1344 different functions which require different kinds of command-line arguments.
Benjamin Peterson90c58022010-03-03 01:55:09 +00001345 :class:`ArgumentParser` supports the creation of such sub-commands with the
Georg Brandld2decd92010-03-02 22:17:38 +00001346 :meth:`add_subparsers` method. The :meth:`add_subparsers` method is normally
1347 called with no arguments and returns an special action object. This object
1348 has a single method, ``add_parser``, which takes a command name and any
Benjamin Peterson90c58022010-03-03 01:55:09 +00001349 :class:`ArgumentParser` constructor arguments, and returns an
1350 :class:`ArgumentParser` object that can be modified as usual.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001351
1352 Some example usage::
1353
1354 >>> # create the top-level parser
1355 >>> parser = argparse.ArgumentParser(prog='PROG')
1356 >>> parser.add_argument('--foo', action='store_true', help='foo help')
1357 >>> subparsers = parser.add_subparsers(help='sub-command help')
1358 >>>
1359 >>> # create the parser for the "a" command
1360 >>> parser_a = subparsers.add_parser('a', help='a help')
1361 >>> parser_a.add_argument('bar', type=int, help='bar help')
1362 >>>
1363 >>> # create the parser for the "b" command
1364 >>> parser_b = subparsers.add_parser('b', help='b help')
1365 >>> parser_b.add_argument('--baz', choices='XYZ', help='baz help')
1366 >>>
1367 >>> # parse some arg lists
1368 >>> parser.parse_args(['a', '12'])
1369 Namespace(bar=12, foo=False)
1370 >>> parser.parse_args(['--foo', 'b', '--baz', 'Z'])
1371 Namespace(baz='Z', foo=True)
1372
1373 Note that the object returned by :meth:`parse_args` will only contain
1374 attributes for the main parser and the subparser that was selected by the
1375 command line (and not any other subparsers). So in the example above, when
Georg Brandld2decd92010-03-02 22:17:38 +00001376 the ``"a"`` command is specified, only the ``foo`` and ``bar`` attributes are
1377 present, and when the ``"b"`` command is specified, only the ``foo`` and
Benjamin Petersona39e9662010-03-02 22:05:59 +00001378 ``baz`` attributes are present.
1379
1380 Similarly, when a help message is requested from a subparser, only the help
Georg Brandld2decd92010-03-02 22:17:38 +00001381 for that particular parser will be printed. The help message will not
Benjamin Peterson90c58022010-03-03 01:55:09 +00001382 include parent parser or sibling parser messages. (A help message for each
1383 subparser command, however, can be given by supplying the ``help=`` argument
1384 to ``add_parser`` as above.)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001385
1386 ::
1387
1388 >>> parser.parse_args(['--help'])
1389 usage: PROG [-h] [--foo] {a,b} ...
1390
1391 positional arguments:
1392 {a,b} sub-command help
1393 a a help
1394 b b help
1395
1396 optional arguments:
1397 -h, --help show this help message and exit
1398 --foo foo help
1399
1400 >>> parser.parse_args(['a', '--help'])
1401 usage: PROG a [-h] bar
1402
1403 positional arguments:
1404 bar bar help
1405
1406 optional arguments:
1407 -h, --help show this help message and exit
1408
1409 >>> parser.parse_args(['b', '--help'])
1410 usage: PROG b [-h] [--baz {X,Y,Z}]
1411
1412 optional arguments:
1413 -h, --help show this help message and exit
1414 --baz {X,Y,Z} baz help
1415
Georg Brandld2decd92010-03-02 22:17:38 +00001416 The :meth:`add_subparsers` method also supports ``title`` and ``description``
1417 keyword arguments. When either is present, the subparser's commands will
1418 appear in their own group in the help output. For example::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001419
1420 >>> parser = argparse.ArgumentParser()
1421 >>> subparsers = parser.add_subparsers(title='subcommands',
1422 ... description='valid subcommands',
1423 ... help='additional help')
1424 >>> subparsers.add_parser('foo')
1425 >>> subparsers.add_parser('bar')
1426 >>> parser.parse_args(['-h'])
1427 usage: [-h] {foo,bar} ...
1428
1429 optional arguments:
1430 -h, --help show this help message and exit
1431
1432 subcommands:
1433 valid subcommands
1434
1435 {foo,bar} additional help
1436
1437
Georg Brandld2decd92010-03-02 22:17:38 +00001438 One particularly effective way of handling sub-commands is to combine the use
1439 of the :meth:`add_subparsers` method with calls to :meth:`set_defaults` so
1440 that each subparser knows which Python function it should execute. For
Benjamin Petersona39e9662010-03-02 22:05:59 +00001441 example::
1442
1443 >>> # sub-command functions
1444 >>> def foo(args):
1445 ... print args.x * args.y
1446 ...
1447 >>> def bar(args):
1448 ... print '((%s))' % args.z
1449 ...
1450 >>> # create the top-level parser
1451 >>> parser = argparse.ArgumentParser()
1452 >>> subparsers = parser.add_subparsers()
1453 >>>
1454 >>> # create the parser for the "foo" command
1455 >>> parser_foo = subparsers.add_parser('foo')
1456 >>> parser_foo.add_argument('-x', type=int, default=1)
1457 >>> parser_foo.add_argument('y', type=float)
1458 >>> parser_foo.set_defaults(func=foo)
1459 >>>
1460 >>> # create the parser for the "bar" command
1461 >>> parser_bar = subparsers.add_parser('bar')
1462 >>> parser_bar.add_argument('z')
1463 >>> parser_bar.set_defaults(func=bar)
1464 >>>
1465 >>> # parse the args and call whatever function was selected
1466 >>> args = parser.parse_args('foo 1 -x 2'.split())
1467 >>> args.func(args)
1468 2.0
1469 >>>
1470 >>> # parse the args and call whatever function was selected
1471 >>> args = parser.parse_args('bar XYZYX'.split())
1472 >>> args.func(args)
1473 ((XYZYX))
1474
Benjamin Peterson90c58022010-03-03 01:55:09 +00001475 This way, you can let :meth:`parse_args` does the job of calling the
1476 appropriate function after argument parsing is complete. Associating
1477 functions with actions like this is typically the easiest way to handle the
1478 different actions for each of your subparsers. However, if it is necessary
1479 to check the name of the subparser that was invoked, the ``dest`` keyword
1480 argument to the :meth:`add_subparsers` call will work::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001481
1482 >>> parser = argparse.ArgumentParser()
1483 >>> subparsers = parser.add_subparsers(dest='subparser_name')
1484 >>> subparser1 = subparsers.add_parser('1')
1485 >>> subparser1.add_argument('-x')
1486 >>> subparser2 = subparsers.add_parser('2')
1487 >>> subparser2.add_argument('y')
1488 >>> parser.parse_args(['2', 'frobble'])
1489 Namespace(subparser_name='2', y='frobble')
1490
1491
1492FileType objects
1493^^^^^^^^^^^^^^^^
1494
1495.. class:: FileType(mode='r', bufsize=None)
1496
1497 The :class:`FileType` factory creates objects that can be passed to the type
Benjamin Peterson90c58022010-03-03 01:55:09 +00001498 argument of :meth:`ArgumentParser.add_argument`. Arguments that have
1499 :class:`FileType` objects as their type will open command-line args as files
1500 with the requested modes and buffer sizes:
Benjamin Petersona39e9662010-03-02 22:05:59 +00001501
1502 >>> parser = argparse.ArgumentParser()
1503 >>> parser.add_argument('--output', type=argparse.FileType('wb', 0))
1504 >>> parser.parse_args(['--output', 'out'])
1505 Namespace(output=<open file 'out', mode 'wb' at 0x...>)
1506
1507 FileType objects understand the pseudo-argument ``'-'`` and automatically
1508 convert this into ``sys.stdin`` for readable :class:`FileType` objects and
1509 ``sys.stdout`` for writable :class:`FileType` objects:
1510
1511 >>> parser = argparse.ArgumentParser()
1512 >>> parser.add_argument('infile', type=argparse.FileType('r'))
1513 >>> parser.parse_args(['-'])
1514 Namespace(infile=<open file '<stdin>', mode 'r' at 0x...>)
1515
1516
1517Argument groups
1518^^^^^^^^^^^^^^^
1519
Georg Brandlb8d0e362010-11-26 07:53:50 +00001520.. method:: ArgumentParser.add_argument_group(title=None, description=None)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001521
Benjamin Peterson90c58022010-03-03 01:55:09 +00001522 By default, :class:`ArgumentParser` groups command-line arguments into
Benjamin Petersona39e9662010-03-02 22:05:59 +00001523 "positional arguments" and "optional arguments" when displaying help
1524 messages. When there is a better conceptual grouping of arguments than this
1525 default one, appropriate groups can be created using the
1526 :meth:`add_argument_group` method::
1527
1528 >>> parser = argparse.ArgumentParser(prog='PROG', add_help=False)
1529 >>> group = parser.add_argument_group('group')
1530 >>> group.add_argument('--foo', help='foo help')
1531 >>> group.add_argument('bar', help='bar help')
1532 >>> parser.print_help()
1533 usage: PROG [--foo FOO] bar
1534
1535 group:
1536 bar bar help
1537 --foo FOO foo help
1538
1539 The :meth:`add_argument_group` method returns an argument group object which
Benjamin Peterson90c58022010-03-03 01:55:09 +00001540 has an :meth:`~ArgumentParser.add_argument` method just like a regular
1541 :class:`ArgumentParser`. When an argument is added to the group, the parser
1542 treats it just like a normal argument, but displays the argument in a
1543 separate group for help messages. The :meth:`add_argument_group` method
Georg Brandlb8d0e362010-11-26 07:53:50 +00001544 accepts *title* and *description* arguments which can be used to
Benjamin Peterson90c58022010-03-03 01:55:09 +00001545 customize this display::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001546
1547 >>> parser = argparse.ArgumentParser(prog='PROG', add_help=False)
1548 >>> group1 = parser.add_argument_group('group1', 'group1 description')
1549 >>> group1.add_argument('foo', help='foo help')
1550 >>> group2 = parser.add_argument_group('group2', 'group2 description')
1551 >>> group2.add_argument('--bar', help='bar help')
1552 >>> parser.print_help()
1553 usage: PROG [--bar BAR] foo
1554
1555 group1:
1556 group1 description
1557
1558 foo foo help
1559
1560 group2:
1561 group2 description
1562
1563 --bar BAR bar help
1564
Benjamin Peterson90c58022010-03-03 01:55:09 +00001565 Note that any arguments not your user defined groups will end up back in the
1566 usual "positional arguments" and "optional arguments" sections.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001567
1568
1569Mutual exclusion
1570^^^^^^^^^^^^^^^^
1571
Georg Brandlb8d0e362010-11-26 07:53:50 +00001572.. method:: add_mutually_exclusive_group(required=False)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001573
Benjamin Peterson90c58022010-03-03 01:55:09 +00001574 Create a mutually exclusive group. argparse will make sure that only one of
Benjamin Petersona39e9662010-03-02 22:05:59 +00001575 the arguments in the mutually exclusive group was present on the command
1576 line::
1577
1578 >>> parser = argparse.ArgumentParser(prog='PROG')
1579 >>> group = parser.add_mutually_exclusive_group()
1580 >>> group.add_argument('--foo', action='store_true')
1581 >>> group.add_argument('--bar', action='store_false')
1582 >>> parser.parse_args(['--foo'])
1583 Namespace(bar=True, foo=True)
1584 >>> parser.parse_args(['--bar'])
1585 Namespace(bar=False, foo=False)
1586 >>> parser.parse_args(['--foo', '--bar'])
1587 usage: PROG [-h] [--foo | --bar]
1588 PROG: error: argument --bar: not allowed with argument --foo
1589
Georg Brandlb8d0e362010-11-26 07:53:50 +00001590 The :meth:`add_mutually_exclusive_group` method also accepts a *required*
Benjamin Petersona39e9662010-03-02 22:05:59 +00001591 argument, to indicate that at least one of the mutually exclusive arguments
1592 is required::
1593
1594 >>> parser = argparse.ArgumentParser(prog='PROG')
1595 >>> group = parser.add_mutually_exclusive_group(required=True)
1596 >>> group.add_argument('--foo', action='store_true')
1597 >>> group.add_argument('--bar', action='store_false')
1598 >>> parser.parse_args([])
1599 usage: PROG [-h] (--foo | --bar)
1600 PROG: error: one of the arguments --foo --bar is required
1601
1602 Note that currently mutually exclusive argument groups do not support the
Georg Brandlb8d0e362010-11-26 07:53:50 +00001603 *title* and *description* arguments of :meth:`add_argument_group`.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001604
1605
1606Parser defaults
1607^^^^^^^^^^^^^^^
1608
Benjamin Peterson90c58022010-03-03 01:55:09 +00001609.. method:: ArgumentParser.set_defaults(**kwargs)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001610
Georg Brandld2decd92010-03-02 22:17:38 +00001611 Most of the time, the attributes of the object returned by :meth:`parse_args`
1612 will be fully determined by inspecting the command-line args and the argument
Benjamin Petersonc516d192010-03-03 02:04:24 +00001613 actions. :meth:`ArgumentParser.set_defaults` allows some additional
1614 attributes that are determined without any inspection of the command-line to
1615 be added::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001616
1617 >>> parser = argparse.ArgumentParser()
1618 >>> parser.add_argument('foo', type=int)
1619 >>> parser.set_defaults(bar=42, baz='badger')
1620 >>> parser.parse_args(['736'])
1621 Namespace(bar=42, baz='badger', foo=736)
1622
Benjamin Peterson90c58022010-03-03 01:55:09 +00001623 Note that parser-level defaults always override argument-level defaults::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001624
1625 >>> parser = argparse.ArgumentParser()
1626 >>> parser.add_argument('--foo', default='bar')
1627 >>> parser.set_defaults(foo='spam')
1628 >>> parser.parse_args([])
1629 Namespace(foo='spam')
1630
Benjamin Peterson90c58022010-03-03 01:55:09 +00001631 Parser-level defaults can be particularly useful when working with multiple
1632 parsers. See the :meth:`~ArgumentParser.add_subparsers` method for an
1633 example of this type.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001634
Benjamin Peterson90c58022010-03-03 01:55:09 +00001635.. method:: ArgumentParser.get_default(dest)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001636
1637 Get the default value for a namespace attribute, as set by either
Benjamin Peterson90c58022010-03-03 01:55:09 +00001638 :meth:`~ArgumentParser.add_argument` or by
1639 :meth:`~ArgumentParser.set_defaults`::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001640
1641 >>> parser = argparse.ArgumentParser()
1642 >>> parser.add_argument('--foo', default='badger')
1643 >>> parser.get_default('foo')
1644 'badger'
1645
1646
1647Printing help
1648^^^^^^^^^^^^^
1649
1650In most typical applications, :meth:`parse_args` will take care of formatting
Benjamin Peterson90c58022010-03-03 01:55:09 +00001651and printing any usage or error messages. However, several formatting methods
1652are available:
Benjamin Petersona39e9662010-03-02 22:05:59 +00001653
Georg Brandlb8d0e362010-11-26 07:53:50 +00001654.. method:: ArgumentParser.print_usage(file=None)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001655
1656 Print a brief description of how the :class:`ArgumentParser` should be
Georg Brandlb8d0e362010-11-26 07:53:50 +00001657 invoked on the command line. If *file* is ``None``, :data:`sys.stderr` is
Benjamin Petersona39e9662010-03-02 22:05:59 +00001658 assumed.
1659
Georg Brandlb8d0e362010-11-26 07:53:50 +00001660.. method:: ArgumentParser.print_help(file=None)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001661
1662 Print a help message, including the program usage and information about the
Georg Brandlb8d0e362010-11-26 07:53:50 +00001663 arguments registered with the :class:`ArgumentParser`. If *file* is
1664 ``None``, :data:`sys.stderr` is assumed.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001665
1666There are also variants of these methods that simply return a string instead of
1667printing it:
1668
Georg Brandlb8d0e362010-11-26 07:53:50 +00001669.. method:: ArgumentParser.format_usage()
Benjamin Petersona39e9662010-03-02 22:05:59 +00001670
1671 Return a string containing a brief description of how the
1672 :class:`ArgumentParser` should be invoked on the command line.
1673
Georg Brandlb8d0e362010-11-26 07:53:50 +00001674.. method:: ArgumentParser.format_help()
Benjamin Petersona39e9662010-03-02 22:05:59 +00001675
1676 Return a string containing a help message, including the program usage and
1677 information about the arguments registered with the :class:`ArgumentParser`.
1678
1679
Benjamin Petersona39e9662010-03-02 22:05:59 +00001680Partial parsing
1681^^^^^^^^^^^^^^^
1682
Georg Brandlb8d0e362010-11-26 07:53:50 +00001683.. method:: ArgumentParser.parse_known_args(args=None, namespace=None)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001684
1685Sometimes a script may only parse a few of the command line arguments, passing
1686the remaining arguments on to another script or program. In these cases, the
Georg Brandld2decd92010-03-02 22:17:38 +00001687:meth:`parse_known_args` method can be useful. It works much like
Benjamin Peterson90c58022010-03-03 01:55:09 +00001688:meth:`~ArgumentParser.parse_args` except that it does not produce an error when
1689extra arguments are present. Instead, it returns a two item tuple containing
1690the populated namespace and the list of remaining argument strings.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001691
1692::
1693
1694 >>> parser = argparse.ArgumentParser()
1695 >>> parser.add_argument('--foo', action='store_true')
1696 >>> parser.add_argument('bar')
1697 >>> parser.parse_known_args(['--foo', '--badger', 'BAR', 'spam'])
1698 (Namespace(bar='BAR', foo=True), ['--badger', 'spam'])
1699
1700
1701Customizing file parsing
1702^^^^^^^^^^^^^^^^^^^^^^^^
1703
Benjamin Peterson90c58022010-03-03 01:55:09 +00001704.. method:: ArgumentParser.convert_arg_line_to_args(arg_line)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001705
Georg Brandlb8d0e362010-11-26 07:53:50 +00001706 Arguments that are read from a file (see the *fromfile_prefix_chars*
Benjamin Petersona39e9662010-03-02 22:05:59 +00001707 keyword argument to the :class:`ArgumentParser` constructor) are read one
Benjamin Peterson90c58022010-03-03 01:55:09 +00001708 argument per line. :meth:`convert_arg_line_to_args` can be overriden for
1709 fancier reading.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001710
Georg Brandlb8d0e362010-11-26 07:53:50 +00001711 This method takes a single argument *arg_line* which is a string read from
Benjamin Petersona39e9662010-03-02 22:05:59 +00001712 the argument file. It returns a list of arguments parsed from this string.
1713 The method is called once per line read from the argument file, in order.
1714
Georg Brandld2decd92010-03-02 22:17:38 +00001715 A useful override of this method is one that treats each space-separated word
1716 as an argument::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001717
1718 def convert_arg_line_to_args(self, arg_line):
1719 for arg in arg_line.split():
1720 if not arg.strip():
1721 continue
1722 yield arg
1723
1724
Georg Brandlb8d0e362010-11-26 07:53:50 +00001725Exiting methods
1726^^^^^^^^^^^^^^^
1727
1728.. method:: ArgumentParser.exit(status=0, message=None)
1729
1730 This method terminates the program, exiting with the specified *status*
1731 and, if given, it prints a *message* before that.
1732
1733.. method:: ArgumentParser.error(message)
1734
1735 This method prints a usage message including the *message* to the
1736 standard output and terminates the program with a status code of 2.
1737
1738
Georg Brandl58df6792010-07-03 10:25:47 +00001739.. _argparse-from-optparse:
1740
Benjamin Petersona39e9662010-03-02 22:05:59 +00001741Upgrading optparse code
1742-----------------------
1743
1744Originally, the argparse module had attempted to maintain compatibility with
Georg Brandld2decd92010-03-02 22:17:38 +00001745optparse. However, optparse was difficult to extend transparently, particularly
1746with the changes required to support the new ``nargs=`` specifiers and better
Georg Brandl404bd7f2010-04-25 10:16:00 +00001747usage messages. When most everything in optparse had either been copy-pasted
Georg Brandld2decd92010-03-02 22:17:38 +00001748over or monkey-patched, it no longer seemed practical to try to maintain the
1749backwards compatibility.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001750
1751A partial upgrade path from optparse to argparse:
1752
Georg Brandl585bbb92011-01-09 09:33:09 +00001753* Replace all ``add_option()`` calls with :meth:`ArgumentParser.add_argument`
1754 calls.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001755
Georg Brandld2decd92010-03-02 22:17:38 +00001756* Replace ``options, args = parser.parse_args()`` with ``args =
Georg Brandl585bbb92011-01-09 09:33:09 +00001757 parser.parse_args()`` and add additional :meth:`ArgumentParser.add_argument`
1758 calls for the positional arguments.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001759
1760* Replace callback actions and the ``callback_*`` keyword arguments with
1761 ``type`` or ``action`` arguments.
1762
1763* Replace string names for ``type`` keyword arguments with the corresponding
1764 type objects (e.g. int, float, complex, etc).
1765
Benjamin Peterson90c58022010-03-03 01:55:09 +00001766* Replace :class:`optparse.Values` with :class:`Namespace` and
1767 :exc:`optparse.OptionError` and :exc:`optparse.OptionValueError` with
1768 :exc:`ArgumentError`.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001769
Georg Brandld2decd92010-03-02 22:17:38 +00001770* Replace strings with implicit arguments such as ``%default`` or ``%prog`` with
1771 the standard python syntax to use dictionaries to format strings, that is,
1772 ``%(default)s`` and ``%(prog)s``.
Steven Bethard74bd9cf2010-05-24 02:38:00 +00001773
1774* Replace the OptionParser constructor ``version`` argument with a call to
1775 ``parser.add_argument('--version', action='version', version='<the version>')``