blob: 61e1786b017a8993be5aa1a87e9006668fe11de9 [file] [log] [blame]
Georg Brandl1d827ff2011-04-16 16:44:54 +02001:mod:`argparse` --- Parser for command-line options, arguments and sub-commands
Georg Brandle0bf91d2010-10-17 10:34:28 +00002===============================================================================
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003
4.. module:: argparse
Ezio Melotti2409d772011-04-16 23:13:50 +03005 :synopsis: Command-line option and argument-parsing library.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00006.. moduleauthor:: Steven Bethard <steven.bethard@gmail.com>
Benjamin Peterson698a18a2010-03-02 22:34:37 +00007.. sectionauthor:: Steven Bethard <steven.bethard@gmail.com>
8
Raymond Hettingera1993682011-01-27 01:20:32 +00009**Source code:** :source:`Lib/argparse.py`
10
11.. versionadded:: 3.2
12
13--------------
Benjamin Peterson698a18a2010-03-02 22:34:37 +000014
Ezio Melotti2409d772011-04-16 23:13:50 +030015The :mod:`argparse` module makes it easy to write user-friendly command-line
Benjamin Peterson98047eb2010-03-03 02:07:08 +000016interfaces. The program defines what arguments it requires, and :mod:`argparse`
Benjamin Peterson698a18a2010-03-02 22:34:37 +000017will figure out how to parse those out of :data:`sys.argv`. The :mod:`argparse`
Benjamin Peterson98047eb2010-03-03 02:07:08 +000018module also automatically generates help and usage messages and issues errors
19when users give the program invalid arguments.
Benjamin Peterson698a18a2010-03-02 22:34:37 +000020
Georg Brandle0bf91d2010-10-17 10:34:28 +000021
Benjamin Peterson698a18a2010-03-02 22:34:37 +000022Example
23-------
24
Benjamin Peterson98047eb2010-03-03 02:07:08 +000025The following code is a Python program that takes a list of integers and
26produces either the sum or the max::
Benjamin Peterson698a18a2010-03-02 22:34:37 +000027
28 import argparse
29
30 parser = argparse.ArgumentParser(description='Process some integers.')
31 parser.add_argument('integers', metavar='N', type=int, nargs='+',
32 help='an integer for the accumulator')
33 parser.add_argument('--sum', dest='accumulate', action='store_const',
34 const=sum, default=max,
35 help='sum the integers (default: find the max)')
36
37 args = parser.parse_args()
Benjamin Petersonb2deb112010-03-03 02:09:18 +000038 print(args.accumulate(args.integers))
Benjamin Peterson698a18a2010-03-02 22:34:37 +000039
40Assuming the Python code above is saved into a file called ``prog.py``, it can
41be run at the command line and provides useful help messages::
42
43 $ prog.py -h
44 usage: prog.py [-h] [--sum] N [N ...]
45
46 Process some integers.
47
48 positional arguments:
49 N an integer for the accumulator
50
51 optional arguments:
52 -h, --help show this help message and exit
53 --sum sum the integers (default: find the max)
54
55When run with the appropriate arguments, it prints either the sum or the max of
56the command-line integers::
57
58 $ prog.py 1 2 3 4
59 4
60
61 $ prog.py 1 2 3 4 --sum
62 10
63
64If invalid arguments are passed in, it will issue an error::
65
66 $ prog.py a b c
67 usage: prog.py [-h] [--sum] N [N ...]
68 prog.py: error: argument N: invalid int value: 'a'
69
70The following sections walk you through this example.
71
Georg Brandle0bf91d2010-10-17 10:34:28 +000072
Benjamin Peterson698a18a2010-03-02 22:34:37 +000073Creating a parser
74^^^^^^^^^^^^^^^^^
75
Benjamin Peterson2614cda2010-03-21 22:36:19 +000076The first step in using the :mod:`argparse` is creating an
Benjamin Peterson98047eb2010-03-03 02:07:08 +000077:class:`ArgumentParser` object::
Benjamin Peterson698a18a2010-03-02 22:34:37 +000078
79 >>> parser = argparse.ArgumentParser(description='Process some integers.')
80
81The :class:`ArgumentParser` object will hold all the information necessary to
Ezio Melotticca4ef82011-04-21 15:26:46 +030082parse the command line into Python data types.
Benjamin Peterson698a18a2010-03-02 22:34:37 +000083
84
85Adding arguments
86^^^^^^^^^^^^^^^^
87
Benjamin Peterson98047eb2010-03-03 02:07:08 +000088Filling an :class:`ArgumentParser` with information about program arguments is
89done by making calls to the :meth:`~ArgumentParser.add_argument` method.
90Generally, these calls tell the :class:`ArgumentParser` how to take the strings
91on the command line and turn them into objects. This information is stored and
92used when :meth:`~ArgumentParser.parse_args` is called. For example::
Benjamin Peterson698a18a2010-03-02 22:34:37 +000093
94 >>> parser.add_argument('integers', metavar='N', type=int, nargs='+',
95 ... help='an integer for the accumulator')
96 >>> parser.add_argument('--sum', dest='accumulate', action='store_const',
97 ... const=sum, default=max,
98 ... help='sum the integers (default: find the max)')
99
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300100Later, calling :meth:`~ArgumentParser.parse_args` will return an object with
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000101two attributes, ``integers`` and ``accumulate``. The ``integers`` attribute
102will be a list of one or more ints, and the ``accumulate`` attribute will be
103either the :func:`sum` function, if ``--sum`` was specified at the command line,
104or the :func:`max` function if it was not.
105
Georg Brandle0bf91d2010-10-17 10:34:28 +0000106
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000107Parsing arguments
108^^^^^^^^^^^^^^^^^
109
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000110:class:`ArgumentParser` parses args through the
Georg Brandl1d827ff2011-04-16 16:44:54 +0200111:meth:`~ArgumentParser.parse_args` method. This will inspect the command line,
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000112convert each arg to the appropriate type and then invoke the appropriate action.
113In most cases, this means a simple namespace object will be built up from
Georg Brandl1d827ff2011-04-16 16:44:54 +0200114attributes parsed out of the command line::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000115
116 >>> parser.parse_args(['--sum', '7', '-1', '42'])
117 Namespace(accumulate=<built-in function sum>, integers=[7, -1, 42])
118
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000119In a script, :meth:`~ArgumentParser.parse_args` will typically be called with no
120arguments, and the :class:`ArgumentParser` will automatically determine the
121command-line args from :data:`sys.argv`.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000122
123
124ArgumentParser objects
125----------------------
126
Georg Brandlc9007082011-01-09 09:04:08 +0000127.. class:: ArgumentParser([description], [epilog], [prog], [usage], [add_help], \
128 [argument_default], [parents], [prefix_chars], \
129 [conflict_handler], [formatter_class])
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000130
131 Create a new :class:`ArgumentParser` object. Each parameter has its own more
132 detailed description below, but in short they are:
133
134 * description_ - Text to display before the argument help.
135
136 * epilog_ - Text to display after the argument help.
137
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000138 * add_help_ - Add a -h/--help option to the parser. (default: ``True``)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000139
140 * argument_default_ - Set the global default value for arguments.
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000141 (default: ``None``)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000142
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000143 * parents_ - A list of :class:`ArgumentParser` objects whose arguments should
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000144 also be included.
145
146 * prefix_chars_ - The set of characters that prefix optional arguments.
147 (default: '-')
148
149 * fromfile_prefix_chars_ - The set of characters that prefix files from
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000150 which additional arguments should be read. (default: ``None``)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000151
152 * formatter_class_ - A class for customizing the help output.
153
154 * conflict_handler_ - Usually unnecessary, defines strategy for resolving
155 conflicting optionals.
156
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000157 * prog_ - The name of the program (default:
158 :data:`sys.argv[0]`)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000159
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000160 * usage_ - The string describing the program usage (default: generated)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000161
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000162The following sections describe how each of these are used.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000163
164
165description
166^^^^^^^^^^^
167
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000168Most calls to the :class:`ArgumentParser` constructor will use the
169``description=`` keyword argument. This argument gives a brief description of
170what the program does and how it works. In help messages, the description is
171displayed between the command-line usage string and the help messages for the
172various arguments::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000173
174 >>> parser = argparse.ArgumentParser(description='A foo that bars')
175 >>> parser.print_help()
176 usage: argparse.py [-h]
177
178 A foo that bars
179
180 optional arguments:
181 -h, --help show this help message and exit
182
183By default, the description will be line-wrapped so that it fits within the
184given space. To change this behavior, see the formatter_class_ argument.
185
186
187epilog
188^^^^^^
189
190Some programs like to display additional description of the program after the
191description of the arguments. Such text can be specified using the ``epilog=``
192argument to :class:`ArgumentParser`::
193
194 >>> parser = argparse.ArgumentParser(
195 ... description='A foo that bars',
196 ... epilog="And that's how you'd foo a bar")
197 >>> parser.print_help()
198 usage: argparse.py [-h]
199
200 A foo that bars
201
202 optional arguments:
203 -h, --help show this help message and exit
204
205 And that's how you'd foo a bar
206
207As with the description_ argument, the ``epilog=`` text is by default
208line-wrapped, but this behavior can be adjusted with the formatter_class_
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000209argument to :class:`ArgumentParser`.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000210
211
212add_help
213^^^^^^^^
214
R. David Murray88c49fe2010-08-03 17:56:09 +0000215By default, ArgumentParser objects add an option which simply displays
216the parser's help message. For example, consider a file named
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000217``myprogram.py`` containing the following code::
218
219 import argparse
220 parser = argparse.ArgumentParser()
221 parser.add_argument('--foo', help='foo help')
222 args = parser.parse_args()
223
Georg Brandl1d827ff2011-04-16 16:44:54 +0200224If ``-h`` or ``--help`` is supplied at the command line, the ArgumentParser
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000225help will be printed::
226
227 $ python myprogram.py --help
228 usage: myprogram.py [-h] [--foo FOO]
229
230 optional arguments:
231 -h, --help show this help message and exit
232 --foo FOO foo help
233
234Occasionally, it may be useful to disable the addition of this help option.
235This can be achieved by passing ``False`` as the ``add_help=`` argument to
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000236:class:`ArgumentParser`::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000237
238 >>> parser = argparse.ArgumentParser(prog='PROG', add_help=False)
239 >>> parser.add_argument('--foo', help='foo help')
240 >>> parser.print_help()
241 usage: PROG [--foo FOO]
242
243 optional arguments:
244 --foo FOO foo help
245
R. David Murray88c49fe2010-08-03 17:56:09 +0000246The help option is typically ``-h/--help``. The exception to this is
247if the ``prefix_chars=`` is specified and does not include ``'-'``, in
248which case ``-h`` and ``--help`` are not valid options. In
249this case, the first character in ``prefix_chars`` is used to prefix
250the help options::
251
252 >>> parser = argparse.ArgumentParser(prog='PROG', prefix_chars='+/')
253 >>> parser.print_help()
254 usage: PROG [+h]
255
256 optional arguments:
257 +h, ++help show this help message and exit
258
259
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000260prefix_chars
261^^^^^^^^^^^^
262
263Most command-line options will use ``'-'`` as the prefix, e.g. ``-f/--foo``.
R. David Murray88c49fe2010-08-03 17:56:09 +0000264Parsers that need to support different or additional prefix
265characters, e.g. for options
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000266like ``+f`` or ``/foo``, may specify them using the ``prefix_chars=`` argument
267to the ArgumentParser constructor::
268
269 >>> parser = argparse.ArgumentParser(prog='PROG', prefix_chars='-+')
270 >>> parser.add_argument('+f')
271 >>> parser.add_argument('++bar')
272 >>> parser.parse_args('+f X ++bar Y'.split())
273 Namespace(bar='Y', f='X')
274
275The ``prefix_chars=`` argument defaults to ``'-'``. Supplying a set of
276characters that does not include ``'-'`` will cause ``-f/--foo`` options to be
277disallowed.
278
279
280fromfile_prefix_chars
281^^^^^^^^^^^^^^^^^^^^^
282
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000283Sometimes, for example when dealing with a particularly long argument lists, it
284may make sense to keep the list of arguments in a file rather than typing it out
285at the command line. If the ``fromfile_prefix_chars=`` argument is given to the
286:class:`ArgumentParser` constructor, then arguments that start with any of the
287specified characters will be treated as files, and will be replaced by the
288arguments they contain. For example::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000289
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000290 >>> with open('args.txt', 'w') as fp:
291 ... fp.write('-f\nbar')
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000292 >>> parser = argparse.ArgumentParser(fromfile_prefix_chars='@')
293 >>> parser.add_argument('-f')
294 >>> parser.parse_args(['-f', 'foo', '@args.txt'])
295 Namespace(f='bar')
296
297Arguments read from a file must by default be one per line (but see also
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300298:meth:`~ArgumentParser.convert_arg_line_to_args`) and are treated as if they
299were in the same place as the original file referencing argument on the command
300line. So in the example above, the expression ``['-f', 'foo', '@args.txt']``
301is considered equivalent to the expression ``['-f', 'foo', '-f', 'bar']``.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000302
303The ``fromfile_prefix_chars=`` argument defaults to ``None``, meaning that
304arguments will never be treated as file references.
305
Georg Brandle0bf91d2010-10-17 10:34:28 +0000306
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000307argument_default
308^^^^^^^^^^^^^^^^
309
310Generally, argument defaults are specified either by passing a default to
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300311:meth:`~ArgumentParser.add_argument` or by calling the
312:meth:`~ArgumentParser.set_defaults` methods with a specific set of name-value
313pairs. Sometimes however, it may be useful to specify a single parser-wide
314default for arguments. This can be accomplished by passing the
315``argument_default=`` keyword argument to :class:`ArgumentParser`. For example,
316to globally suppress attribute creation on :meth:`~ArgumentParser.parse_args`
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000317calls, we supply ``argument_default=SUPPRESS``::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000318
319 >>> parser = argparse.ArgumentParser(argument_default=argparse.SUPPRESS)
320 >>> parser.add_argument('--foo')
321 >>> parser.add_argument('bar', nargs='?')
322 >>> parser.parse_args(['--foo', '1', 'BAR'])
323 Namespace(bar='BAR', foo='1')
324 >>> parser.parse_args([])
325 Namespace()
326
327
328parents
329^^^^^^^
330
331Sometimes, several parsers share a common set of arguments. Rather than
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000332repeating the definitions of these arguments, a single parser with all the
333shared arguments and passed to ``parents=`` argument to :class:`ArgumentParser`
334can be used. The ``parents=`` argument takes a list of :class:`ArgumentParser`
335objects, collects all the positional and optional actions from them, and adds
336these actions to the :class:`ArgumentParser` object being constructed::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000337
338 >>> parent_parser = argparse.ArgumentParser(add_help=False)
339 >>> parent_parser.add_argument('--parent', type=int)
340
341 >>> foo_parser = argparse.ArgumentParser(parents=[parent_parser])
342 >>> foo_parser.add_argument('foo')
343 >>> foo_parser.parse_args(['--parent', '2', 'XXX'])
344 Namespace(foo='XXX', parent=2)
345
346 >>> bar_parser = argparse.ArgumentParser(parents=[parent_parser])
347 >>> bar_parser.add_argument('--bar')
348 >>> bar_parser.parse_args(['--bar', 'YYY'])
349 Namespace(bar='YYY', parent=None)
350
351Note that most parent parsers will specify ``add_help=False``. Otherwise, the
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000352:class:`ArgumentParser` will see two ``-h/--help`` options (one in the parent
353and one in the child) and raise an error.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000354
Steven Bethardd186f992011-03-26 21:49:00 +0100355.. note::
356 You must fully initialize the parsers before passing them via ``parents=``.
357 If you change the parent parsers after the child parser, those changes will
358 not be reflected in the child.
359
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000360
361formatter_class
362^^^^^^^^^^^^^^^
363
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000364:class:`ArgumentParser` objects allow the help formatting to be customized by
365specifying an alternate formatting class. Currently, there are three such
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300366classes:
367
368.. class:: RawDescriptionHelpFormatter
369 RawTextHelpFormatter
370 ArgumentDefaultsHelpFormatter
371
372The first two allow more control over how textual descriptions are displayed,
373while the last automatically adds information about argument default values.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000374
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000375By default, :class:`ArgumentParser` objects line-wrap the description_ and
376epilog_ texts in command-line help messages::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000377
378 >>> parser = argparse.ArgumentParser(
379 ... prog='PROG',
380 ... description='''this description
381 ... was indented weird
382 ... but that is okay''',
383 ... epilog='''
384 ... likewise for this epilog whose whitespace will
385 ... be cleaned up and whose words will be wrapped
386 ... across a couple lines''')
387 >>> parser.print_help()
388 usage: PROG [-h]
389
390 this description was indented weird but that is okay
391
392 optional arguments:
393 -h, --help show this help message and exit
394
395 likewise for this epilog whose whitespace will be cleaned up and whose words
396 will be wrapped across a couple lines
397
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300398Passing :class:`~argparse.RawDescriptionHelpFormatter` as ``formatter_class=``
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000399indicates that description_ and epilog_ are already correctly formatted and
400should not be line-wrapped::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000401
402 >>> parser = argparse.ArgumentParser(
403 ... prog='PROG',
404 ... formatter_class=argparse.RawDescriptionHelpFormatter,
405 ... description=textwrap.dedent('''\
406 ... Please do not mess up this text!
407 ... --------------------------------
408 ... I have indented it
409 ... exactly the way
410 ... I want it
411 ... '''))
412 >>> parser.print_help()
413 usage: PROG [-h]
414
415 Please do not mess up this text!
416 --------------------------------
417 I have indented it
418 exactly the way
419 I want it
420
421 optional arguments:
422 -h, --help show this help message and exit
423
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000424:class:`RawTextHelpFormatter` maintains whitespace for all sorts of help text
425including argument descriptions.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000426
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000427The other formatter class available, :class:`ArgumentDefaultsHelpFormatter`,
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000428will add information about the default value of each of the arguments::
429
430 >>> parser = argparse.ArgumentParser(
431 ... prog='PROG',
432 ... formatter_class=argparse.ArgumentDefaultsHelpFormatter)
433 >>> parser.add_argument('--foo', type=int, default=42, help='FOO!')
434 >>> parser.add_argument('bar', nargs='*', default=[1, 2, 3], help='BAR!')
435 >>> parser.print_help()
436 usage: PROG [-h] [--foo FOO] [bar [bar ...]]
437
438 positional arguments:
439 bar BAR! (default: [1, 2, 3])
440
441 optional arguments:
442 -h, --help show this help message and exit
443 --foo FOO FOO! (default: 42)
444
445
446conflict_handler
447^^^^^^^^^^^^^^^^
448
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000449:class:`ArgumentParser` objects do not allow two actions with the same option
450string. By default, :class:`ArgumentParser` objects raises an exception if an
451attempt is made to create an argument with an option string that is already in
452use::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000453
454 >>> parser = argparse.ArgumentParser(prog='PROG')
455 >>> parser.add_argument('-f', '--foo', help='old foo help')
456 >>> parser.add_argument('--foo', help='new foo help')
457 Traceback (most recent call last):
458 ..
459 ArgumentError: argument --foo: conflicting option string(s): --foo
460
461Sometimes (e.g. when using parents_) it may be useful to simply override any
462older arguments with the same option string. To get this behavior, the value
463``'resolve'`` can be supplied to the ``conflict_handler=`` argument of
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000464:class:`ArgumentParser`::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000465
466 >>> parser = argparse.ArgumentParser(prog='PROG', conflict_handler='resolve')
467 >>> parser.add_argument('-f', '--foo', help='old foo help')
468 >>> parser.add_argument('--foo', help='new foo help')
469 >>> parser.print_help()
470 usage: PROG [-h] [-f FOO] [--foo FOO]
471
472 optional arguments:
473 -h, --help show this help message and exit
474 -f FOO old foo help
475 --foo FOO new foo help
476
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000477Note that :class:`ArgumentParser` objects only remove an action if all of its
478option strings are overridden. So, in the example above, the old ``-f/--foo``
479action is retained as the ``-f`` action, because only the ``--foo`` option
480string was overridden.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000481
482
483prog
484^^^^
485
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000486By default, :class:`ArgumentParser` objects uses ``sys.argv[0]`` to determine
487how to display the name of the program in help messages. This default is almost
Ezio Melottif82340d2010-05-27 22:38:16 +0000488always desirable because it will make the help messages match how the program was
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000489invoked on the command line. For example, consider a file named
490``myprogram.py`` with the following code::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000491
492 import argparse
493 parser = argparse.ArgumentParser()
494 parser.add_argument('--foo', help='foo help')
495 args = parser.parse_args()
496
497The help for this program will display ``myprogram.py`` as the program name
498(regardless of where the program was invoked from)::
499
500 $ python myprogram.py --help
501 usage: myprogram.py [-h] [--foo FOO]
502
503 optional arguments:
504 -h, --help show this help message and exit
505 --foo FOO foo help
506 $ cd ..
507 $ python subdir\myprogram.py --help
508 usage: myprogram.py [-h] [--foo FOO]
509
510 optional arguments:
511 -h, --help show this help message and exit
512 --foo FOO foo help
513
514To change this default behavior, another value can be supplied using the
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000515``prog=`` argument to :class:`ArgumentParser`::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000516
517 >>> parser = argparse.ArgumentParser(prog='myprogram')
518 >>> parser.print_help()
519 usage: myprogram [-h]
520
521 optional arguments:
522 -h, --help show this help message and exit
523
524Note that the program name, whether determined from ``sys.argv[0]`` or from the
525``prog=`` argument, is available to help messages using the ``%(prog)s`` format
526specifier.
527
528::
529
530 >>> parser = argparse.ArgumentParser(prog='myprogram')
531 >>> parser.add_argument('--foo', help='foo of the %(prog)s program')
532 >>> parser.print_help()
533 usage: myprogram [-h] [--foo FOO]
534
535 optional arguments:
536 -h, --help show this help message and exit
537 --foo FOO foo of the myprogram program
538
539
540usage
541^^^^^
542
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000543By default, :class:`ArgumentParser` calculates the usage message from the
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000544arguments it contains::
545
546 >>> parser = argparse.ArgumentParser(prog='PROG')
547 >>> parser.add_argument('--foo', nargs='?', help='foo help')
548 >>> parser.add_argument('bar', nargs='+', help='bar help')
549 >>> parser.print_help()
550 usage: PROG [-h] [--foo [FOO]] bar [bar ...]
551
552 positional arguments:
553 bar bar help
554
555 optional arguments:
556 -h, --help show this help message and exit
557 --foo [FOO] foo help
558
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000559The default message can be overridden with the ``usage=`` keyword argument::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000560
561 >>> parser = argparse.ArgumentParser(prog='PROG', usage='%(prog)s [options]')
562 >>> parser.add_argument('--foo', nargs='?', help='foo help')
563 >>> parser.add_argument('bar', nargs='+', help='bar help')
564 >>> parser.print_help()
565 usage: PROG [options]
566
567 positional arguments:
568 bar bar help
569
570 optional arguments:
571 -h, --help show this help message and exit
572 --foo [FOO] foo help
573
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000574The ``%(prog)s`` format specifier is available to fill in the program name in
575your usage messages.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000576
577
578The add_argument() method
579-------------------------
580
Georg Brandlc9007082011-01-09 09:04:08 +0000581.. method:: ArgumentParser.add_argument(name or flags..., [action], [nargs], \
582 [const], [default], [type], [choices], [required], \
583 [help], [metavar], [dest])
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000584
Georg Brandl1d827ff2011-04-16 16:44:54 +0200585 Define how a single command-line argument should be parsed. Each parameter
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000586 has its own more detailed description below, but in short they are:
587
588 * `name or flags`_ - Either a name or a list of option strings, e.g. ``foo``
Ezio Melottidca309d2011-04-21 23:09:27 +0300589 or ``-f, --foo``.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000590
591 * action_ - The basic type of action to be taken when this argument is
Georg Brandl1d827ff2011-04-16 16:44:54 +0200592 encountered at the command line.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000593
594 * nargs_ - The number of command-line arguments that should be consumed.
595
596 * const_ - A constant value required by some action_ and nargs_ selections.
597
598 * default_ - The value produced if the argument is absent from the
Georg Brandl1d827ff2011-04-16 16:44:54 +0200599 command line.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000600
Ezio Melotti2409d772011-04-16 23:13:50 +0300601 * type_ - The type to which the command-line argument should be converted.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000602
603 * choices_ - A container of the allowable values for the argument.
604
605 * required_ - Whether or not the command-line option may be omitted
606 (optionals only).
607
608 * help_ - A brief description of what the argument does.
609
610 * metavar_ - A name for the argument in usage messages.
611
612 * dest_ - The name of the attribute to be added to the object returned by
613 :meth:`parse_args`.
614
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000615The following sections describe how each of these are used.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000616
Georg Brandle0bf91d2010-10-17 10:34:28 +0000617
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000618name or flags
619^^^^^^^^^^^^^
620
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300621The :meth:`~ArgumentParser.add_argument` method must know whether an optional
622argument, like ``-f`` or ``--foo``, or a positional argument, like a list of
623filenames, is expected. The first arguments passed to
624:meth:`~ArgumentParser.add_argument` must therefore be either a series of
625flags, or a simple argument name. For example, an optional argument could
626be created like::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000627
628 >>> parser.add_argument('-f', '--foo')
629
630while a positional argument could be created like::
631
632 >>> parser.add_argument('bar')
633
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300634When :meth:`~ArgumentParser.parse_args` is called, optional arguments will be
635identified by the ``-`` prefix, and the remaining arguments will be assumed to
636be positional::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000637
638 >>> parser = argparse.ArgumentParser(prog='PROG')
639 >>> parser.add_argument('-f', '--foo')
640 >>> parser.add_argument('bar')
641 >>> parser.parse_args(['BAR'])
642 Namespace(bar='BAR', foo=None)
643 >>> parser.parse_args(['BAR', '--foo', 'FOO'])
644 Namespace(bar='BAR', foo='FOO')
645 >>> parser.parse_args(['--foo', 'FOO'])
646 usage: PROG [-h] [-f FOO] bar
647 PROG: error: too few arguments
648
Georg Brandle0bf91d2010-10-17 10:34:28 +0000649
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000650action
651^^^^^^
652
653:class:`ArgumentParser` objects associate command-line args with actions. These
654actions can do just about anything with the command-line args associated with
655them, though most actions simply add an attribute to the object returned by
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300656:meth:`~ArgumentParser.parse_args`. The ``action`` keyword argument specifies
657how the command-line args should be handled. The supported actions are:
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000658
659* ``'store'`` - This just stores the argument's value. This is the default
Ezio Melotti2f1db7d2011-04-21 23:06:48 +0300660 action. For example::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000661
662 >>> parser = argparse.ArgumentParser()
663 >>> parser.add_argument('--foo')
664 >>> parser.parse_args('--foo 1'.split())
665 Namespace(foo='1')
666
667* ``'store_const'`` - This stores the value specified by the const_ keyword
Ezio Melotti2f1db7d2011-04-21 23:06:48 +0300668 argument. (Note that the const_ keyword argument defaults to the rather
669 unhelpful ``None``.) The ``'store_const'`` action is most commonly used with
670 optional arguments that specify some sort of flag. For example::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000671
672 >>> parser = argparse.ArgumentParser()
673 >>> parser.add_argument('--foo', action='store_const', const=42)
674 >>> parser.parse_args('--foo'.split())
675 Namespace(foo=42)
676
677* ``'store_true'`` and ``'store_false'`` - These store the values ``True`` and
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000678 ``False`` respectively. These are special cases of ``'store_const'``. For
679 example::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000680
681 >>> parser = argparse.ArgumentParser()
682 >>> parser.add_argument('--foo', action='store_true')
683 >>> parser.add_argument('--bar', action='store_false')
684 >>> parser.parse_args('--foo --bar'.split())
685 Namespace(bar=False, foo=True)
686
687* ``'append'`` - This stores a list, and appends each argument value to the
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000688 list. This is useful to allow an option to be specified multiple times.
689 Example usage::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000690
691 >>> parser = argparse.ArgumentParser()
692 >>> parser.add_argument('--foo', action='append')
693 >>> parser.parse_args('--foo 1 --foo 2'.split())
694 Namespace(foo=['1', '2'])
695
696* ``'append_const'`` - This stores a list, and appends the value specified by
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000697 the const_ keyword argument to the list. (Note that the const_ keyword
698 argument defaults to ``None``.) The ``'append_const'`` action is typically
699 useful when multiple arguments need to store constants to the same list. For
700 example::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000701
702 >>> parser = argparse.ArgumentParser()
703 >>> parser.add_argument('--str', dest='types', action='append_const', const=str)
704 >>> parser.add_argument('--int', dest='types', action='append_const', const=int)
705 >>> parser.parse_args('--str --int'.split())
706 Namespace(types=[<type 'str'>, <type 'int'>])
707
708* ``'version'`` - This expects a ``version=`` keyword argument in the
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300709 :meth:`~ArgumentParser.add_argument` call, and prints version information
710 and exits when invoked.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000711
712 >>> import argparse
713 >>> parser = argparse.ArgumentParser(prog='PROG')
Steven Bethard59710962010-05-24 03:21:08 +0000714 >>> parser.add_argument('--version', action='version', version='%(prog)s 2.0')
715 >>> parser.parse_args(['--version'])
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000716 PROG 2.0
717
718You can also specify an arbitrary action by passing an object that implements
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000719the Action API. The easiest way to do this is to extend
720:class:`argparse.Action`, supplying an appropriate ``__call__`` method. The
721``__call__`` method should accept four parameters:
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000722
723* ``parser`` - The ArgumentParser object which contains this action.
724
725* ``namespace`` - The namespace object that will be returned by
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300726 :meth:`~ArgumentParser.parse_args`. Most actions add an attribute to this
727 object.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000728
729* ``values`` - The associated command-line args, with any type-conversions
730 applied. (Type-conversions are specified with the type_ keyword argument to
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300731 :meth:`~ArgumentParser.add_argument`.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000732
733* ``option_string`` - The option string that was used to invoke this action.
734 The ``option_string`` argument is optional, and will be absent if the action
735 is associated with a positional argument.
736
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000737An example of a custom action::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000738
739 >>> class FooAction(argparse.Action):
740 ... def __call__(self, parser, namespace, values, option_string=None):
Georg Brandl571a9532010-07-26 17:00:20 +0000741 ... print('%r %r %r' % (namespace, values, option_string))
742 ... setattr(namespace, self.dest, values)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000743 ...
744 >>> parser = argparse.ArgumentParser()
745 >>> parser.add_argument('--foo', action=FooAction)
746 >>> parser.add_argument('bar', action=FooAction)
747 >>> args = parser.parse_args('1 --foo 2'.split())
748 Namespace(bar=None, foo=None) '1' None
749 Namespace(bar='1', foo=None) '2' '--foo'
750 >>> args
751 Namespace(bar='1', foo='2')
752
753
754nargs
755^^^^^
756
757ArgumentParser objects usually associate a single command-line argument with a
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000758single action to be taken. The ``nargs`` keyword argument associates a
Ezio Melotti00f53af2011-04-21 22:56:51 +0300759different number of command-line arguments with a single action. The supported
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000760values are:
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000761
Georg Brandl1d827ff2011-04-16 16:44:54 +0200762* N (an integer). N args from the command line will be gathered together into a
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000763 list. For example::
764
Georg Brandl682d7e02010-10-06 10:26:05 +0000765 >>> parser = argparse.ArgumentParser()
766 >>> parser.add_argument('--foo', nargs=2)
767 >>> parser.add_argument('bar', nargs=1)
768 >>> parser.parse_args('c --foo a b'.split())
769 Namespace(bar=['c'], foo=['a', 'b'])
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000770
Georg Brandl682d7e02010-10-06 10:26:05 +0000771 Note that ``nargs=1`` produces a list of one item. This is different from
772 the default, in which the item is produced by itself.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000773
Georg Brandl1d827ff2011-04-16 16:44:54 +0200774* ``'?'``. One arg will be consumed from the command line if possible, and
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000775 produced as a single item. If no command-line arg is present, the value from
776 default_ will be produced. Note that for optional arguments, there is an
777 additional case - the option string is present but not followed by a
778 command-line arg. In this case the value from const_ will be produced. Some
779 examples to illustrate this::
780
781 >>> parser = argparse.ArgumentParser()
782 >>> parser.add_argument('--foo', nargs='?', const='c', default='d')
783 >>> parser.add_argument('bar', nargs='?', default='d')
784 >>> parser.parse_args('XX --foo YY'.split())
785 Namespace(bar='XX', foo='YY')
786 >>> parser.parse_args('XX --foo'.split())
787 Namespace(bar='XX', foo='c')
788 >>> parser.parse_args(''.split())
789 Namespace(bar='d', foo='d')
790
791 One of the more common uses of ``nargs='?'`` is to allow optional input and
792 output files::
793
794 >>> parser = argparse.ArgumentParser()
Georg Brandle0bf91d2010-10-17 10:34:28 +0000795 >>> parser.add_argument('infile', nargs='?', type=argparse.FileType('r'),
796 ... default=sys.stdin)
797 >>> parser.add_argument('outfile', nargs='?', type=argparse.FileType('w'),
798 ... default=sys.stdout)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000799 >>> parser.parse_args(['input.txt', 'output.txt'])
Georg Brandl04536b02011-01-09 09:31:01 +0000800 Namespace(infile=<_io.TextIOWrapper name='input.txt' encoding='UTF-8'>,
801 outfile=<_io.TextIOWrapper name='output.txt' encoding='UTF-8'>)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000802 >>> parser.parse_args([])
Georg Brandl04536b02011-01-09 09:31:01 +0000803 Namespace(infile=<_io.TextIOWrapper name='<stdin>' encoding='UTF-8'>,
804 outfile=<_io.TextIOWrapper name='<stdout>' encoding='UTF-8'>)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000805
806* ``'*'``. All command-line args present are gathered into a list. Note that
807 it generally doesn't make much sense to have more than one positional argument
808 with ``nargs='*'``, but multiple optional arguments with ``nargs='*'`` is
809 possible. For example::
810
811 >>> parser = argparse.ArgumentParser()
812 >>> parser.add_argument('--foo', nargs='*')
813 >>> parser.add_argument('--bar', nargs='*')
814 >>> parser.add_argument('baz', nargs='*')
815 >>> parser.parse_args('a b --foo x y --bar 1 2'.split())
816 Namespace(bar=['1', '2'], baz=['a', 'b'], foo=['x', 'y'])
817
818* ``'+'``. Just like ``'*'``, all command-line args present are gathered into a
819 list. Additionally, an error message will be generated if there wasn't at
820 least one command-line arg present. For example::
821
822 >>> parser = argparse.ArgumentParser(prog='PROG')
823 >>> parser.add_argument('foo', nargs='+')
824 >>> parser.parse_args('a b'.split())
825 Namespace(foo=['a', 'b'])
826 >>> parser.parse_args(''.split())
827 usage: PROG [-h] foo [foo ...]
828 PROG: error: too few arguments
829
830If the ``nargs`` keyword argument is not provided, the number of args consumed
831is determined by the action_. Generally this means a single command-line arg
832will be consumed and a single item (not a list) will be produced.
833
834
835const
836^^^^^
837
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300838The ``const`` argument of :meth:`~ArgumentParser.add_argument` is used to hold
839constant values that are not read from the command line but are required for
840the various :class:`ArgumentParser` actions. The two most common uses of it are:
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000841
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300842* When :meth:`~ArgumentParser.add_argument` is called with
843 ``action='store_const'`` or ``action='append_const'``. These actions add the
844 ``const`` value to one of the attributes of the object returned by :meth:`~ArgumentParser.parse_args`. See the action_ description for examples.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000845
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300846* When :meth:`~ArgumentParser.add_argument` is called with option strings
847 (like ``-f`` or ``--foo``) and ``nargs='?'``. This creates an optional
848 argument that can be followed by zero or one command-line args.
849 When parsing the command line, if the option string is encountered with no
850 command-line arg following it, the value of ``const`` will be assumed instead.
851 See the nargs_ description for examples.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000852
853The ``const`` keyword argument defaults to ``None``.
854
855
856default
857^^^^^^^
858
859All optional arguments and some positional arguments may be omitted at the
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300860command line. The ``default`` keyword argument of
861:meth:`~ArgumentParser.add_argument`, whose value defaults to ``None``,
862specifies what value should be used if the command-line arg is not present.
863For optional arguments, the ``default`` value is used when the option string
864was not present at the command line::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000865
866 >>> parser = argparse.ArgumentParser()
867 >>> parser.add_argument('--foo', default=42)
868 >>> parser.parse_args('--foo 2'.split())
869 Namespace(foo='2')
870 >>> parser.parse_args(''.split())
871 Namespace(foo=42)
872
873For positional arguments with nargs_ ``='?'`` or ``'*'``, the ``default`` value
874is used when no command-line arg was present::
875
876 >>> parser = argparse.ArgumentParser()
877 >>> parser.add_argument('foo', nargs='?', default=42)
878 >>> parser.parse_args('a'.split())
879 Namespace(foo='a')
880 >>> parser.parse_args(''.split())
881 Namespace(foo=42)
882
883
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000884Providing ``default=argparse.SUPPRESS`` causes no attribute to be added if the
885command-line argument was not present.::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000886
887 >>> parser = argparse.ArgumentParser()
888 >>> parser.add_argument('--foo', default=argparse.SUPPRESS)
889 >>> parser.parse_args([])
890 Namespace()
891 >>> parser.parse_args(['--foo', '1'])
892 Namespace(foo='1')
893
894
895type
896^^^^
897
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300898By default, :class:`ArgumentParser` objects read command-line args in as simple
899strings. However, quite often the command-line string should instead be
900interpreted as another type, like a :class:`float` or :class:`int`. The
901``type`` keyword argument of :meth:`~ArgumentParser.add_argument` allows any
902necessary type-checking and type-conversions to be performed. Common built-in
903types and functions can be used directly as the value of the ``type`` argument::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000904
905 >>> parser = argparse.ArgumentParser()
906 >>> parser.add_argument('foo', type=int)
Georg Brandl04536b02011-01-09 09:31:01 +0000907 >>> parser.add_argument('bar', type=open)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000908 >>> parser.parse_args('2 temp.txt'.split())
Georg Brandl04536b02011-01-09 09:31:01 +0000909 Namespace(bar=<_io.TextIOWrapper name='temp.txt' encoding='UTF-8'>, foo=2)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000910
911To ease the use of various types of files, the argparse module provides the
912factory FileType which takes the ``mode=`` and ``bufsize=`` arguments of the
Georg Brandl04536b02011-01-09 09:31:01 +0000913:func:`open` function. For example, ``FileType('w')`` can be used to create a
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000914writable file::
915
916 >>> parser = argparse.ArgumentParser()
917 >>> parser.add_argument('bar', type=argparse.FileType('w'))
918 >>> parser.parse_args(['out.txt'])
Georg Brandl04536b02011-01-09 09:31:01 +0000919 Namespace(bar=<_io.TextIOWrapper name='out.txt' encoding='UTF-8'>)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000920
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000921``type=`` can take any callable that takes a single string argument and returns
922the type-converted value::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000923
924 >>> def perfect_square(string):
925 ... value = int(string)
926 ... sqrt = math.sqrt(value)
927 ... if sqrt != int(sqrt):
928 ... msg = "%r is not a perfect square" % string
929 ... raise argparse.ArgumentTypeError(msg)
930 ... return value
931 ...
932 >>> parser = argparse.ArgumentParser(prog='PROG')
933 >>> parser.add_argument('foo', type=perfect_square)
934 >>> parser.parse_args('9'.split())
935 Namespace(foo=9)
936 >>> parser.parse_args('7'.split())
937 usage: PROG [-h] foo
938 PROG: error: argument foo: '7' is not a perfect square
939
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000940The choices_ keyword argument may be more convenient for type checkers that
941simply check against a range of values::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000942
943 >>> parser = argparse.ArgumentParser(prog='PROG')
Fred Drakec7eb7892011-03-03 05:29:59 +0000944 >>> parser.add_argument('foo', type=int, choices=range(5, 10))
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000945 >>> parser.parse_args('7'.split())
946 Namespace(foo=7)
947 >>> parser.parse_args('11'.split())
948 usage: PROG [-h] {5,6,7,8,9}
949 PROG: error: argument foo: invalid choice: 11 (choose from 5, 6, 7, 8, 9)
950
951See the choices_ section for more details.
952
953
954choices
955^^^^^^^
956
957Some command-line args should be selected from a restricted set of values.
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000958These can be handled by passing a container object as the ``choices`` keyword
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300959argument to :meth:`~ArgumentParser.add_argument`. When the command line is
960parsed, arg values will be checked, and an error message will be displayed if
961the arg was not one of the acceptable values::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000962
963 >>> parser = argparse.ArgumentParser(prog='PROG')
964 >>> parser.add_argument('foo', choices='abc')
965 >>> parser.parse_args('c'.split())
966 Namespace(foo='c')
967 >>> parser.parse_args('X'.split())
968 usage: PROG [-h] {a,b,c}
969 PROG: error: argument foo: invalid choice: 'X' (choose from 'a', 'b', 'c')
970
971Note that inclusion in the ``choices`` container is checked after any type_
972conversions have been performed, so the type of the objects in the ``choices``
973container should match the type_ specified::
974
975 >>> parser = argparse.ArgumentParser(prog='PROG')
976 >>> parser.add_argument('foo', type=complex, choices=[1, 1j])
977 >>> parser.parse_args('1j'.split())
978 Namespace(foo=1j)
979 >>> parser.parse_args('-- -4'.split())
980 usage: PROG [-h] {1,1j}
981 PROG: error: argument foo: invalid choice: (-4+0j) (choose from 1, 1j)
982
983Any object that supports the ``in`` operator can be passed as the ``choices``
984value, so :class:`dict` objects, :class:`set` objects, custom containers,
985etc. are all supported.
986
987
988required
989^^^^^^^^
990
Ezio Melotti0ee9c1b2011-04-21 16:12:17 +0300991In general, the :mod:`argparse` module assumes that flags like ``-f`` and ``--bar``
Georg Brandl1d827ff2011-04-16 16:44:54 +0200992indicate *optional* arguments, which can always be omitted at the command line.
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000993To make an option *required*, ``True`` can be specified for the ``required=``
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300994keyword argument to :meth:`~ArgumentParser.add_argument`::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000995
996 >>> parser = argparse.ArgumentParser()
997 >>> parser.add_argument('--foo', required=True)
998 >>> parser.parse_args(['--foo', 'BAR'])
999 Namespace(foo='BAR')
1000 >>> parser.parse_args([])
1001 usage: argparse.py [-h] [--foo FOO]
1002 argparse.py: error: option --foo is required
1003
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001004As the example shows, if an option is marked as ``required``,
1005:meth:`~ArgumentParser.parse_args` will report an error if that option is not
1006present at the command line.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001007
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001008.. note::
1009
1010 Required options are generally considered bad form because users expect
1011 *options* to be *optional*, and thus they should be avoided when possible.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001012
1013
1014help
1015^^^^
1016
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001017The ``help`` value is a string containing a brief description of the argument.
1018When a user requests help (usually by using ``-h`` or ``--help`` at the
Georg Brandl1d827ff2011-04-16 16:44:54 +02001019command line), these ``help`` descriptions will be displayed with each
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001020argument::
1021
1022 >>> parser = argparse.ArgumentParser(prog='frobble')
1023 >>> parser.add_argument('--foo', action='store_true',
1024 ... help='foo the bars before frobbling')
1025 >>> parser.add_argument('bar', nargs='+',
1026 ... help='one of the bars to be frobbled')
1027 >>> parser.parse_args('-h'.split())
1028 usage: frobble [-h] [--foo] bar [bar ...]
1029
1030 positional arguments:
1031 bar one of the bars to be frobbled
1032
1033 optional arguments:
1034 -h, --help show this help message and exit
1035 --foo foo the bars before frobbling
1036
1037The ``help`` strings can include various format specifiers to avoid repetition
1038of things like the program name or the argument default_. The available
1039specifiers include the program name, ``%(prog)s`` and most keyword arguments to
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001040:meth:`~ArgumentParser.add_argument`, e.g. ``%(default)s``, ``%(type)s``, etc.::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001041
1042 >>> parser = argparse.ArgumentParser(prog='frobble')
1043 >>> parser.add_argument('bar', nargs='?', type=int, default=42,
1044 ... help='the bar to %(prog)s (default: %(default)s)')
1045 >>> parser.print_help()
1046 usage: frobble [-h] [bar]
1047
1048 positional arguments:
1049 bar the bar to frobble (default: 42)
1050
1051 optional arguments:
1052 -h, --help show this help message and exit
1053
1054
1055metavar
1056^^^^^^^
1057
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001058When :class:`ArgumentParser` generates help messages, it need some way to refer
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001059to each expected argument. By default, ArgumentParser objects use the dest_
1060value as the "name" of each object. By default, for positional argument
1061actions, the dest_ value is used directly, and for optional argument actions,
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001062the dest_ value is uppercased. So, a single positional argument with
1063``dest='bar'`` will that argument will be referred to as ``bar``. A single
1064optional argument ``--foo`` that should be followed by a single command-line arg
1065will be referred to as ``FOO``. An example::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001066
1067 >>> parser = argparse.ArgumentParser()
1068 >>> parser.add_argument('--foo')
1069 >>> parser.add_argument('bar')
1070 >>> parser.parse_args('X --foo Y'.split())
1071 Namespace(bar='X', foo='Y')
1072 >>> parser.print_help()
1073 usage: [-h] [--foo FOO] bar
1074
1075 positional arguments:
1076 bar
1077
1078 optional arguments:
1079 -h, --help show this help message and exit
1080 --foo FOO
1081
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001082An alternative name can be specified with ``metavar``::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001083
1084 >>> parser = argparse.ArgumentParser()
1085 >>> parser.add_argument('--foo', metavar='YYY')
1086 >>> parser.add_argument('bar', metavar='XXX')
1087 >>> parser.parse_args('X --foo Y'.split())
1088 Namespace(bar='X', foo='Y')
1089 >>> parser.print_help()
1090 usage: [-h] [--foo YYY] XXX
1091
1092 positional arguments:
1093 XXX
1094
1095 optional arguments:
1096 -h, --help show this help message and exit
1097 --foo YYY
1098
1099Note that ``metavar`` only changes the *displayed* name - the name of the
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001100attribute on the :meth:`~ArgumentParser.parse_args` object is still determined
1101by the dest_ value.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001102
1103Different values of ``nargs`` may cause the metavar to be used multiple times.
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001104Providing a tuple to ``metavar`` specifies a different display for each of the
1105arguments::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001106
1107 >>> parser = argparse.ArgumentParser(prog='PROG')
1108 >>> parser.add_argument('-x', nargs=2)
1109 >>> parser.add_argument('--foo', nargs=2, metavar=('bar', 'baz'))
1110 >>> parser.print_help()
1111 usage: PROG [-h] [-x X X] [--foo bar baz]
1112
1113 optional arguments:
1114 -h, --help show this help message and exit
1115 -x X X
1116 --foo bar baz
1117
1118
1119dest
1120^^^^
1121
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001122Most :class:`ArgumentParser` actions add some value as an attribute of the
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001123object returned by :meth:`~ArgumentParser.parse_args`. The name of this
1124attribute is determined by the ``dest`` keyword argument of
1125:meth:`~ArgumentParser.add_argument`. For positional argument actions,
1126``dest`` is normally supplied as the first argument to
1127:meth:`~ArgumentParser.add_argument`::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001128
1129 >>> parser = argparse.ArgumentParser()
1130 >>> parser.add_argument('bar')
1131 >>> parser.parse_args('XXX'.split())
1132 Namespace(bar='XXX')
1133
1134For optional argument actions, the value of ``dest`` is normally inferred from
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001135the option strings. :class:`ArgumentParser` generates the value of ``dest`` by
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001136taking the first long option string and stripping away the initial ``'--'``
1137string. If no long option strings were supplied, ``dest`` will be derived from
1138the first short option string by stripping the initial ``'-'`` character. Any
1139internal ``'-'`` characters will be converted to ``'_'`` characters to make sure
1140the string is a valid attribute name. The examples below illustrate this
1141behavior::
1142
1143 >>> parser = argparse.ArgumentParser()
1144 >>> parser.add_argument('-f', '--foo-bar', '--foo')
1145 >>> parser.add_argument('-x', '-y')
1146 >>> parser.parse_args('-f 1 -x 2'.split())
1147 Namespace(foo_bar='1', x='2')
1148 >>> parser.parse_args('--foo 1 -y 2'.split())
1149 Namespace(foo_bar='1', x='2')
1150
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001151``dest`` allows a custom attribute name to be provided::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001152
1153 >>> parser = argparse.ArgumentParser()
1154 >>> parser.add_argument('--foo', dest='bar')
1155 >>> parser.parse_args('--foo XXX'.split())
1156 Namespace(bar='XXX')
1157
1158
1159The parse_args() method
1160-----------------------
1161
Georg Brandle0bf91d2010-10-17 10:34:28 +00001162.. method:: ArgumentParser.parse_args(args=None, namespace=None)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001163
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001164 Convert argument strings to objects and assign them as attributes of the
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001165 namespace. Return the populated namespace.
1166
1167 Previous calls to :meth:`add_argument` determine exactly what objects are
1168 created and how they are assigned. See the documentation for
1169 :meth:`add_argument` for details.
1170
1171 By default, the arg strings are taken from :data:`sys.argv`, and a new empty
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001172 :class:`Namespace` object is created for the attributes.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001173
Georg Brandle0bf91d2010-10-17 10:34:28 +00001174
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001175Option value syntax
1176^^^^^^^^^^^^^^^^^^^
1177
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001178The :meth:`~ArgumentParser.parse_args` method supports several ways of
1179specifying the value of an option (if it takes one). In the simplest case, the
1180option and its value are passed as two separate arguments::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001181
1182 >>> parser = argparse.ArgumentParser(prog='PROG')
1183 >>> parser.add_argument('-x')
1184 >>> parser.add_argument('--foo')
1185 >>> parser.parse_args('-x X'.split())
1186 Namespace(foo=None, x='X')
1187 >>> parser.parse_args('--foo FOO'.split())
1188 Namespace(foo='FOO', x=None)
1189
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001190For long options (options with names longer than a single character), the option
Georg Brandl1d827ff2011-04-16 16:44:54 +02001191and value can also be passed as a single command-line argument, using ``=`` to
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001192separate them::
1193
1194 >>> parser.parse_args('--foo=FOO'.split())
1195 Namespace(foo='FOO', x=None)
1196
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001197For short options (options only one character long), the option and its value
1198can be concatenated::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001199
1200 >>> parser.parse_args('-xX'.split())
1201 Namespace(foo=None, x='X')
1202
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001203Several short options can be joined together, using only a single ``-`` prefix,
1204as long as only the last option (or none of them) requires a value::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001205
1206 >>> parser = argparse.ArgumentParser(prog='PROG')
1207 >>> parser.add_argument('-x', action='store_true')
1208 >>> parser.add_argument('-y', action='store_true')
1209 >>> parser.add_argument('-z')
1210 >>> parser.parse_args('-xyzZ'.split())
1211 Namespace(x=True, y=True, z='Z')
1212
1213
1214Invalid arguments
1215^^^^^^^^^^^^^^^^^
1216
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001217While parsing the command line, :meth:`~ArgumentParser.parse_args` checks for a
1218variety of errors, including ambiguous options, invalid types, invalid options,
1219wrong number of positional arguments, etc. When it encounters such an error,
1220it exits and prints the error along with a usage message::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001221
1222 >>> parser = argparse.ArgumentParser(prog='PROG')
1223 >>> parser.add_argument('--foo', type=int)
1224 >>> parser.add_argument('bar', nargs='?')
1225
1226 >>> # invalid type
1227 >>> parser.parse_args(['--foo', 'spam'])
1228 usage: PROG [-h] [--foo FOO] [bar]
1229 PROG: error: argument --foo: invalid int value: 'spam'
1230
1231 >>> # invalid option
1232 >>> parser.parse_args(['--bar'])
1233 usage: PROG [-h] [--foo FOO] [bar]
1234 PROG: error: no such option: --bar
1235
1236 >>> # wrong number of arguments
1237 >>> parser.parse_args(['spam', 'badger'])
1238 usage: PROG [-h] [--foo FOO] [bar]
1239 PROG: error: extra arguments found: badger
1240
1241
1242Arguments containing ``"-"``
1243^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1244
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001245The :meth:`~ArgumentParser.parse_args` method attempts to give errors whenever
1246the user has clearly made a mistake, but some situations are inherently
1247ambiguous. For example, the command-line arg ``'-1'`` could either be an
1248attempt to specify an option or an attempt to provide a positional argument.
1249The :meth:`~ArgumentParser.parse_args` method is cautious here: positional
1250arguments may only begin with ``'-'`` if they look like negative numbers and
1251there are no options in the parser that look like negative numbers::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001252
1253 >>> parser = argparse.ArgumentParser(prog='PROG')
1254 >>> parser.add_argument('-x')
1255 >>> parser.add_argument('foo', nargs='?')
1256
1257 >>> # no negative number options, so -1 is a positional argument
1258 >>> parser.parse_args(['-x', '-1'])
1259 Namespace(foo=None, x='-1')
1260
1261 >>> # no negative number options, so -1 and -5 are positional arguments
1262 >>> parser.parse_args(['-x', '-1', '-5'])
1263 Namespace(foo='-5', x='-1')
1264
1265 >>> parser = argparse.ArgumentParser(prog='PROG')
1266 >>> parser.add_argument('-1', dest='one')
1267 >>> parser.add_argument('foo', nargs='?')
1268
1269 >>> # negative number options present, so -1 is an option
1270 >>> parser.parse_args(['-1', 'X'])
1271 Namespace(foo=None, one='X')
1272
1273 >>> # negative number options present, so -2 is an option
1274 >>> parser.parse_args(['-2'])
1275 usage: PROG [-h] [-1 ONE] [foo]
1276 PROG: error: no such option: -2
1277
1278 >>> # negative number options present, so both -1s are options
1279 >>> parser.parse_args(['-1', '-1'])
1280 usage: PROG [-h] [-1 ONE] [foo]
1281 PROG: error: argument -1: expected one argument
1282
1283If you have positional arguments that must begin with ``'-'`` and don't look
1284like negative numbers, you can insert the pseudo-argument ``'--'`` which tells
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001285:meth:`~ArgumentParser.parse_args` that everything after that is a positional
1286argument::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001287
1288 >>> parser.parse_args(['--', '-f'])
1289 Namespace(foo='-f', one=None)
1290
1291
1292Argument abbreviations
1293^^^^^^^^^^^^^^^^^^^^^^
1294
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001295The :meth:`~ArgumentParser.parse_args` method allows long options to be
1296abbreviated if the abbreviation is unambiguous::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001297
1298 >>> parser = argparse.ArgumentParser(prog='PROG')
1299 >>> parser.add_argument('-bacon')
1300 >>> parser.add_argument('-badger')
1301 >>> parser.parse_args('-bac MMM'.split())
1302 Namespace(bacon='MMM', badger=None)
1303 >>> parser.parse_args('-bad WOOD'.split())
1304 Namespace(bacon=None, badger='WOOD')
1305 >>> parser.parse_args('-ba BA'.split())
1306 usage: PROG [-h] [-bacon BACON] [-badger BADGER]
1307 PROG: error: ambiguous option: -ba could match -badger, -bacon
1308
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001309An error is produced for arguments that could produce more than one options.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001310
1311
1312Beyond ``sys.argv``
1313^^^^^^^^^^^^^^^^^^^
1314
1315Sometimes it may be useful to have an ArgumentParser parse args other than those
1316of :data:`sys.argv`. This can be accomplished by passing a list of strings to
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001317:meth:`~ArgumentParser.parse_args`. This is useful for testing at the
1318interactive prompt::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001319
1320 >>> parser = argparse.ArgumentParser()
1321 >>> parser.add_argument(
Fred Drakec7eb7892011-03-03 05:29:59 +00001322 ... 'integers', metavar='int', type=int, choices=range(10),
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001323 ... nargs='+', help='an integer in the range 0..9')
1324 >>> parser.add_argument(
1325 ... '--sum', dest='accumulate', action='store_const', const=sum,
1326 ... default=max, help='sum the integers (default: find the max)')
1327 >>> parser.parse_args(['1', '2', '3', '4'])
1328 Namespace(accumulate=<built-in function max>, integers=[1, 2, 3, 4])
1329 >>> parser.parse_args('1 2 3 4 --sum'.split())
1330 Namespace(accumulate=<built-in function sum>, integers=[1, 2, 3, 4])
1331
1332
Steven Bethardd8f2d502011-03-26 19:50:06 +01001333The Namespace object
1334^^^^^^^^^^^^^^^^^^^^
1335
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001336By default, :meth:`~ArgumentParser.parse_args` will return a new object of type
1337:class:`Namespace` where the necessary attributes have been set. This class is
1338deliberately simple, just an :class:`object` subclass with a readable string
1339representation. If you prefer to have dict-like view of the attributes, you
1340can use the standard Python idiom via :func:`vars`::
Steven Bethardd8f2d502011-03-26 19:50:06 +01001341
1342 >>> parser = argparse.ArgumentParser()
1343 >>> parser.add_argument('--foo')
1344 >>> args = parser.parse_args(['--foo', 'BAR'])
1345 >>> vars(args)
1346 {'foo': 'BAR'}
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001347
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001348It may also be useful to have an :class:`ArgumentParser` assign attributes to an
Steven Bethardd8f2d502011-03-26 19:50:06 +01001349already existing object, rather than a new :class:`Namespace` object. This can
1350be achieved by specifying the ``namespace=`` keyword argument::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001351
Éric Araujo28053fb2010-11-22 03:09:19 +00001352 >>> class C:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001353 ... pass
1354 ...
1355 >>> c = C()
1356 >>> parser = argparse.ArgumentParser()
1357 >>> parser.add_argument('--foo')
1358 >>> parser.parse_args(args=['--foo', 'BAR'], namespace=c)
1359 >>> c.foo
1360 'BAR'
1361
1362
1363Other utilities
1364---------------
1365
1366Sub-commands
1367^^^^^^^^^^^^
1368
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001369.. method:: ArgumentParser.add_subparsers()
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001370
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001371 Many programs split up their functionality into a number of sub-commands,
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001372 for example, the ``svn`` program can invoke sub-commands like ``svn
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001373 checkout``, ``svn update``, and ``svn commit``. Splitting up functionality
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001374 this way can be a particularly good idea when a program performs several
1375 different functions which require different kinds of command-line arguments.
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001376 :class:`ArgumentParser` supports the creation of such sub-commands with the
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001377 :meth:`add_subparsers` method. The :meth:`add_subparsers` method is normally
1378 called with no arguments and returns an special action object. This object
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001379 has a single method, :meth:`~ArgumentParser.add_parser`, which takes a
1380 command name and any :class:`ArgumentParser` constructor arguments, and
1381 returns an :class:`ArgumentParser` object that can be modified as usual.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001382
1383 Some example usage::
1384
1385 >>> # create the top-level parser
1386 >>> parser = argparse.ArgumentParser(prog='PROG')
1387 >>> parser.add_argument('--foo', action='store_true', help='foo help')
1388 >>> subparsers = parser.add_subparsers(help='sub-command help')
1389 >>>
1390 >>> # create the parser for the "a" command
1391 >>> parser_a = subparsers.add_parser('a', help='a help')
1392 >>> parser_a.add_argument('bar', type=int, help='bar help')
1393 >>>
1394 >>> # create the parser for the "b" command
1395 >>> parser_b = subparsers.add_parser('b', help='b help')
1396 >>> parser_b.add_argument('--baz', choices='XYZ', help='baz help')
1397 >>>
1398 >>> # parse some arg lists
1399 >>> parser.parse_args(['a', '12'])
1400 Namespace(bar=12, foo=False)
1401 >>> parser.parse_args(['--foo', 'b', '--baz', 'Z'])
1402 Namespace(baz='Z', foo=True)
1403
1404 Note that the object returned by :meth:`parse_args` will only contain
1405 attributes for the main parser and the subparser that was selected by the
1406 command line (and not any other subparsers). So in the example above, when
1407 the ``"a"`` command is specified, only the ``foo`` and ``bar`` attributes are
1408 present, and when the ``"b"`` command is specified, only the ``foo`` and
1409 ``baz`` attributes are present.
1410
1411 Similarly, when a help message is requested from a subparser, only the help
1412 for that particular parser will be printed. The help message will not
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001413 include parent parser or sibling parser messages. (A help message for each
1414 subparser command, however, can be given by supplying the ``help=`` argument
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001415 to :meth:`add_parser` as above.)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001416
1417 ::
1418
1419 >>> parser.parse_args(['--help'])
1420 usage: PROG [-h] [--foo] {a,b} ...
1421
1422 positional arguments:
1423 {a,b} sub-command help
1424 a a help
1425 b b help
1426
1427 optional arguments:
1428 -h, --help show this help message and exit
1429 --foo foo help
1430
1431 >>> parser.parse_args(['a', '--help'])
1432 usage: PROG a [-h] bar
1433
1434 positional arguments:
1435 bar bar help
1436
1437 optional arguments:
1438 -h, --help show this help message and exit
1439
1440 >>> parser.parse_args(['b', '--help'])
1441 usage: PROG b [-h] [--baz {X,Y,Z}]
1442
1443 optional arguments:
1444 -h, --help show this help message and exit
1445 --baz {X,Y,Z} baz help
1446
1447 The :meth:`add_subparsers` method also supports ``title`` and ``description``
1448 keyword arguments. When either is present, the subparser's commands will
1449 appear in their own group in the help output. For example::
1450
1451 >>> parser = argparse.ArgumentParser()
1452 >>> subparsers = parser.add_subparsers(title='subcommands',
1453 ... description='valid subcommands',
1454 ... help='additional help')
1455 >>> subparsers.add_parser('foo')
1456 >>> subparsers.add_parser('bar')
1457 >>> parser.parse_args(['-h'])
1458 usage: [-h] {foo,bar} ...
1459
1460 optional arguments:
1461 -h, --help show this help message and exit
1462
1463 subcommands:
1464 valid subcommands
1465
1466 {foo,bar} additional help
1467
Steven Bethardfd311a72010-12-18 11:19:23 +00001468 Furthermore, ``add_parser`` supports an additional ``aliases`` argument,
1469 which allows multiple strings to refer to the same subparser. This example,
1470 like ``svn``, aliases ``co`` as a shorthand for ``checkout``::
1471
1472 >>> parser = argparse.ArgumentParser()
1473 >>> subparsers = parser.add_subparsers()
1474 >>> checkout = subparsers.add_parser('checkout', aliases=['co'])
1475 >>> checkout.add_argument('foo')
1476 >>> parser.parse_args(['co', 'bar'])
1477 Namespace(foo='bar')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001478
1479 One particularly effective way of handling sub-commands is to combine the use
1480 of the :meth:`add_subparsers` method with calls to :meth:`set_defaults` so
1481 that each subparser knows which Python function it should execute. For
1482 example::
1483
1484 >>> # sub-command functions
1485 >>> def foo(args):
Benjamin Petersonb2deb112010-03-03 02:09:18 +00001486 ... print(args.x * args.y)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001487 ...
1488 >>> def bar(args):
Benjamin Petersonb2deb112010-03-03 02:09:18 +00001489 ... print('((%s))' % args.z)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001490 ...
1491 >>> # create the top-level parser
1492 >>> parser = argparse.ArgumentParser()
1493 >>> subparsers = parser.add_subparsers()
1494 >>>
1495 >>> # create the parser for the "foo" command
1496 >>> parser_foo = subparsers.add_parser('foo')
1497 >>> parser_foo.add_argument('-x', type=int, default=1)
1498 >>> parser_foo.add_argument('y', type=float)
1499 >>> parser_foo.set_defaults(func=foo)
1500 >>>
1501 >>> # create the parser for the "bar" command
1502 >>> parser_bar = subparsers.add_parser('bar')
1503 >>> parser_bar.add_argument('z')
1504 >>> parser_bar.set_defaults(func=bar)
1505 >>>
1506 >>> # parse the args and call whatever function was selected
1507 >>> args = parser.parse_args('foo 1 -x 2'.split())
1508 >>> args.func(args)
1509 2.0
1510 >>>
1511 >>> # parse the args and call whatever function was selected
1512 >>> args = parser.parse_args('bar XYZYX'.split())
1513 >>> args.func(args)
1514 ((XYZYX))
1515
Steven Bethardfd311a72010-12-18 11:19:23 +00001516 This way, you can let :meth:`parse_args` do the job of calling the
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001517 appropriate function after argument parsing is complete. Associating
1518 functions with actions like this is typically the easiest way to handle the
1519 different actions for each of your subparsers. However, if it is necessary
1520 to check the name of the subparser that was invoked, the ``dest`` keyword
1521 argument to the :meth:`add_subparsers` call will work::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001522
1523 >>> parser = argparse.ArgumentParser()
1524 >>> subparsers = parser.add_subparsers(dest='subparser_name')
1525 >>> subparser1 = subparsers.add_parser('1')
1526 >>> subparser1.add_argument('-x')
1527 >>> subparser2 = subparsers.add_parser('2')
1528 >>> subparser2.add_argument('y')
1529 >>> parser.parse_args(['2', 'frobble'])
1530 Namespace(subparser_name='2', y='frobble')
1531
1532
1533FileType objects
1534^^^^^^^^^^^^^^^^
1535
1536.. class:: FileType(mode='r', bufsize=None)
1537
1538 The :class:`FileType` factory creates objects that can be passed to the type
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001539 argument of :meth:`ArgumentParser.add_argument`. Arguments that have
1540 :class:`FileType` objects as their type will open command-line args as files
1541 with the requested modes and buffer sizes:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001542
1543 >>> parser = argparse.ArgumentParser()
1544 >>> parser.add_argument('--output', type=argparse.FileType('wb', 0))
1545 >>> parser.parse_args(['--output', 'out'])
Georg Brandl04536b02011-01-09 09:31:01 +00001546 Namespace(output=<_io.BufferedWriter name='out'>)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001547
1548 FileType objects understand the pseudo-argument ``'-'`` and automatically
1549 convert this into ``sys.stdin`` for readable :class:`FileType` objects and
1550 ``sys.stdout`` for writable :class:`FileType` objects:
1551
1552 >>> parser = argparse.ArgumentParser()
1553 >>> parser.add_argument('infile', type=argparse.FileType('r'))
1554 >>> parser.parse_args(['-'])
Georg Brandl04536b02011-01-09 09:31:01 +00001555 Namespace(infile=<_io.TextIOWrapper name='<stdin>' encoding='UTF-8'>)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001556
1557
1558Argument groups
1559^^^^^^^^^^^^^^^
1560
Georg Brandle0bf91d2010-10-17 10:34:28 +00001561.. method:: ArgumentParser.add_argument_group(title=None, description=None)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001562
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001563 By default, :class:`ArgumentParser` groups command-line arguments into
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001564 "positional arguments" and "optional arguments" when displaying help
1565 messages. When there is a better conceptual grouping of arguments than this
1566 default one, appropriate groups can be created using the
1567 :meth:`add_argument_group` method::
1568
1569 >>> parser = argparse.ArgumentParser(prog='PROG', add_help=False)
1570 >>> group = parser.add_argument_group('group')
1571 >>> group.add_argument('--foo', help='foo help')
1572 >>> group.add_argument('bar', help='bar help')
1573 >>> parser.print_help()
1574 usage: PROG [--foo FOO] bar
1575
1576 group:
1577 bar bar help
1578 --foo FOO foo help
1579
1580 The :meth:`add_argument_group` method returns an argument group object which
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001581 has an :meth:`~ArgumentParser.add_argument` method just like a regular
1582 :class:`ArgumentParser`. When an argument is added to the group, the parser
1583 treats it just like a normal argument, but displays the argument in a
1584 separate group for help messages. The :meth:`add_argument_group` method
Georg Brandle0bf91d2010-10-17 10:34:28 +00001585 accepts *title* and *description* arguments which can be used to
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001586 customize this display::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001587
1588 >>> parser = argparse.ArgumentParser(prog='PROG', add_help=False)
1589 >>> group1 = parser.add_argument_group('group1', 'group1 description')
1590 >>> group1.add_argument('foo', help='foo help')
1591 >>> group2 = parser.add_argument_group('group2', 'group2 description')
1592 >>> group2.add_argument('--bar', help='bar help')
1593 >>> parser.print_help()
1594 usage: PROG [--bar BAR] foo
1595
1596 group1:
1597 group1 description
1598
1599 foo foo help
1600
1601 group2:
1602 group2 description
1603
1604 --bar BAR bar help
1605
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001606 Note that any arguments not your user defined groups will end up back in the
1607 usual "positional arguments" and "optional arguments" sections.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001608
1609
1610Mutual exclusion
1611^^^^^^^^^^^^^^^^
1612
Georg Brandle0bf91d2010-10-17 10:34:28 +00001613.. method:: add_mutually_exclusive_group(required=False)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001614
Ezio Melotti0ee9c1b2011-04-21 16:12:17 +03001615 Create a mutually exclusive group. :mod:`argparse` will make sure that only
1616 one of the arguments in the mutually exclusive group was present on the
1617 command line::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001618
1619 >>> parser = argparse.ArgumentParser(prog='PROG')
1620 >>> group = parser.add_mutually_exclusive_group()
1621 >>> group.add_argument('--foo', action='store_true')
1622 >>> group.add_argument('--bar', action='store_false')
1623 >>> parser.parse_args(['--foo'])
1624 Namespace(bar=True, foo=True)
1625 >>> parser.parse_args(['--bar'])
1626 Namespace(bar=False, foo=False)
1627 >>> parser.parse_args(['--foo', '--bar'])
1628 usage: PROG [-h] [--foo | --bar]
1629 PROG: error: argument --bar: not allowed with argument --foo
1630
Georg Brandle0bf91d2010-10-17 10:34:28 +00001631 The :meth:`add_mutually_exclusive_group` method also accepts a *required*
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001632 argument, to indicate that at least one of the mutually exclusive arguments
1633 is required::
1634
1635 >>> parser = argparse.ArgumentParser(prog='PROG')
1636 >>> group = parser.add_mutually_exclusive_group(required=True)
1637 >>> group.add_argument('--foo', action='store_true')
1638 >>> group.add_argument('--bar', action='store_false')
1639 >>> parser.parse_args([])
1640 usage: PROG [-h] (--foo | --bar)
1641 PROG: error: one of the arguments --foo --bar is required
1642
1643 Note that currently mutually exclusive argument groups do not support the
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001644 *title* and *description* arguments of
1645 :meth:`~ArgumentParser.add_argument_group`.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001646
1647
1648Parser defaults
1649^^^^^^^^^^^^^^^
1650
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001651.. method:: ArgumentParser.set_defaults(**kwargs)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001652
1653 Most of the time, the attributes of the object returned by :meth:`parse_args`
1654 will be fully determined by inspecting the command-line args and the argument
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001655 actions. :meth:`set_defaults` allows some additional
Georg Brandl1d827ff2011-04-16 16:44:54 +02001656 attributes that are determined without any inspection of the command line to
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001657 be added::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001658
1659 >>> parser = argparse.ArgumentParser()
1660 >>> parser.add_argument('foo', type=int)
1661 >>> parser.set_defaults(bar=42, baz='badger')
1662 >>> parser.parse_args(['736'])
1663 Namespace(bar=42, baz='badger', foo=736)
1664
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001665 Note that parser-level defaults always override argument-level defaults::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001666
1667 >>> parser = argparse.ArgumentParser()
1668 >>> parser.add_argument('--foo', default='bar')
1669 >>> parser.set_defaults(foo='spam')
1670 >>> parser.parse_args([])
1671 Namespace(foo='spam')
1672
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001673 Parser-level defaults can be particularly useful when working with multiple
1674 parsers. See the :meth:`~ArgumentParser.add_subparsers` method for an
1675 example of this type.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001676
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001677.. method:: ArgumentParser.get_default(dest)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001678
1679 Get the default value for a namespace attribute, as set by either
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001680 :meth:`~ArgumentParser.add_argument` or by
1681 :meth:`~ArgumentParser.set_defaults`::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001682
1683 >>> parser = argparse.ArgumentParser()
1684 >>> parser.add_argument('--foo', default='badger')
1685 >>> parser.get_default('foo')
1686 'badger'
1687
1688
1689Printing help
1690^^^^^^^^^^^^^
1691
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001692In most typical applications, :meth:`~ArgumentParser.parse_args` will take
1693care of formatting and printing any usage or error messages. However, several
1694formatting methods are available:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001695
Georg Brandle0bf91d2010-10-17 10:34:28 +00001696.. method:: ArgumentParser.print_usage(file=None)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001697
1698 Print a brief description of how the :class:`ArgumentParser` should be
R. David Murray32e17712010-12-18 16:39:06 +00001699 invoked on the command line. If *file* is ``None``, :data:`sys.stdout` is
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001700 assumed.
1701
Georg Brandle0bf91d2010-10-17 10:34:28 +00001702.. method:: ArgumentParser.print_help(file=None)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001703
1704 Print a help message, including the program usage and information about the
Georg Brandle0bf91d2010-10-17 10:34:28 +00001705 arguments registered with the :class:`ArgumentParser`. If *file* is
R. David Murray32e17712010-12-18 16:39:06 +00001706 ``None``, :data:`sys.stdout` is assumed.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001707
1708There are also variants of these methods that simply return a string instead of
1709printing it:
1710
Georg Brandle0bf91d2010-10-17 10:34:28 +00001711.. method:: ArgumentParser.format_usage()
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001712
1713 Return a string containing a brief description of how the
1714 :class:`ArgumentParser` should be invoked on the command line.
1715
Georg Brandle0bf91d2010-10-17 10:34:28 +00001716.. method:: ArgumentParser.format_help()
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001717
1718 Return a string containing a help message, including the program usage and
1719 information about the arguments registered with the :class:`ArgumentParser`.
1720
1721
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001722Partial parsing
1723^^^^^^^^^^^^^^^
1724
Georg Brandle0bf91d2010-10-17 10:34:28 +00001725.. method:: ArgumentParser.parse_known_args(args=None, namespace=None)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001726
Georg Brandl1d827ff2011-04-16 16:44:54 +02001727Sometimes a script may only parse a few of the command-line arguments, passing
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001728the remaining arguments on to another script or program. In these cases, the
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001729:meth:`~ArgumentParser.parse_known_args` method can be useful. It works much like
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001730:meth:`~ArgumentParser.parse_args` except that it does not produce an error when
1731extra arguments are present. Instead, it returns a two item tuple containing
1732the populated namespace and the list of remaining argument strings.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001733
1734::
1735
1736 >>> parser = argparse.ArgumentParser()
1737 >>> parser.add_argument('--foo', action='store_true')
1738 >>> parser.add_argument('bar')
1739 >>> parser.parse_known_args(['--foo', '--badger', 'BAR', 'spam'])
1740 (Namespace(bar='BAR', foo=True), ['--badger', 'spam'])
1741
1742
1743Customizing file parsing
1744^^^^^^^^^^^^^^^^^^^^^^^^
1745
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001746.. method:: ArgumentParser.convert_arg_line_to_args(arg_line)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001747
Georg Brandle0bf91d2010-10-17 10:34:28 +00001748 Arguments that are read from a file (see the *fromfile_prefix_chars*
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001749 keyword argument to the :class:`ArgumentParser` constructor) are read one
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001750 argument per line. :meth:`convert_arg_line_to_args` can be overriden for
1751 fancier reading.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001752
Georg Brandle0bf91d2010-10-17 10:34:28 +00001753 This method takes a single argument *arg_line* which is a string read from
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001754 the argument file. It returns a list of arguments parsed from this string.
1755 The method is called once per line read from the argument file, in order.
1756
1757 A useful override of this method is one that treats each space-separated word
1758 as an argument::
1759
1760 def convert_arg_line_to_args(self, arg_line):
1761 for arg in arg_line.split():
1762 if not arg.strip():
1763 continue
1764 yield arg
1765
1766
Georg Brandl93754922010-10-17 10:28:04 +00001767Exiting methods
1768^^^^^^^^^^^^^^^
1769
1770.. method:: ArgumentParser.exit(status=0, message=None)
1771
1772 This method terminates the program, exiting with the specified *status*
1773 and, if given, it prints a *message* before that.
1774
1775.. method:: ArgumentParser.error(message)
1776
1777 This method prints a usage message including the *message* to the
1778 standard output and terminates the program with a status code of 2.
1779
Raymond Hettinger677e10a2010-12-07 06:45:30 +00001780.. _upgrading-optparse-code:
Georg Brandl93754922010-10-17 10:28:04 +00001781
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001782Upgrading optparse code
1783-----------------------
1784
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001785Originally, the :mod:`argparse` module had attempted to maintain compatibility
Ezio Melotti0ee9c1b2011-04-21 16:12:17 +03001786with :mod:`optparse`. However, :mod:`optparse` was difficult to extend
1787transparently, particularly with the changes required to support the new
1788``nargs=`` specifiers and better usage messages. When most everything in
1789:mod:`optparse` had either been copy-pasted over or monkey-patched, it no
1790longer seemed practical to try to maintain the backwards compatibility.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001791
Ezio Melotti0ee9c1b2011-04-21 16:12:17 +03001792A partial upgrade path from :mod:`optparse` to :mod:`argparse`:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001793
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001794* Replace all :meth:`optparse.OptionParser.add_option` calls with
1795 :meth:`ArgumentParser.add_argument` calls.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001796
1797* Replace ``options, args = parser.parse_args()`` with ``args =
Georg Brandlc9007082011-01-09 09:04:08 +00001798 parser.parse_args()`` and add additional :meth:`ArgumentParser.add_argument`
1799 calls for the positional arguments.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001800
1801* Replace callback actions and the ``callback_*`` keyword arguments with
1802 ``type`` or ``action`` arguments.
1803
1804* Replace string names for ``type`` keyword arguments with the corresponding
1805 type objects (e.g. int, float, complex, etc).
1806
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001807* Replace :class:`optparse.Values` with :class:`Namespace` and
1808 :exc:`optparse.OptionError` and :exc:`optparse.OptionValueError` with
1809 :exc:`ArgumentError`.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001810
1811* Replace strings with implicit arguments such as ``%default`` or ``%prog`` with
Ezio Melotticca4ef82011-04-21 15:26:46 +03001812 the standard Python syntax to use dictionaries to format strings, that is,
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001813 ``%(default)s`` and ``%(prog)s``.
Steven Bethard59710962010-05-24 03:21:08 +00001814
1815* Replace the OptionParser constructor ``version`` argument with a call to
1816 ``parser.add_argument('--version', action='version', version='<the version>')``