blob: 6399ce7a6118aabf8c84845d6fbf29c6a4aa5a32 [file] [log] [blame]
Georg Brandle0bf91d2010-10-17 10:34:28 +00001:mod:`argparse` --- Parser for command line options, arguments and sub-commands
2===============================================================================
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003
4.. module:: argparse
5 :synopsis: Command-line option and argument parsing library.
6.. moduleauthor:: Steven Bethard <steven.bethard@gmail.com>
Ezio Melottif8754a62010-03-21 07:16:43 +00007.. versionadded:: 3.2
Benjamin Peterson698a18a2010-03-02 22:34:37 +00008.. sectionauthor:: Steven Bethard <steven.bethard@gmail.com>
9
10
11The :mod:`argparse` module makes it easy to write user friendly command line
Benjamin Peterson98047eb2010-03-03 02:07:08 +000012interfaces. The program defines what arguments it requires, and :mod:`argparse`
Benjamin Peterson698a18a2010-03-02 22:34:37 +000013will figure out how to parse those out of :data:`sys.argv`. The :mod:`argparse`
Benjamin Peterson98047eb2010-03-03 02:07:08 +000014module also automatically generates help and usage messages and issues errors
15when users give the program invalid arguments.
Benjamin Peterson698a18a2010-03-02 22:34:37 +000016
Georg Brandle0bf91d2010-10-17 10:34:28 +000017
Benjamin Peterson698a18a2010-03-02 22:34:37 +000018Example
19-------
20
Benjamin Peterson98047eb2010-03-03 02:07:08 +000021The following code is a Python program that takes a list of integers and
22produces either the sum or the max::
Benjamin Peterson698a18a2010-03-02 22:34:37 +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()
Benjamin Petersonb2deb112010-03-03 02:09:18 +000034 print(args.accumulate(args.integers))
Benjamin Peterson698a18a2010-03-02 22:34:37 +000035
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 Brandle0bf91d2010-10-17 10:34:28 +000068
Benjamin Peterson698a18a2010-03-02 22:34:37 +000069Creating a parser
70^^^^^^^^^^^^^^^^^
71
Benjamin Peterson2614cda2010-03-21 22:36:19 +000072The first step in using the :mod:`argparse` is creating an
Benjamin Peterson98047eb2010-03-03 02:07:08 +000073:class:`ArgumentParser` object::
Benjamin Peterson698a18a2010-03-02 22:34:37 +000074
75 >>> parser = argparse.ArgumentParser(description='Process some integers.')
76
77The :class:`ArgumentParser` object will hold all the information necessary to
Benjamin Peterson98047eb2010-03-03 02:07:08 +000078parse the command line into python data types.
Benjamin Peterson698a18a2010-03-02 22:34:37 +000079
80
81Adding arguments
82^^^^^^^^^^^^^^^^
83
Benjamin Peterson98047eb2010-03-03 02:07:08 +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 Peterson698a18a2010-03-02 22:34:37 +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 Peterson98047eb2010-03-03 02:07:08 +000096Later, calling :meth:`parse_args` will return an object with
Benjamin Peterson698a18a2010-03-02 22:34:37 +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.
101
Georg Brandle0bf91d2010-10-17 10:34:28 +0000102
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000103Parsing arguments
104^^^^^^^^^^^^^^^^^
105
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000106:class:`ArgumentParser` parses args through the
107:meth:`~ArgumentParser.parse_args` method. This will inspect the command-line,
Benjamin Peterson698a18a2010-03-02 22:34:37 +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::
111
112 >>> parser.parse_args(['--sum', '7', '-1', '42'])
113 Namespace(accumulate=<built-in function sum>, integers=[7, -1, 42])
114
Benjamin Peterson98047eb2010-03-03 02:07:08 +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 Peterson698a18a2010-03-02 22:34:37 +0000118
119
120ArgumentParser objects
121----------------------
122
Georg Brandlc9007082011-01-09 09:04:08 +0000123.. class:: ArgumentParser([description], [epilog], [prog], [usage], [add_help], \
124 [argument_default], [parents], [prefix_chars], \
125 [conflict_handler], [formatter_class])
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000126
127 Create a new :class:`ArgumentParser` object. Each parameter has its own more
128 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 Peterson98047eb2010-03-03 02:07:08 +0000134 * add_help_ - Add a -h/--help option to the parser. (default: ``True``)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000135
136 * argument_default_ - Set the global default value for arguments.
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000137 (default: ``None``)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000138
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000139 * parents_ - A list of :class:`ArgumentParser` objects whose arguments should
Benjamin Peterson698a18a2010-03-02 22:34:37 +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 Peterson98047eb2010-03-03 02:07:08 +0000146 which additional arguments should be read. (default: ``None``)
Benjamin Peterson698a18a2010-03-02 22:34:37 +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 Peterson98047eb2010-03-03 02:07:08 +0000153 * prog_ - The name of the program (default:
154 :data:`sys.argv[0]`)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000155
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000156 * usage_ - The string describing the program usage (default: generated)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000157
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000158The following sections describe how each of these are used.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000159
160
161description
162^^^^^^^^^^^
163
Benjamin Peterson98047eb2010-03-03 02:07:08 +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 Peterson698a18a2010-03-02 22:34:37 +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
180given space. To change this behavior, see the formatter_class_ argument.
181
182
183epilog
184^^^^^^
185
186Some programs like to display additional description of the program after the
187description of the arguments. Such text can be specified using the ``epilog=``
188argument to :class:`ArgumentParser`::
189
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 Peterson98047eb2010-03-03 02:07:08 +0000205argument to :class:`ArgumentParser`.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000206
207
208add_help
209^^^^^^^^
210
R. David Murray88c49fe2010-08-03 17:56:09 +0000211By default, ArgumentParser objects add an option which simply displays
212the parser's help message. For example, consider a file named
Benjamin Peterson698a18a2010-03-02 22:34:37 +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 Peterson98047eb2010-03-03 02:07:08 +0000232:class:`ArgumentParser`::
Benjamin Peterson698a18a2010-03-02 22:34:37 +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 Murray88c49fe2010-08-03 17:56:09 +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 Peterson698a18a2010-03-02 22:34:37 +0000256prefix_chars
257^^^^^^^^^^^^
258
259Most command-line options will use ``'-'`` as the prefix, e.g. ``-f/--foo``.
R. David Murray88c49fe2010-08-03 17:56:09 +0000260Parsers that need to support different or additional prefix
261characters, e.g. for options
Benjamin Peterson698a18a2010-03-02 22:34:37 +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 Peterson98047eb2010-03-03 02:07:08 +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 Peterson698a18a2010-03-02 22:34:37 +0000285
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000286 >>> with open('args.txt', 'w') as fp:
287 ... fp.write('-f\nbar')
Benjamin Peterson698a18a2010-03-02 22:34:37 +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
295place as the original file referencing argument on the command line. So in the
296example 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 Brandle0bf91d2010-10-17 10:34:28 +0000302
Benjamin Peterson698a18a2010-03-02 22:34:37 +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
308specific 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 Peterson98047eb2010-03-03 02:07:08 +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 Peterson698a18a2010-03-02 22:34:37 +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 Peterson98047eb2010-03-03 02:07:08 +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 Peterson698a18a2010-03-02 22:34:37 +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
346Note that most parent parsers will specify ``add_help=False``. Otherwise, the
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000347:class:`ArgumentParser` will see two ``-h/--help`` options (one in the parent
348and one in the child) and raise an error.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000349
350
351formatter_class
352^^^^^^^^^^^^^^^
353
Benjamin Peterson98047eb2010-03-03 02:07:08 +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`,
Benjamin Peterson698a18a2010-03-02 22:34:37 +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.
361
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000362By default, :class:`ArgumentParser` objects line-wrap the description_ and
363epilog_ texts in command-line help messages::
Benjamin Peterson698a18a2010-03-02 22:34:37 +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 Peterson98047eb2010-03-03 02:07:08 +0000385Passing :class:`argparse.RawDescriptionHelpFormatter` as ``formatter_class=``
386indicates that description_ and epilog_ are already correctly formatted and
387should not be line-wrapped::
Benjamin Peterson698a18a2010-03-02 22:34:37 +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 Peterson98047eb2010-03-03 02:07:08 +0000411:class:`RawTextHelpFormatter` maintains whitespace for all sorts of help text
412including argument descriptions.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000413
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000414The other formatter class available, :class:`ArgumentDefaultsHelpFormatter`,
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000415will add information about the default value of each of the arguments::
416
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 Peterson98047eb2010-03-03 02:07:08 +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 Peterson698a18a2010-03-02 22:34:37 +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
449older arguments with the same option string. To get this behavior, the value
450``'resolve'`` can be supplied to the ``conflict_handler=`` argument of
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000451:class:`ArgumentParser`::
Benjamin Peterson698a18a2010-03-02 22:34:37 +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 Peterson98047eb2010-03-03 02:07:08 +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 Peterson698a18a2010-03-02 22:34:37 +0000468
469
470prog
471^^^^
472
Benjamin Peterson98047eb2010-03-03 02:07:08 +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 Melottif82340d2010-05-27 22:38:16 +0000475always desirable because it will make the help messages match how the program was
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000476invoked on the command line. For example, consider a file named
477``myprogram.py`` with the following code::
Benjamin Peterson698a18a2010-03-02 22:34:37 +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 Peterson98047eb2010-03-03 02:07:08 +0000502``prog=`` argument to :class:`ArgumentParser`::
Benjamin Peterson698a18a2010-03-02 22:34:37 +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 Peterson98047eb2010-03-03 02:07:08 +0000530By default, :class:`ArgumentParser` calculates the usage message from the
Benjamin Peterson698a18a2010-03-02 22:34:37 +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 Peterson98047eb2010-03-03 02:07:08 +0000546The default message can be overridden with the ``usage=`` keyword argument::
Benjamin Peterson698a18a2010-03-02 22:34:37 +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 Peterson98047eb2010-03-03 02:07:08 +0000561The ``%(prog)s`` format specifier is available to fill in the program name in
562your usage messages.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000563
564
565The add_argument() method
566-------------------------
567
Georg Brandlc9007082011-01-09 09:04:08 +0000568.. method:: ArgumentParser.add_argument(name or flags..., [action], [nargs], \
569 [const], [default], [type], [choices], [required], \
570 [help], [metavar], [dest])
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000571
572 Define how a single command line argument should be parsed. Each parameter
573 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 Peterson98047eb2010-03-03 02:07:08 +0000602The following sections describe how each of these are used.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000603
Georg Brandle0bf91d2010-10-17 10:34:28 +0000604
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000605name or flags
606^^^^^^^^^^^^^
607
Benjamin Peterson98047eb2010-03-03 02:07:08 +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 Peterson698a18a2010-03-02 22:34:37 +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 Brandle0bf91d2010-10-17 10:34:28 +0000634
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000635action
636^^^^^^
637
638:class:`ArgumentParser` objects associate command-line args with actions. These
639actions 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 Peterson98047eb2010-03-03 02:07:08 +0000641:meth:`parse_args`. The ``action`` keyword argument specifies how the
642command-line args should be handled. The supported actions are:
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000643
644* ``'store'`` - This just stores the argument's value. This is the default
645 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 Peterson98047eb2010-03-03 02:07:08 +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 Peterson698a18a2010-03-02 22:34:37 +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 Peterson98047eb2010-03-03 02:07:08 +0000663 ``False`` respectively. These are special cases of ``'store_const'``. For
664 example::
Benjamin Peterson698a18a2010-03-02 22:34:37 +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 Peterson98047eb2010-03-03 02:07:08 +0000673 list. This is useful to allow an option to be specified multiple times.
674 Example usage::
Benjamin Peterson698a18a2010-03-02 22:34:37 +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 Peterson98047eb2010-03-03 02:07:08 +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 Peterson698a18a2010-03-02 22:34:37 +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 Bethard59710962010-05-24 03:21:08 +0000699 >>> parser.add_argument('--version', action='version', version='%(prog)s 2.0')
700 >>> parser.parse_args(['--version'])
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000701 PROG 2.0
702
703You can also specify an arbitrary action by passing an object that implements
Benjamin Peterson98047eb2010-03-03 02:07:08 +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 Peterson698a18a2010-03-02 22:34:37 +0000707
708* ``parser`` - The ArgumentParser object which contains this action.
709
710* ``namespace`` - The namespace object that will be returned by
711 :meth:`parse_args`. Most actions add an attribute to this object.
712
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 Peterson98047eb2010-03-03 02:07:08 +0000721An example of a custom action::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000722
723 >>> class FooAction(argparse.Action):
724 ... def __call__(self, parser, namespace, values, option_string=None):
Georg Brandl571a9532010-07-26 17:00:20 +0000725 ... print('%r %r %r' % (namespace, values, option_string))
726 ... setattr(namespace, self.dest, values)
Benjamin Peterson698a18a2010-03-02 22:34:37 +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 Peterson98047eb2010-03-03 02:07:08 +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 Peterson698a18a2010-03-02 22:34:37 +0000745
746* N (an integer). N args from the command-line will be gathered together into a
747 list. For example::
748
Georg Brandl682d7e02010-10-06 10:26:05 +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 Peterson698a18a2010-03-02 22:34:37 +0000754
Georg Brandl682d7e02010-10-06 10:26:05 +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 Peterson698a18a2010-03-02 22:34:37 +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
765 >>> 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')
774
775 One of the more common uses of ``nargs='?'`` is to allow optional input and
776 output files::
777
778 >>> parser = argparse.ArgumentParser()
Georg Brandle0bf91d2010-10-17 10:34:28 +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)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000783 >>> parser.parse_args(['input.txt', 'output.txt'])
Georg Brandl04536b02011-01-09 09:31:01 +0000784 Namespace(infile=<_io.TextIOWrapper name='input.txt' encoding='UTF-8'>,
785 outfile=<_io.TextIOWrapper name='output.txt' encoding='UTF-8'>)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000786 >>> parser.parse_args([])
Georg Brandl04536b02011-01-09 09:31:01 +0000787 Namespace(infile=<_io.TextIOWrapper name='<stdin>' encoding='UTF-8'>,
788 outfile=<_io.TextIOWrapper name='<stdout>' encoding='UTF-8'>)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000789
790* ``'*'``. 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::
794
795 >>> 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'])
801
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
806 >>> 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
813
814If the ``nargs`` keyword argument is not provided, the number of args consumed
815is determined by the action_. Generally this means a single command-line arg
816will 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
832 ``--foo``) and ``nargs='?'``. This creates an optional argument that can be
833 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 Peterson98047eb2010-03-03 02:07:08 +0000868Providing ``default=argparse.SUPPRESS`` causes no attribute to be added if the
869command-line argument was not present.::
Benjamin Peterson698a18a2010-03-02 22:34:37 +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
Georg Brandl04536b02011-01-09 09:31:01 +0000884another type, like a :class:`float` or :class:`int`. The ``type`` keyword
885argument of :meth:`add_argument` allows any necessary type-checking and
886type-conversions to be performed. Common built-in types and functions can be
887used directly as the value of the ``type`` argument::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000888
889 >>> parser = argparse.ArgumentParser()
890 >>> parser.add_argument('foo', type=int)
Georg Brandl04536b02011-01-09 09:31:01 +0000891 >>> parser.add_argument('bar', type=open)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000892 >>> parser.parse_args('2 temp.txt'.split())
Georg Brandl04536b02011-01-09 09:31:01 +0000893 Namespace(bar=<_io.TextIOWrapper name='temp.txt' encoding='UTF-8'>, foo=2)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000894
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 Brandl04536b02011-01-09 09:31:01 +0000897:func:`open` function. For example, ``FileType('w')`` can be used to create a
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000898writable file::
899
900 >>> parser = argparse.ArgumentParser()
901 >>> parser.add_argument('bar', type=argparse.FileType('w'))
902 >>> parser.parse_args(['out.txt'])
Georg Brandl04536b02011-01-09 09:31:01 +0000903 Namespace(bar=<_io.TextIOWrapper name='out.txt' encoding='UTF-8'>)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000904
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000905``type=`` can take any callable that takes a single string argument and returns
906the type-converted value::
Benjamin Peterson698a18a2010-03-02 22:34:37 +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 Peterson98047eb2010-03-03 02:07:08 +0000924The choices_ keyword argument may be more convenient for type checkers that
925simply check against a range of values::
Benjamin Peterson698a18a2010-03-02 22:34:37 +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 Peterson98047eb2010-03-03 02:07:08 +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 Peterson698a18a2010-03-02 22:34:37 +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``
968value, so :class:`dict` objects, :class:`set` objects, custom containers,
969etc. are all supported.
970
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 Peterson98047eb2010-03-03 02:07:08 +0000977To make an option *required*, ``True`` can be specified for the ``required=``
978keyword argument to :meth:`add_argument`::
Benjamin Peterson698a18a2010-03-02 22:34:37 +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 Peterson98047eb2010-03-03 02:07:08 +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 Peterson698a18a2010-03-02 22:34:37 +0000995
996
997help
998^^^^
999
Benjamin Peterson98047eb2010-03-03 02:07:08 +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
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001003argument::
1004
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 Peterson98047eb2010-03-03 02:07:08 +00001041When :class:`ArgumentParser` generates help messages, it need some way to refer
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001042to each expected argument. By default, ArgumentParser objects use the dest_
1043value as the "name" of each object. By default, for positional argument
1044actions, the dest_ value is used directly, and for optional argument actions,
Benjamin Peterson98047eb2010-03-03 02:07:08 +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 Peterson698a18a2010-03-02 22:34:37 +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 Peterson98047eb2010-03-03 02:07:08 +00001065An alternative name can be specified with ``metavar``::
Benjamin Peterson698a18a2010-03-02 22:34:37 +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 Peterson98047eb2010-03-03 02:07:08 +00001087Providing a tuple to ``metavar`` specifies a different display for each of the
1088arguments::
Benjamin Peterson698a18a2010-03-02 22:34:37 +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 Peterson98047eb2010-03-03 02:07:08 +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 Peterson698a18a2010-03-02 22:34:37 +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 Peterson98047eb2010-03-03 02:07:08 +00001117the option strings. :class:`ArgumentParser` generates the value of ``dest`` by
Benjamin Peterson698a18a2010-03-02 22:34:37 +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
1121internal ``'-'`` characters will be converted to ``'_'`` characters to make sure
1122the string is a valid attribute name. The examples below illustrate this
1123behavior::
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 Peterson98047eb2010-03-03 02:07:08 +00001133``dest`` allows a custom attribute name to be provided::
Benjamin Peterson698a18a2010-03-02 22:34:37 +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 Brandle0bf91d2010-10-17 10:34:28 +00001144.. method:: ArgumentParser.parse_args(args=None, namespace=None)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001145
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001146 Convert argument strings to objects and assign them as attributes of the
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001147 namespace. Return the populated namespace.
1148
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
1153 By default, the arg strings are taken from :data:`sys.argv`, and a new empty
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001154 :class:`Namespace` object is created for the attributes.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001155
Georg Brandle0bf91d2010-10-17 10:34:28 +00001156
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001157Option value syntax
1158^^^^^^^^^^^^^^^^^^^
1159
1160The :meth:`parse_args` method supports several ways of specifying the value of
1161an option (if it takes one). In the simplest case, the option and its value are
1162passed 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 Peterson98047eb2010-03-03 02:07:08 +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
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001174separate them::
1175
1176 >>> parser.parse_args('--foo=FOO'.split())
1177 Namespace(foo='FOO', x=None)
1178
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001179For short options (options only one character long), the option and its value
1180can be concatenated::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001181
1182 >>> parser.parse_args('-xX'.split())
1183 Namespace(foo=None, x='X')
1184
Benjamin Peterson98047eb2010-03-03 02:07:08 +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 Peterson698a18a2010-03-02 22:34:37 +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
1201positional arguments, etc. When it encounters such an error, it exits and
1202prints 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
1228made a mistake, but some situations are inherently ambiguous. For example, the
1229command-line arg ``'-1'`` could either be an attempt to specify an option or an
1230attempt to provide a positional argument. The ``parse_args`` method is cautious
1231here: 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 Peterson98047eb2010-03-03 02:07:08 +00001276The :meth:`parse_args` method allows long options to be abbreviated if the
Benjamin Peterson698a18a2010-03-02 22:34:37 +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 Peterson98047eb2010-03-03 02:07:08 +00001290An error is produced for arguments that could produce more than one options.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001291
1292
1293Beyond ``sys.argv``
1294^^^^^^^^^^^^^^^^^^^
1295
1296Sometimes 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 Peterson98047eb2010-03-03 02:07:08 +00001298``parse_args``. This is useful for testing at the interactive prompt::
Benjamin Peterson698a18a2010-03-02 22:34:37 +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 Peterson98047eb2010-03-03 02:07:08 +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 Peterson698a18a2010-03-02 22:34:37 +00001320
Éric Araujo28053fb2010-11-22 03:09:19 +00001321 >>> class C:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001322 ... 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 Peterson98047eb2010-03-03 02:07:08 +00001338.. method:: ArgumentParser.add_subparsers()
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001339
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001340 Many programs split up their functionality into a number of sub-commands,
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001341 for example, the ``svn`` program can invoke sub-commands like ``svn
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001342 checkout``, ``svn update``, and ``svn commit``. Splitting up functionality
Benjamin Peterson698a18a2010-03-02 22:34:37 +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 Peterson98047eb2010-03-03 02:07:08 +00001345 :class:`ArgumentParser` supports the creation of such sub-commands with the
Benjamin Peterson698a18a2010-03-02 22:34:37 +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 Peterson98047eb2010-03-03 02:07:08 +00001349 :class:`ArgumentParser` constructor arguments, and returns an
1350 :class:`ArgumentParser` object that can be modified as usual.
Benjamin Peterson698a18a2010-03-02 22:34:37 +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
1376 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
1378 ``baz`` attributes are present.
1379
1380 Similarly, when a help message is requested from a subparser, only the help
1381 for that particular parser will be printed. The help message will not
Benjamin Peterson98047eb2010-03-03 02:07:08 +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 Peterson698a18a2010-03-02 22:34:37 +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
1416 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::
1419
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
Steven Bethardfd311a72010-12-18 11:19:23 +00001437 Furthermore, ``add_parser`` supports an additional ``aliases`` argument,
1438 which allows multiple strings to refer to the same subparser. This example,
1439 like ``svn``, aliases ``co`` as a shorthand for ``checkout``::
1440
1441 >>> parser = argparse.ArgumentParser()
1442 >>> subparsers = parser.add_subparsers()
1443 >>> checkout = subparsers.add_parser('checkout', aliases=['co'])
1444 >>> checkout.add_argument('foo')
1445 >>> parser.parse_args(['co', 'bar'])
1446 Namespace(foo='bar')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001447
1448 One particularly effective way of handling sub-commands is to combine the use
1449 of the :meth:`add_subparsers` method with calls to :meth:`set_defaults` so
1450 that each subparser knows which Python function it should execute. For
1451 example::
1452
1453 >>> # sub-command functions
1454 >>> def foo(args):
Benjamin Petersonb2deb112010-03-03 02:09:18 +00001455 ... print(args.x * args.y)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001456 ...
1457 >>> def bar(args):
Benjamin Petersonb2deb112010-03-03 02:09:18 +00001458 ... print('((%s))' % args.z)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001459 ...
1460 >>> # create the top-level parser
1461 >>> parser = argparse.ArgumentParser()
1462 >>> subparsers = parser.add_subparsers()
1463 >>>
1464 >>> # create the parser for the "foo" command
1465 >>> parser_foo = subparsers.add_parser('foo')
1466 >>> parser_foo.add_argument('-x', type=int, default=1)
1467 >>> parser_foo.add_argument('y', type=float)
1468 >>> parser_foo.set_defaults(func=foo)
1469 >>>
1470 >>> # create the parser for the "bar" command
1471 >>> parser_bar = subparsers.add_parser('bar')
1472 >>> parser_bar.add_argument('z')
1473 >>> parser_bar.set_defaults(func=bar)
1474 >>>
1475 >>> # parse the args and call whatever function was selected
1476 >>> args = parser.parse_args('foo 1 -x 2'.split())
1477 >>> args.func(args)
1478 2.0
1479 >>>
1480 >>> # parse the args and call whatever function was selected
1481 >>> args = parser.parse_args('bar XYZYX'.split())
1482 >>> args.func(args)
1483 ((XYZYX))
1484
Steven Bethardfd311a72010-12-18 11:19:23 +00001485 This way, you can let :meth:`parse_args` do the job of calling the
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001486 appropriate function after argument parsing is complete. Associating
1487 functions with actions like this is typically the easiest way to handle the
1488 different actions for each of your subparsers. However, if it is necessary
1489 to check the name of the subparser that was invoked, the ``dest`` keyword
1490 argument to the :meth:`add_subparsers` call will work::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001491
1492 >>> parser = argparse.ArgumentParser()
1493 >>> subparsers = parser.add_subparsers(dest='subparser_name')
1494 >>> subparser1 = subparsers.add_parser('1')
1495 >>> subparser1.add_argument('-x')
1496 >>> subparser2 = subparsers.add_parser('2')
1497 >>> subparser2.add_argument('y')
1498 >>> parser.parse_args(['2', 'frobble'])
1499 Namespace(subparser_name='2', y='frobble')
1500
1501
1502FileType objects
1503^^^^^^^^^^^^^^^^
1504
1505.. class:: FileType(mode='r', bufsize=None)
1506
1507 The :class:`FileType` factory creates objects that can be passed to the type
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001508 argument of :meth:`ArgumentParser.add_argument`. Arguments that have
1509 :class:`FileType` objects as their type will open command-line args as files
1510 with the requested modes and buffer sizes:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001511
1512 >>> parser = argparse.ArgumentParser()
1513 >>> parser.add_argument('--output', type=argparse.FileType('wb', 0))
1514 >>> parser.parse_args(['--output', 'out'])
Georg Brandl04536b02011-01-09 09:31:01 +00001515 Namespace(output=<_io.BufferedWriter name='out'>)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001516
1517 FileType objects understand the pseudo-argument ``'-'`` and automatically
1518 convert this into ``sys.stdin`` for readable :class:`FileType` objects and
1519 ``sys.stdout`` for writable :class:`FileType` objects:
1520
1521 >>> parser = argparse.ArgumentParser()
1522 >>> parser.add_argument('infile', type=argparse.FileType('r'))
1523 >>> parser.parse_args(['-'])
Georg Brandl04536b02011-01-09 09:31:01 +00001524 Namespace(infile=<_io.TextIOWrapper name='<stdin>' encoding='UTF-8'>)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001525
1526
1527Argument groups
1528^^^^^^^^^^^^^^^
1529
Georg Brandle0bf91d2010-10-17 10:34:28 +00001530.. method:: ArgumentParser.add_argument_group(title=None, description=None)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001531
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001532 By default, :class:`ArgumentParser` groups command-line arguments into
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001533 "positional arguments" and "optional arguments" when displaying help
1534 messages. When there is a better conceptual grouping of arguments than this
1535 default one, appropriate groups can be created using the
1536 :meth:`add_argument_group` method::
1537
1538 >>> parser = argparse.ArgumentParser(prog='PROG', add_help=False)
1539 >>> group = parser.add_argument_group('group')
1540 >>> group.add_argument('--foo', help='foo help')
1541 >>> group.add_argument('bar', help='bar help')
1542 >>> parser.print_help()
1543 usage: PROG [--foo FOO] bar
1544
1545 group:
1546 bar bar help
1547 --foo FOO foo help
1548
1549 The :meth:`add_argument_group` method returns an argument group object which
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001550 has an :meth:`~ArgumentParser.add_argument` method just like a regular
1551 :class:`ArgumentParser`. When an argument is added to the group, the parser
1552 treats it just like a normal argument, but displays the argument in a
1553 separate group for help messages. The :meth:`add_argument_group` method
Georg Brandle0bf91d2010-10-17 10:34:28 +00001554 accepts *title* and *description* arguments which can be used to
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001555 customize this display::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001556
1557 >>> parser = argparse.ArgumentParser(prog='PROG', add_help=False)
1558 >>> group1 = parser.add_argument_group('group1', 'group1 description')
1559 >>> group1.add_argument('foo', help='foo help')
1560 >>> group2 = parser.add_argument_group('group2', 'group2 description')
1561 >>> group2.add_argument('--bar', help='bar help')
1562 >>> parser.print_help()
1563 usage: PROG [--bar BAR] foo
1564
1565 group1:
1566 group1 description
1567
1568 foo foo help
1569
1570 group2:
1571 group2 description
1572
1573 --bar BAR bar help
1574
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001575 Note that any arguments not your user defined groups will end up back in the
1576 usual "positional arguments" and "optional arguments" sections.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001577
1578
1579Mutual exclusion
1580^^^^^^^^^^^^^^^^
1581
Georg Brandle0bf91d2010-10-17 10:34:28 +00001582.. method:: add_mutually_exclusive_group(required=False)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001583
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001584 Create a mutually exclusive group. argparse will make sure that only one of
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001585 the arguments in the mutually exclusive group was present on the command
1586 line::
1587
1588 >>> parser = argparse.ArgumentParser(prog='PROG')
1589 >>> group = parser.add_mutually_exclusive_group()
1590 >>> group.add_argument('--foo', action='store_true')
1591 >>> group.add_argument('--bar', action='store_false')
1592 >>> parser.parse_args(['--foo'])
1593 Namespace(bar=True, foo=True)
1594 >>> parser.parse_args(['--bar'])
1595 Namespace(bar=False, foo=False)
1596 >>> parser.parse_args(['--foo', '--bar'])
1597 usage: PROG [-h] [--foo | --bar]
1598 PROG: error: argument --bar: not allowed with argument --foo
1599
Georg Brandle0bf91d2010-10-17 10:34:28 +00001600 The :meth:`add_mutually_exclusive_group` method also accepts a *required*
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001601 argument, to indicate that at least one of the mutually exclusive arguments
1602 is required::
1603
1604 >>> parser = argparse.ArgumentParser(prog='PROG')
1605 >>> group = parser.add_mutually_exclusive_group(required=True)
1606 >>> group.add_argument('--foo', action='store_true')
1607 >>> group.add_argument('--bar', action='store_false')
1608 >>> parser.parse_args([])
1609 usage: PROG [-h] (--foo | --bar)
1610 PROG: error: one of the arguments --foo --bar is required
1611
1612 Note that currently mutually exclusive argument groups do not support the
Georg Brandle0bf91d2010-10-17 10:34:28 +00001613 *title* and *description* arguments of :meth:`add_argument_group`.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001614
1615
1616Parser defaults
1617^^^^^^^^^^^^^^^
1618
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001619.. method:: ArgumentParser.set_defaults(**kwargs)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001620
1621 Most of the time, the attributes of the object returned by :meth:`parse_args`
1622 will be fully determined by inspecting the command-line args and the argument
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001623 actions. :meth:`ArgumentParser.set_defaults` allows some additional
1624 attributes that are determined without any inspection of the command-line to
1625 be added::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001626
1627 >>> parser = argparse.ArgumentParser()
1628 >>> parser.add_argument('foo', type=int)
1629 >>> parser.set_defaults(bar=42, baz='badger')
1630 >>> parser.parse_args(['736'])
1631 Namespace(bar=42, baz='badger', foo=736)
1632
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001633 Note that parser-level defaults always override argument-level defaults::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001634
1635 >>> parser = argparse.ArgumentParser()
1636 >>> parser.add_argument('--foo', default='bar')
1637 >>> parser.set_defaults(foo='spam')
1638 >>> parser.parse_args([])
1639 Namespace(foo='spam')
1640
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001641 Parser-level defaults can be particularly useful when working with multiple
1642 parsers. See the :meth:`~ArgumentParser.add_subparsers` method for an
1643 example of this type.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001644
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001645.. method:: ArgumentParser.get_default(dest)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001646
1647 Get the default value for a namespace attribute, as set by either
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001648 :meth:`~ArgumentParser.add_argument` or by
1649 :meth:`~ArgumentParser.set_defaults`::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001650
1651 >>> parser = argparse.ArgumentParser()
1652 >>> parser.add_argument('--foo', default='badger')
1653 >>> parser.get_default('foo')
1654 'badger'
1655
1656
1657Printing help
1658^^^^^^^^^^^^^
1659
1660In most typical applications, :meth:`parse_args` will take care of formatting
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001661and printing any usage or error messages. However, several formatting methods
1662are available:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001663
Georg Brandle0bf91d2010-10-17 10:34:28 +00001664.. method:: ArgumentParser.print_usage(file=None)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001665
1666 Print a brief description of how the :class:`ArgumentParser` should be
R. David Murray32e17712010-12-18 16:39:06 +00001667 invoked on the command line. If *file* is ``None``, :data:`sys.stdout` is
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001668 assumed.
1669
Georg Brandle0bf91d2010-10-17 10:34:28 +00001670.. method:: ArgumentParser.print_help(file=None)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001671
1672 Print a help message, including the program usage and information about the
Georg Brandle0bf91d2010-10-17 10:34:28 +00001673 arguments registered with the :class:`ArgumentParser`. If *file* is
R. David Murray32e17712010-12-18 16:39:06 +00001674 ``None``, :data:`sys.stdout` is assumed.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001675
1676There are also variants of these methods that simply return a string instead of
1677printing it:
1678
Georg Brandle0bf91d2010-10-17 10:34:28 +00001679.. method:: ArgumentParser.format_usage()
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001680
1681 Return a string containing a brief description of how the
1682 :class:`ArgumentParser` should be invoked on the command line.
1683
Georg Brandle0bf91d2010-10-17 10:34:28 +00001684.. method:: ArgumentParser.format_help()
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001685
1686 Return a string containing a help message, including the program usage and
1687 information about the arguments registered with the :class:`ArgumentParser`.
1688
1689
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001690Partial parsing
1691^^^^^^^^^^^^^^^
1692
Georg Brandle0bf91d2010-10-17 10:34:28 +00001693.. method:: ArgumentParser.parse_known_args(args=None, namespace=None)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001694
1695Sometimes a script may only parse a few of the command line arguments, passing
1696the remaining arguments on to another script or program. In these cases, the
1697:meth:`parse_known_args` method can be useful. It works much like
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001698:meth:`~ArgumentParser.parse_args` except that it does not produce an error when
1699extra arguments are present. Instead, it returns a two item tuple containing
1700the populated namespace and the list of remaining argument strings.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001701
1702::
1703
1704 >>> parser = argparse.ArgumentParser()
1705 >>> parser.add_argument('--foo', action='store_true')
1706 >>> parser.add_argument('bar')
1707 >>> parser.parse_known_args(['--foo', '--badger', 'BAR', 'spam'])
1708 (Namespace(bar='BAR', foo=True), ['--badger', 'spam'])
1709
1710
1711Customizing file parsing
1712^^^^^^^^^^^^^^^^^^^^^^^^
1713
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001714.. method:: ArgumentParser.convert_arg_line_to_args(arg_line)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001715
Georg Brandle0bf91d2010-10-17 10:34:28 +00001716 Arguments that are read from a file (see the *fromfile_prefix_chars*
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001717 keyword argument to the :class:`ArgumentParser` constructor) are read one
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001718 argument per line. :meth:`convert_arg_line_to_args` can be overriden for
1719 fancier reading.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001720
Georg Brandle0bf91d2010-10-17 10:34:28 +00001721 This method takes a single argument *arg_line* which is a string read from
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001722 the argument file. It returns a list of arguments parsed from this string.
1723 The method is called once per line read from the argument file, in order.
1724
1725 A useful override of this method is one that treats each space-separated word
1726 as an argument::
1727
1728 def convert_arg_line_to_args(self, arg_line):
1729 for arg in arg_line.split():
1730 if not arg.strip():
1731 continue
1732 yield arg
1733
1734
Georg Brandl93754922010-10-17 10:28:04 +00001735Exiting methods
1736^^^^^^^^^^^^^^^
1737
1738.. method:: ArgumentParser.exit(status=0, message=None)
1739
1740 This method terminates the program, exiting with the specified *status*
1741 and, if given, it prints a *message* before that.
1742
1743.. method:: ArgumentParser.error(message)
1744
1745 This method prints a usage message including the *message* to the
1746 standard output and terminates the program with a status code of 2.
1747
Raymond Hettinger677e10a2010-12-07 06:45:30 +00001748.. _upgrading-optparse-code:
Georg Brandl93754922010-10-17 10:28:04 +00001749
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001750Upgrading optparse code
1751-----------------------
1752
1753Originally, the argparse module had attempted to maintain compatibility with
1754optparse. However, optparse was difficult to extend transparently, particularly
1755with the changes required to support the new ``nargs=`` specifiers and better
Georg Brandl386bc6d2010-04-25 10:19:53 +00001756usage messages. When most everything in optparse had either been copy-pasted
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001757over or monkey-patched, it no longer seemed practical to try to maintain the
1758backwards compatibility.
1759
1760A partial upgrade path from optparse to argparse:
1761
Georg Brandlc9007082011-01-09 09:04:08 +00001762* Replace all ``add_option()`` calls with :meth:`ArgumentParser.add_argument`
1763 calls.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001764
1765* Replace ``options, args = parser.parse_args()`` with ``args =
Georg Brandlc9007082011-01-09 09:04:08 +00001766 parser.parse_args()`` and add additional :meth:`ArgumentParser.add_argument`
1767 calls for the positional arguments.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001768
1769* Replace callback actions and the ``callback_*`` keyword arguments with
1770 ``type`` or ``action`` arguments.
1771
1772* Replace string names for ``type`` keyword arguments with the corresponding
1773 type objects (e.g. int, float, complex, etc).
1774
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001775* Replace :class:`optparse.Values` with :class:`Namespace` and
1776 :exc:`optparse.OptionError` and :exc:`optparse.OptionValueError` with
1777 :exc:`ArgumentError`.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001778
1779* Replace strings with implicit arguments such as ``%default`` or ``%prog`` with
1780 the standard python syntax to use dictionaries to format strings, that is,
1781 ``%(default)s`` and ``%(prog)s``.
Steven Bethard59710962010-05-24 03:21:08 +00001782
1783* Replace the OptionParser constructor ``version`` argument with a call to
1784 ``parser.add_argument('--version', action='version', version='<the version>')``