blob: a30a8c4706dfccec810d36ac22145f3c20f6c007 [file] [log] [blame]
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001:mod:`argparse` -- Parser for command line options, arguments and sub-commands
2==============================================================================
3
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
17Example
18-------
19
Benjamin Peterson98047eb2010-03-03 02:07:08 +000020The following code is a Python program that takes a list of integers and
21produces either the sum or the max::
Benjamin Peterson698a18a2010-03-02 22:34:37 +000022
23 import argparse
24
25 parser = argparse.ArgumentParser(description='Process some integers.')
26 parser.add_argument('integers', metavar='N', type=int, nargs='+',
27 help='an integer for the accumulator')
28 parser.add_argument('--sum', dest='accumulate', action='store_const',
29 const=sum, default=max,
30 help='sum the integers (default: find the max)')
31
32 args = parser.parse_args()
Benjamin Petersonb2deb112010-03-03 02:09:18 +000033 print(args.accumulate(args.integers))
Benjamin Peterson698a18a2010-03-02 22:34:37 +000034
35Assuming the Python code above is saved into a file called ``prog.py``, it can
36be run at the command line and provides useful help messages::
37
38 $ prog.py -h
39 usage: prog.py [-h] [--sum] N [N ...]
40
41 Process some integers.
42
43 positional arguments:
44 N an integer for the accumulator
45
46 optional arguments:
47 -h, --help show this help message and exit
48 --sum sum the integers (default: find the max)
49
50When run with the appropriate arguments, it prints either the sum or the max of
51the command-line integers::
52
53 $ prog.py 1 2 3 4
54 4
55
56 $ prog.py 1 2 3 4 --sum
57 10
58
59If invalid arguments are passed in, it will issue an error::
60
61 $ prog.py a b c
62 usage: prog.py [-h] [--sum] N [N ...]
63 prog.py: error: argument N: invalid int value: 'a'
64
65The following sections walk you through this example.
66
67Creating a parser
68^^^^^^^^^^^^^^^^^
69
Benjamin Peterson2614cda2010-03-21 22:36:19 +000070The first step in using the :mod:`argparse` is creating an
Benjamin Peterson98047eb2010-03-03 02:07:08 +000071:class:`ArgumentParser` object::
Benjamin Peterson698a18a2010-03-02 22:34:37 +000072
73 >>> parser = argparse.ArgumentParser(description='Process some integers.')
74
75The :class:`ArgumentParser` object will hold all the information necessary to
Benjamin Peterson98047eb2010-03-03 02:07:08 +000076parse the command line into python data types.
Benjamin Peterson698a18a2010-03-02 22:34:37 +000077
78
79Adding arguments
80^^^^^^^^^^^^^^^^
81
Benjamin Peterson98047eb2010-03-03 02:07:08 +000082Filling an :class:`ArgumentParser` with information about program arguments is
83done by making calls to the :meth:`~ArgumentParser.add_argument` method.
84Generally, these calls tell the :class:`ArgumentParser` how to take the strings
85on the command line and turn them into objects. This information is stored and
86used when :meth:`~ArgumentParser.parse_args` is called. For example::
Benjamin Peterson698a18a2010-03-02 22:34:37 +000087
88 >>> parser.add_argument('integers', metavar='N', type=int, nargs='+',
89 ... help='an integer for the accumulator')
90 >>> parser.add_argument('--sum', dest='accumulate', action='store_const',
91 ... const=sum, default=max,
92 ... help='sum the integers (default: find the max)')
93
Benjamin Peterson98047eb2010-03-03 02:07:08 +000094Later, calling :meth:`parse_args` will return an object with
Benjamin Peterson698a18a2010-03-02 22:34:37 +000095two attributes, ``integers`` and ``accumulate``. The ``integers`` attribute
96will be a list of one or more ints, and the ``accumulate`` attribute will be
97either the :func:`sum` function, if ``--sum`` was specified at the command line,
98or the :func:`max` function if it was not.
99
100Parsing arguments
101^^^^^^^^^^^^^^^^^
102
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000103:class:`ArgumentParser` parses args through the
104:meth:`~ArgumentParser.parse_args` method. This will inspect the command-line,
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000105convert each arg to the appropriate type and then invoke the appropriate action.
106In most cases, this means a simple namespace object will be built up from
107attributes parsed out of the command-line::
108
109 >>> parser.parse_args(['--sum', '7', '-1', '42'])
110 Namespace(accumulate=<built-in function sum>, integers=[7, -1, 42])
111
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000112In a script, :meth:`~ArgumentParser.parse_args` will typically be called with no
113arguments, and the :class:`ArgumentParser` will automatically determine the
114command-line args from :data:`sys.argv`.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000115
116
117ArgumentParser objects
118----------------------
119
120.. class:: ArgumentParser([description], [epilog], [prog], [usage], [add_help], [argument_default], [parents], [prefix_chars], [conflict_handler], [formatter_class])
121
122 Create a new :class:`ArgumentParser` object. Each parameter has its own more
123 detailed description below, but in short they are:
124
125 * description_ - Text to display before the argument help.
126
127 * epilog_ - Text to display after the argument help.
128
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000129 * add_help_ - Add a -h/--help option to the parser. (default: ``True``)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000130
131 * argument_default_ - Set the global default value for arguments.
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000132 (default: ``None``)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000133
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000134 * parents_ - A list of :class:`ArgumentParser` objects whose arguments should
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000135 also be included.
136
137 * prefix_chars_ - The set of characters that prefix optional arguments.
138 (default: '-')
139
140 * fromfile_prefix_chars_ - The set of characters that prefix files from
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000141 which additional arguments should be read. (default: ``None``)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000142
143 * formatter_class_ - A class for customizing the help output.
144
145 * conflict_handler_ - Usually unnecessary, defines strategy for resolving
146 conflicting optionals.
147
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000148 * prog_ - The name of the program (default:
149 :data:`sys.argv[0]`)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000150
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000151 * usage_ - The string describing the program usage (default: generated)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000152
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000153The following sections describe how each of these are used.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000154
155
156description
157^^^^^^^^^^^
158
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000159Most calls to the :class:`ArgumentParser` constructor will use the
160``description=`` keyword argument. This argument gives a brief description of
161what the program does and how it works. In help messages, the description is
162displayed between the command-line usage string and the help messages for the
163various arguments::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000164
165 >>> parser = argparse.ArgumentParser(description='A foo that bars')
166 >>> parser.print_help()
167 usage: argparse.py [-h]
168
169 A foo that bars
170
171 optional arguments:
172 -h, --help show this help message and exit
173
174By default, the description will be line-wrapped so that it fits within the
175given space. To change this behavior, see the formatter_class_ argument.
176
177
178epilog
179^^^^^^
180
181Some programs like to display additional description of the program after the
182description of the arguments. Such text can be specified using the ``epilog=``
183argument to :class:`ArgumentParser`::
184
185 >>> parser = argparse.ArgumentParser(
186 ... description='A foo that bars',
187 ... epilog="And that's how you'd foo a bar")
188 >>> parser.print_help()
189 usage: argparse.py [-h]
190
191 A foo that bars
192
193 optional arguments:
194 -h, --help show this help message and exit
195
196 And that's how you'd foo a bar
197
198As with the description_ argument, the ``epilog=`` text is by default
199line-wrapped, but this behavior can be adjusted with the formatter_class_
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000200argument to :class:`ArgumentParser`.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000201
202
203add_help
204^^^^^^^^
205
R. David Murray88c49fe2010-08-03 17:56:09 +0000206By default, ArgumentParser objects add an option which simply displays
207the parser's help message. For example, consider a file named
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000208``myprogram.py`` containing the following code::
209
210 import argparse
211 parser = argparse.ArgumentParser()
212 parser.add_argument('--foo', help='foo help')
213 args = parser.parse_args()
214
215If ``-h`` or ``--help`` is supplied is at the command-line, the ArgumentParser
216help will be printed::
217
218 $ python myprogram.py --help
219 usage: myprogram.py [-h] [--foo FOO]
220
221 optional arguments:
222 -h, --help show this help message and exit
223 --foo FOO foo help
224
225Occasionally, it may be useful to disable the addition of this help option.
226This can be achieved by passing ``False`` as the ``add_help=`` argument to
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000227:class:`ArgumentParser`::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000228
229 >>> parser = argparse.ArgumentParser(prog='PROG', add_help=False)
230 >>> parser.add_argument('--foo', help='foo help')
231 >>> parser.print_help()
232 usage: PROG [--foo FOO]
233
234 optional arguments:
235 --foo FOO foo help
236
R. David Murray88c49fe2010-08-03 17:56:09 +0000237The help option is typically ``-h/--help``. The exception to this is
238if the ``prefix_chars=`` is specified and does not include ``'-'``, in
239which case ``-h`` and ``--help`` are not valid options. In
240this case, the first character in ``prefix_chars`` is used to prefix
241the help options::
242
243 >>> parser = argparse.ArgumentParser(prog='PROG', prefix_chars='+/')
244 >>> parser.print_help()
245 usage: PROG [+h]
246
247 optional arguments:
248 +h, ++help show this help message and exit
249
250
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000251
252prefix_chars
253^^^^^^^^^^^^
254
255Most command-line options will use ``'-'`` as the prefix, e.g. ``-f/--foo``.
R. David Murray88c49fe2010-08-03 17:56:09 +0000256Parsers that need to support different or additional prefix
257characters, e.g. for options
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000258like ``+f`` or ``/foo``, may specify them using the ``prefix_chars=`` argument
259to the ArgumentParser constructor::
260
261 >>> parser = argparse.ArgumentParser(prog='PROG', prefix_chars='-+')
262 >>> parser.add_argument('+f')
263 >>> parser.add_argument('++bar')
264 >>> parser.parse_args('+f X ++bar Y'.split())
265 Namespace(bar='Y', f='X')
266
267The ``prefix_chars=`` argument defaults to ``'-'``. Supplying a set of
268characters that does not include ``'-'`` will cause ``-f/--foo`` options to be
269disallowed.
270
271
272fromfile_prefix_chars
273^^^^^^^^^^^^^^^^^^^^^
274
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000275Sometimes, for example when dealing with a particularly long argument lists, it
276may make sense to keep the list of arguments in a file rather than typing it out
277at the command line. If the ``fromfile_prefix_chars=`` argument is given to the
278:class:`ArgumentParser` constructor, then arguments that start with any of the
279specified characters will be treated as files, and will be replaced by the
280arguments they contain. For example::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000281
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000282 >>> with open('args.txt', 'w') as fp:
283 ... fp.write('-f\nbar')
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000284 >>> parser = argparse.ArgumentParser(fromfile_prefix_chars='@')
285 >>> parser.add_argument('-f')
286 >>> parser.parse_args(['-f', 'foo', '@args.txt'])
287 Namespace(f='bar')
288
289Arguments read from a file must by default be one per line (but see also
290:meth:`convert_arg_line_to_args`) and are treated as if they were in the same
291place as the original file referencing argument on the command line. So in the
292example above, the expression ``['-f', 'foo', '@args.txt']`` is considered
293equivalent to the expression ``['-f', 'foo', '-f', 'bar']``.
294
295The ``fromfile_prefix_chars=`` argument defaults to ``None``, meaning that
296arguments will never be treated as file references.
297
298argument_default
299^^^^^^^^^^^^^^^^
300
301Generally, argument defaults are specified either by passing a default to
302:meth:`add_argument` or by calling the :meth:`set_defaults` methods with a
303specific set of name-value pairs. Sometimes however, it may be useful to
304specify a single parser-wide default for arguments. This can be accomplished by
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000305passing the ``argument_default=`` keyword argument to :class:`ArgumentParser`.
306For example, to globally suppress attribute creation on :meth:`parse_args`
307calls, we supply ``argument_default=SUPPRESS``::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000308
309 >>> parser = argparse.ArgumentParser(argument_default=argparse.SUPPRESS)
310 >>> parser.add_argument('--foo')
311 >>> parser.add_argument('bar', nargs='?')
312 >>> parser.parse_args(['--foo', '1', 'BAR'])
313 Namespace(bar='BAR', foo='1')
314 >>> parser.parse_args([])
315 Namespace()
316
317
318parents
319^^^^^^^
320
321Sometimes, several parsers share a common set of arguments. Rather than
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000322repeating the definitions of these arguments, a single parser with all the
323shared arguments and passed to ``parents=`` argument to :class:`ArgumentParser`
324can be used. The ``parents=`` argument takes a list of :class:`ArgumentParser`
325objects, collects all the positional and optional actions from them, and adds
326these actions to the :class:`ArgumentParser` object being constructed::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000327
328 >>> parent_parser = argparse.ArgumentParser(add_help=False)
329 >>> parent_parser.add_argument('--parent', type=int)
330
331 >>> foo_parser = argparse.ArgumentParser(parents=[parent_parser])
332 >>> foo_parser.add_argument('foo')
333 >>> foo_parser.parse_args(['--parent', '2', 'XXX'])
334 Namespace(foo='XXX', parent=2)
335
336 >>> bar_parser = argparse.ArgumentParser(parents=[parent_parser])
337 >>> bar_parser.add_argument('--bar')
338 >>> bar_parser.parse_args(['--bar', 'YYY'])
339 Namespace(bar='YYY', parent=None)
340
341Note that most parent parsers will specify ``add_help=False``. Otherwise, the
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000342:class:`ArgumentParser` will see two ``-h/--help`` options (one in the parent
343and one in the child) and raise an error.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000344
345
346formatter_class
347^^^^^^^^^^^^^^^
348
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000349:class:`ArgumentParser` objects allow the help formatting to be customized by
350specifying an alternate formatting class. Currently, there are three such
351classes: :class:`argparse.RawDescriptionHelpFormatter`,
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000352:class:`argparse.RawTextHelpFormatter` and
353:class:`argparse.ArgumentDefaultsHelpFormatter`. The first two allow more
354control over how textual descriptions are displayed, while the last
355automatically adds information about argument default values.
356
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000357By default, :class:`ArgumentParser` objects line-wrap the description_ and
358epilog_ texts in command-line help messages::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000359
360 >>> parser = argparse.ArgumentParser(
361 ... prog='PROG',
362 ... description='''this description
363 ... was indented weird
364 ... but that is okay''',
365 ... epilog='''
366 ... likewise for this epilog whose whitespace will
367 ... be cleaned up and whose words will be wrapped
368 ... across a couple lines''')
369 >>> parser.print_help()
370 usage: PROG [-h]
371
372 this description was indented weird but that is okay
373
374 optional arguments:
375 -h, --help show this help message and exit
376
377 likewise for this epilog whose whitespace will be cleaned up and whose words
378 will be wrapped across a couple lines
379
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000380Passing :class:`argparse.RawDescriptionHelpFormatter` as ``formatter_class=``
381indicates that description_ and epilog_ are already correctly formatted and
382should not be line-wrapped::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000383
384 >>> parser = argparse.ArgumentParser(
385 ... prog='PROG',
386 ... formatter_class=argparse.RawDescriptionHelpFormatter,
387 ... description=textwrap.dedent('''\
388 ... Please do not mess up this text!
389 ... --------------------------------
390 ... I have indented it
391 ... exactly the way
392 ... I want it
393 ... '''))
394 >>> parser.print_help()
395 usage: PROG [-h]
396
397 Please do not mess up this text!
398 --------------------------------
399 I have indented it
400 exactly the way
401 I want it
402
403 optional arguments:
404 -h, --help show this help message and exit
405
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000406:class:`RawTextHelpFormatter` maintains whitespace for all sorts of help text
407including argument descriptions.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000408
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000409The other formatter class available, :class:`ArgumentDefaultsHelpFormatter`,
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000410will add information about the default value of each of the arguments::
411
412 >>> parser = argparse.ArgumentParser(
413 ... prog='PROG',
414 ... formatter_class=argparse.ArgumentDefaultsHelpFormatter)
415 >>> parser.add_argument('--foo', type=int, default=42, help='FOO!')
416 >>> parser.add_argument('bar', nargs='*', default=[1, 2, 3], help='BAR!')
417 >>> parser.print_help()
418 usage: PROG [-h] [--foo FOO] [bar [bar ...]]
419
420 positional arguments:
421 bar BAR! (default: [1, 2, 3])
422
423 optional arguments:
424 -h, --help show this help message and exit
425 --foo FOO FOO! (default: 42)
426
427
428conflict_handler
429^^^^^^^^^^^^^^^^
430
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000431:class:`ArgumentParser` objects do not allow two actions with the same option
432string. By default, :class:`ArgumentParser` objects raises an exception if an
433attempt is made to create an argument with an option string that is already in
434use::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000435
436 >>> parser = argparse.ArgumentParser(prog='PROG')
437 >>> parser.add_argument('-f', '--foo', help='old foo help')
438 >>> parser.add_argument('--foo', help='new foo help')
439 Traceback (most recent call last):
440 ..
441 ArgumentError: argument --foo: conflicting option string(s): --foo
442
443Sometimes (e.g. when using parents_) it may be useful to simply override any
444older arguments with the same option string. To get this behavior, the value
445``'resolve'`` can be supplied to the ``conflict_handler=`` argument of
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000446:class:`ArgumentParser`::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000447
448 >>> parser = argparse.ArgumentParser(prog='PROG', conflict_handler='resolve')
449 >>> parser.add_argument('-f', '--foo', help='old foo help')
450 >>> parser.add_argument('--foo', help='new foo help')
451 >>> parser.print_help()
452 usage: PROG [-h] [-f FOO] [--foo FOO]
453
454 optional arguments:
455 -h, --help show this help message and exit
456 -f FOO old foo help
457 --foo FOO new foo help
458
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000459Note that :class:`ArgumentParser` objects only remove an action if all of its
460option strings are overridden. So, in the example above, the old ``-f/--foo``
461action is retained as the ``-f`` action, because only the ``--foo`` option
462string was overridden.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000463
464
465prog
466^^^^
467
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000468By default, :class:`ArgumentParser` objects uses ``sys.argv[0]`` to determine
469how to display the name of the program in help messages. This default is almost
Ezio Melottif82340d2010-05-27 22:38:16 +0000470always desirable because it will make the help messages match how the program was
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000471invoked on the command line. For example, consider a file named
472``myprogram.py`` with the following code::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000473
474 import argparse
475 parser = argparse.ArgumentParser()
476 parser.add_argument('--foo', help='foo help')
477 args = parser.parse_args()
478
479The help for this program will display ``myprogram.py`` as the program name
480(regardless of where the program was invoked from)::
481
482 $ python myprogram.py --help
483 usage: myprogram.py [-h] [--foo FOO]
484
485 optional arguments:
486 -h, --help show this help message and exit
487 --foo FOO foo help
488 $ cd ..
489 $ python subdir\myprogram.py --help
490 usage: myprogram.py [-h] [--foo FOO]
491
492 optional arguments:
493 -h, --help show this help message and exit
494 --foo FOO foo help
495
496To change this default behavior, another value can be supplied using the
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000497``prog=`` argument to :class:`ArgumentParser`::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000498
499 >>> parser = argparse.ArgumentParser(prog='myprogram')
500 >>> parser.print_help()
501 usage: myprogram [-h]
502
503 optional arguments:
504 -h, --help show this help message and exit
505
506Note that the program name, whether determined from ``sys.argv[0]`` or from the
507``prog=`` argument, is available to help messages using the ``%(prog)s`` format
508specifier.
509
510::
511
512 >>> parser = argparse.ArgumentParser(prog='myprogram')
513 >>> parser.add_argument('--foo', help='foo of the %(prog)s program')
514 >>> parser.print_help()
515 usage: myprogram [-h] [--foo FOO]
516
517 optional arguments:
518 -h, --help show this help message and exit
519 --foo FOO foo of the myprogram program
520
521
522usage
523^^^^^
524
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000525By default, :class:`ArgumentParser` calculates the usage message from the
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000526arguments it contains::
527
528 >>> parser = argparse.ArgumentParser(prog='PROG')
529 >>> parser.add_argument('--foo', nargs='?', help='foo help')
530 >>> parser.add_argument('bar', nargs='+', help='bar help')
531 >>> parser.print_help()
532 usage: PROG [-h] [--foo [FOO]] bar [bar ...]
533
534 positional arguments:
535 bar bar help
536
537 optional arguments:
538 -h, --help show this help message and exit
539 --foo [FOO] foo help
540
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000541The default message can be overridden with the ``usage=`` keyword argument::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000542
543 >>> parser = argparse.ArgumentParser(prog='PROG', usage='%(prog)s [options]')
544 >>> parser.add_argument('--foo', nargs='?', help='foo help')
545 >>> parser.add_argument('bar', nargs='+', help='bar help')
546 >>> parser.print_help()
547 usage: PROG [options]
548
549 positional arguments:
550 bar bar help
551
552 optional arguments:
553 -h, --help show this help message and exit
554 --foo [FOO] foo help
555
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000556The ``%(prog)s`` format specifier is available to fill in the program name in
557your usage messages.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000558
559
560The add_argument() method
561-------------------------
562
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000563.. method:: ArgumentParser.add_argument(name or flags..., [action], [nargs], [const], [default], [type], [choices], [required], [help], [metavar], [dest])
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000564
565 Define how a single command line argument should be parsed. Each parameter
566 has its own more detailed description below, but in short they are:
567
568 * `name or flags`_ - Either a name or a list of option strings, e.g. ``foo``
569 or ``-f, --foo``
570
571 * action_ - The basic type of action to be taken when this argument is
572 encountered at the command-line.
573
574 * nargs_ - The number of command-line arguments that should be consumed.
575
576 * const_ - A constant value required by some action_ and nargs_ selections.
577
578 * default_ - The value produced if the argument is absent from the
579 command-line.
580
581 * type_ - The type to which the command-line arg should be converted.
582
583 * choices_ - A container of the allowable values for the argument.
584
585 * required_ - Whether or not the command-line option may be omitted
586 (optionals only).
587
588 * help_ - A brief description of what the argument does.
589
590 * metavar_ - A name for the argument in usage messages.
591
592 * dest_ - The name of the attribute to be added to the object returned by
593 :meth:`parse_args`.
594
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000595The following sections describe how each of these are used.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000596
597name or flags
598^^^^^^^^^^^^^
599
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000600The :meth:`add_argument` method must know whether an optional argument, like
601``-f`` or ``--foo``, or a positional argument, like a list of filenames, is
602expected. The first arguments passed to :meth:`add_argument` must therefore be
603either a series of flags, or a simple argument name. For example, an optional
604argument could be created like::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000605
606 >>> parser.add_argument('-f', '--foo')
607
608while a positional argument could be created like::
609
610 >>> parser.add_argument('bar')
611
612When :meth:`parse_args` is called, optional arguments will be identified by the
613``-`` prefix, and the remaining arguments will be assumed to be positional::
614
615 >>> parser = argparse.ArgumentParser(prog='PROG')
616 >>> parser.add_argument('-f', '--foo')
617 >>> parser.add_argument('bar')
618 >>> parser.parse_args(['BAR'])
619 Namespace(bar='BAR', foo=None)
620 >>> parser.parse_args(['BAR', '--foo', 'FOO'])
621 Namespace(bar='BAR', foo='FOO')
622 >>> parser.parse_args(['--foo', 'FOO'])
623 usage: PROG [-h] [-f FOO] bar
624 PROG: error: too few arguments
625
626action
627^^^^^^
628
629:class:`ArgumentParser` objects associate command-line args with actions. These
630actions can do just about anything with the command-line args associated with
631them, though most actions simply add an attribute to the object returned by
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000632:meth:`parse_args`. The ``action`` keyword argument specifies how the
633command-line args should be handled. The supported actions are:
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000634
635* ``'store'`` - This just stores the argument's value. This is the default
636 action. For example::
637
638 >>> parser = argparse.ArgumentParser()
639 >>> parser.add_argument('--foo')
640 >>> parser.parse_args('--foo 1'.split())
641 Namespace(foo='1')
642
643* ``'store_const'`` - This stores the value specified by the const_ keyword
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000644 argument. (Note that the const_ keyword argument defaults to the rather
645 unhelpful ``None``.) The ``'store_const'`` action is most commonly used with
646 optional arguments that specify some sort of flag. For example::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000647
648 >>> parser = argparse.ArgumentParser()
649 >>> parser.add_argument('--foo', action='store_const', const=42)
650 >>> parser.parse_args('--foo'.split())
651 Namespace(foo=42)
652
653* ``'store_true'`` and ``'store_false'`` - These store the values ``True`` and
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000654 ``False`` respectively. These are special cases of ``'store_const'``. For
655 example::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000656
657 >>> parser = argparse.ArgumentParser()
658 >>> parser.add_argument('--foo', action='store_true')
659 >>> parser.add_argument('--bar', action='store_false')
660 >>> parser.parse_args('--foo --bar'.split())
661 Namespace(bar=False, foo=True)
662
663* ``'append'`` - This stores a list, and appends each argument value to the
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000664 list. This is useful to allow an option to be specified multiple times.
665 Example usage::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000666
667 >>> parser = argparse.ArgumentParser()
668 >>> parser.add_argument('--foo', action='append')
669 >>> parser.parse_args('--foo 1 --foo 2'.split())
670 Namespace(foo=['1', '2'])
671
672* ``'append_const'`` - This stores a list, and appends the value specified by
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000673 the const_ keyword argument to the list. (Note that the const_ keyword
674 argument defaults to ``None``.) The ``'append_const'`` action is typically
675 useful when multiple arguments need to store constants to the same list. For
676 example::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000677
678 >>> parser = argparse.ArgumentParser()
679 >>> parser.add_argument('--str', dest='types', action='append_const', const=str)
680 >>> parser.add_argument('--int', dest='types', action='append_const', const=int)
681 >>> parser.parse_args('--str --int'.split())
682 Namespace(types=[<type 'str'>, <type 'int'>])
683
684* ``'version'`` - This expects a ``version=`` keyword argument in the
685 :meth:`add_argument` call, and prints version information and exits when
686 invoked.
687
688 >>> import argparse
689 >>> parser = argparse.ArgumentParser(prog='PROG')
Steven Bethard59710962010-05-24 03:21:08 +0000690 >>> parser.add_argument('--version', action='version', version='%(prog)s 2.0')
691 >>> parser.parse_args(['--version'])
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000692 PROG 2.0
693
694You can also specify an arbitrary action by passing an object that implements
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000695the Action API. The easiest way to do this is to extend
696:class:`argparse.Action`, supplying an appropriate ``__call__`` method. The
697``__call__`` method should accept four parameters:
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000698
699* ``parser`` - The ArgumentParser object which contains this action.
700
701* ``namespace`` - The namespace object that will be returned by
702 :meth:`parse_args`. Most actions add an attribute to this object.
703
704* ``values`` - The associated command-line args, with any type-conversions
705 applied. (Type-conversions are specified with the type_ keyword argument to
706 :meth:`add_argument`.
707
708* ``option_string`` - The option string that was used to invoke this action.
709 The ``option_string`` argument is optional, and will be absent if the action
710 is associated with a positional argument.
711
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000712An example of a custom action::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000713
714 >>> class FooAction(argparse.Action):
715 ... def __call__(self, parser, namespace, values, option_string=None):
Georg Brandl571a9532010-07-26 17:00:20 +0000716 ... print('%r %r %r' % (namespace, values, option_string))
717 ... setattr(namespace, self.dest, values)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000718 ...
719 >>> parser = argparse.ArgumentParser()
720 >>> parser.add_argument('--foo', action=FooAction)
721 >>> parser.add_argument('bar', action=FooAction)
722 >>> args = parser.parse_args('1 --foo 2'.split())
723 Namespace(bar=None, foo=None) '1' None
724 Namespace(bar='1', foo=None) '2' '--foo'
725 >>> args
726 Namespace(bar='1', foo='2')
727
728
729nargs
730^^^^^
731
732ArgumentParser objects usually associate a single command-line argument with a
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000733single action to be taken. The ``nargs`` keyword argument associates a
734different number of command-line arguments with a single action.. The supported
735values are:
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000736
737* N (an integer). N args from the command-line will be gathered together into a
738 list. For example::
739
740 >>> parser = argparse.ArgumentParser()
741 >>> parser.add_argument('--foo', nargs=2)
742 >>> parser.add_argument('bar', nargs=1)
743 >>> parser.parse_args('c --foo a b'.split())
744 Namespace(bar=['c'], foo=['a', 'b'])
745
746 Note that ``nargs=1`` produces a list of one item. This is different from
747 the default, in which the item is produced by itself.
748
749* ``'?'``. One arg will be consumed from the command-line if possible, and
750 produced as a single item. If no command-line arg is present, the value from
751 default_ will be produced. Note that for optional arguments, there is an
752 additional case - the option string is present but not followed by a
753 command-line arg. In this case the value from const_ will be produced. Some
754 examples to illustrate this::
755
756 >>> parser = argparse.ArgumentParser()
757 >>> parser.add_argument('--foo', nargs='?', const='c', default='d')
758 >>> parser.add_argument('bar', nargs='?', default='d')
759 >>> parser.parse_args('XX --foo YY'.split())
760 Namespace(bar='XX', foo='YY')
761 >>> parser.parse_args('XX --foo'.split())
762 Namespace(bar='XX', foo='c')
763 >>> parser.parse_args(''.split())
764 Namespace(bar='d', foo='d')
765
766 One of the more common uses of ``nargs='?'`` is to allow optional input and
767 output files::
768
769 >>> parser = argparse.ArgumentParser()
770 >>> parser.add_argument('infile', nargs='?', type=argparse.FileType('r'), default=sys.stdin)
771 >>> parser.add_argument('outfile', nargs='?', type=argparse.FileType('w'), default=sys.stdout)
772 >>> parser.parse_args(['input.txt', 'output.txt'])
773 Namespace(infile=<open file 'input.txt', mode 'r' at 0x...>, outfile=<open file 'output.txt', mode 'w' at 0x...>)
774 >>> parser.parse_args([])
775 Namespace(infile=<open file '<stdin>', mode 'r' at 0x...>, outfile=<open file '<stdout>', mode 'w' at 0x...>)
776
777* ``'*'``. All command-line args present are gathered into a list. Note that
778 it generally doesn't make much sense to have more than one positional argument
779 with ``nargs='*'``, but multiple optional arguments with ``nargs='*'`` is
780 possible. For example::
781
782 >>> parser = argparse.ArgumentParser()
783 >>> parser.add_argument('--foo', nargs='*')
784 >>> parser.add_argument('--bar', nargs='*')
785 >>> parser.add_argument('baz', nargs='*')
786 >>> parser.parse_args('a b --foo x y --bar 1 2'.split())
787 Namespace(bar=['1', '2'], baz=['a', 'b'], foo=['x', 'y'])
788
789* ``'+'``. Just like ``'*'``, all command-line args present are gathered into a
790 list. Additionally, an error message will be generated if there wasn't at
791 least one command-line arg present. For example::
792
793 >>> parser = argparse.ArgumentParser(prog='PROG')
794 >>> parser.add_argument('foo', nargs='+')
795 >>> parser.parse_args('a b'.split())
796 Namespace(foo=['a', 'b'])
797 >>> parser.parse_args(''.split())
798 usage: PROG [-h] foo [foo ...]
799 PROG: error: too few arguments
800
801If the ``nargs`` keyword argument is not provided, the number of args consumed
802is determined by the action_. Generally this means a single command-line arg
803will be consumed and a single item (not a list) will be produced.
804
805
806const
807^^^^^
808
809The ``const`` argument of :meth:`add_argument` is used to hold constant values
810that are not read from the command line but are required for the various
811ArgumentParser actions. The two most common uses of it are:
812
813* When :meth:`add_argument` is called with ``action='store_const'`` or
814 ``action='append_const'``. These actions add the ``const`` value to one of
815 the attributes of the object returned by :meth:`parse_args`. See the action_
816 description for examples.
817
818* When :meth:`add_argument` is called with option strings (like ``-f`` or
819 ``--foo``) and ``nargs='?'``. This creates an optional argument that can be
820 followed by zero or one command-line args. When parsing the command-line, if
821 the option string is encountered with no command-line arg following it, the
822 value of ``const`` will be assumed instead. See the nargs_ description for
823 examples.
824
825The ``const`` keyword argument defaults to ``None``.
826
827
828default
829^^^^^^^
830
831All optional arguments and some positional arguments may be omitted at the
832command-line. The ``default`` keyword argument of :meth:`add_argument`, whose
833value defaults to ``None``, specifies what value should be used if the
834command-line arg is not present. For optional arguments, the ``default`` value
835is used when the option string was not present at the command line::
836
837 >>> parser = argparse.ArgumentParser()
838 >>> parser.add_argument('--foo', default=42)
839 >>> parser.parse_args('--foo 2'.split())
840 Namespace(foo='2')
841 >>> parser.parse_args(''.split())
842 Namespace(foo=42)
843
844For positional arguments with nargs_ ``='?'`` or ``'*'``, the ``default`` value
845is used when no command-line arg was present::
846
847 >>> parser = argparse.ArgumentParser()
848 >>> parser.add_argument('foo', nargs='?', default=42)
849 >>> parser.parse_args('a'.split())
850 Namespace(foo='a')
851 >>> parser.parse_args(''.split())
852 Namespace(foo=42)
853
854
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000855Providing ``default=argparse.SUPPRESS`` causes no attribute to be added if the
856command-line argument was not present.::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000857
858 >>> parser = argparse.ArgumentParser()
859 >>> parser.add_argument('--foo', default=argparse.SUPPRESS)
860 >>> parser.parse_args([])
861 Namespace()
862 >>> parser.parse_args(['--foo', '1'])
863 Namespace(foo='1')
864
865
866type
867^^^^
868
869By default, ArgumentParser objects read command-line args in as simple strings.
870However, quite often the command-line string should instead be interpreted as
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000871another type, like a :class:`float`, :class:`int` or :class:`file`. The
872``type`` keyword argument of :meth:`add_argument` allows any necessary
Georg Brandl93dc9eb2010-03-14 10:56:14 +0000873type-checking and type-conversions to be performed. Many common built-in types
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000874can be used directly as the value of the ``type`` argument::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000875
876 >>> parser = argparse.ArgumentParser()
877 >>> parser.add_argument('foo', type=int)
878 >>> parser.add_argument('bar', type=file)
879 >>> parser.parse_args('2 temp.txt'.split())
880 Namespace(bar=<open file 'temp.txt', mode 'r' at 0x...>, foo=2)
881
882To ease the use of various types of files, the argparse module provides the
883factory FileType which takes the ``mode=`` and ``bufsize=`` arguments of the
884``file`` object. For example, ``FileType('w')`` can be used to create a
885writable file::
886
887 >>> parser = argparse.ArgumentParser()
888 >>> parser.add_argument('bar', type=argparse.FileType('w'))
889 >>> parser.parse_args(['out.txt'])
890 Namespace(bar=<open file 'out.txt', mode 'w' at 0x...>)
891
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000892``type=`` can take any callable that takes a single string argument and returns
893the type-converted value::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000894
895 >>> def perfect_square(string):
896 ... value = int(string)
897 ... sqrt = math.sqrt(value)
898 ... if sqrt != int(sqrt):
899 ... msg = "%r is not a perfect square" % string
900 ... raise argparse.ArgumentTypeError(msg)
901 ... return value
902 ...
903 >>> parser = argparse.ArgumentParser(prog='PROG')
904 >>> parser.add_argument('foo', type=perfect_square)
905 >>> parser.parse_args('9'.split())
906 Namespace(foo=9)
907 >>> parser.parse_args('7'.split())
908 usage: PROG [-h] foo
909 PROG: error: argument foo: '7' is not a perfect square
910
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000911The choices_ keyword argument may be more convenient for type checkers that
912simply check against a range of values::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000913
914 >>> parser = argparse.ArgumentParser(prog='PROG')
915 >>> parser.add_argument('foo', type=int, choices=xrange(5, 10))
916 >>> parser.parse_args('7'.split())
917 Namespace(foo=7)
918 >>> parser.parse_args('11'.split())
919 usage: PROG [-h] {5,6,7,8,9}
920 PROG: error: argument foo: invalid choice: 11 (choose from 5, 6, 7, 8, 9)
921
922See the choices_ section for more details.
923
924
925choices
926^^^^^^^
927
928Some command-line args should be selected from a restricted set of values.
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000929These can be handled by passing a container object as the ``choices`` keyword
930argument to :meth:`add_argument`. When the command-line is parsed, arg values
931will be checked, and an error message will be displayed if the arg was not one
932of the acceptable values::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000933
934 >>> parser = argparse.ArgumentParser(prog='PROG')
935 >>> parser.add_argument('foo', choices='abc')
936 >>> parser.parse_args('c'.split())
937 Namespace(foo='c')
938 >>> parser.parse_args('X'.split())
939 usage: PROG [-h] {a,b,c}
940 PROG: error: argument foo: invalid choice: 'X' (choose from 'a', 'b', 'c')
941
942Note that inclusion in the ``choices`` container is checked after any type_
943conversions have been performed, so the type of the objects in the ``choices``
944container should match the type_ specified::
945
946 >>> parser = argparse.ArgumentParser(prog='PROG')
947 >>> parser.add_argument('foo', type=complex, choices=[1, 1j])
948 >>> parser.parse_args('1j'.split())
949 Namespace(foo=1j)
950 >>> parser.parse_args('-- -4'.split())
951 usage: PROG [-h] {1,1j}
952 PROG: error: argument foo: invalid choice: (-4+0j) (choose from 1, 1j)
953
954Any object that supports the ``in`` operator can be passed as the ``choices``
955value, so :class:`dict` objects, :class:`set` objects, custom containers,
956etc. are all supported.
957
958
959required
960^^^^^^^^
961
962In general, the argparse module assumes that flags like ``-f`` and ``--bar``
963indicate *optional* arguments, which can always be omitted at the command-line.
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000964To make an option *required*, ``True`` can be specified for the ``required=``
965keyword argument to :meth:`add_argument`::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000966
967 >>> parser = argparse.ArgumentParser()
968 >>> parser.add_argument('--foo', required=True)
969 >>> parser.parse_args(['--foo', 'BAR'])
970 Namespace(foo='BAR')
971 >>> parser.parse_args([])
972 usage: argparse.py [-h] [--foo FOO]
973 argparse.py: error: option --foo is required
974
975As the example shows, if an option is marked as ``required``, :meth:`parse_args`
976will report an error if that option is not present at the command line.
977
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000978.. note::
979
980 Required options are generally considered bad form because users expect
981 *options* to be *optional*, and thus they should be avoided when possible.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000982
983
984help
985^^^^
986
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000987The ``help`` value is a string containing a brief description of the argument.
988When a user requests help (usually by using ``-h`` or ``--help`` at the
989command-line), these ``help`` descriptions will be displayed with each
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000990argument::
991
992 >>> parser = argparse.ArgumentParser(prog='frobble')
993 >>> parser.add_argument('--foo', action='store_true',
994 ... help='foo the bars before frobbling')
995 >>> parser.add_argument('bar', nargs='+',
996 ... help='one of the bars to be frobbled')
997 >>> parser.parse_args('-h'.split())
998 usage: frobble [-h] [--foo] bar [bar ...]
999
1000 positional arguments:
1001 bar one of the bars to be frobbled
1002
1003 optional arguments:
1004 -h, --help show this help message and exit
1005 --foo foo the bars before frobbling
1006
1007The ``help`` strings can include various format specifiers to avoid repetition
1008of things like the program name or the argument default_. The available
1009specifiers include the program name, ``%(prog)s`` and most keyword arguments to
1010:meth:`add_argument`, e.g. ``%(default)s``, ``%(type)s``, etc.::
1011
1012 >>> parser = argparse.ArgumentParser(prog='frobble')
1013 >>> parser.add_argument('bar', nargs='?', type=int, default=42,
1014 ... help='the bar to %(prog)s (default: %(default)s)')
1015 >>> parser.print_help()
1016 usage: frobble [-h] [bar]
1017
1018 positional arguments:
1019 bar the bar to frobble (default: 42)
1020
1021 optional arguments:
1022 -h, --help show this help message and exit
1023
1024
1025metavar
1026^^^^^^^
1027
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001028When :class:`ArgumentParser` generates help messages, it need some way to refer
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001029to each expected argument. By default, ArgumentParser objects use the dest_
1030value as the "name" of each object. By default, for positional argument
1031actions, the dest_ value is used directly, and for optional argument actions,
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001032the dest_ value is uppercased. So, a single positional argument with
1033``dest='bar'`` will that argument will be referred to as ``bar``. A single
1034optional argument ``--foo`` that should be followed by a single command-line arg
1035will be referred to as ``FOO``. An example::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001036
1037 >>> parser = argparse.ArgumentParser()
1038 >>> parser.add_argument('--foo')
1039 >>> parser.add_argument('bar')
1040 >>> parser.parse_args('X --foo Y'.split())
1041 Namespace(bar='X', foo='Y')
1042 >>> parser.print_help()
1043 usage: [-h] [--foo FOO] bar
1044
1045 positional arguments:
1046 bar
1047
1048 optional arguments:
1049 -h, --help show this help message and exit
1050 --foo FOO
1051
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001052An alternative name can be specified with ``metavar``::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001053
1054 >>> parser = argparse.ArgumentParser()
1055 >>> parser.add_argument('--foo', metavar='YYY')
1056 >>> parser.add_argument('bar', metavar='XXX')
1057 >>> parser.parse_args('X --foo Y'.split())
1058 Namespace(bar='X', foo='Y')
1059 >>> parser.print_help()
1060 usage: [-h] [--foo YYY] XXX
1061
1062 positional arguments:
1063 XXX
1064
1065 optional arguments:
1066 -h, --help show this help message and exit
1067 --foo YYY
1068
1069Note that ``metavar`` only changes the *displayed* name - the name of the
1070attribute on the :meth:`parse_args` object is still determined by the dest_
1071value.
1072
1073Different values of ``nargs`` may cause the metavar to be used multiple times.
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001074Providing a tuple to ``metavar`` specifies a different display for each of the
1075arguments::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001076
1077 >>> parser = argparse.ArgumentParser(prog='PROG')
1078 >>> parser.add_argument('-x', nargs=2)
1079 >>> parser.add_argument('--foo', nargs=2, metavar=('bar', 'baz'))
1080 >>> parser.print_help()
1081 usage: PROG [-h] [-x X X] [--foo bar baz]
1082
1083 optional arguments:
1084 -h, --help show this help message and exit
1085 -x X X
1086 --foo bar baz
1087
1088
1089dest
1090^^^^
1091
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001092Most :class:`ArgumentParser` actions add some value as an attribute of the
1093object returned by :meth:`parse_args`. The name of this attribute is determined
1094by the ``dest`` keyword argument of :meth:`add_argument`. For positional
1095argument actions, ``dest`` is normally supplied as the first argument to
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001096:meth:`add_argument`::
1097
1098 >>> parser = argparse.ArgumentParser()
1099 >>> parser.add_argument('bar')
1100 >>> parser.parse_args('XXX'.split())
1101 Namespace(bar='XXX')
1102
1103For optional argument actions, the value of ``dest`` is normally inferred from
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001104the option strings. :class:`ArgumentParser` generates the value of ``dest`` by
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001105taking the first long option string and stripping away the initial ``'--'``
1106string. If no long option strings were supplied, ``dest`` will be derived from
1107the first short option string by stripping the initial ``'-'`` character. Any
1108internal ``'-'`` characters will be converted to ``'_'`` characters to make sure
1109the string is a valid attribute name. The examples below illustrate this
1110behavior::
1111
1112 >>> parser = argparse.ArgumentParser()
1113 >>> parser.add_argument('-f', '--foo-bar', '--foo')
1114 >>> parser.add_argument('-x', '-y')
1115 >>> parser.parse_args('-f 1 -x 2'.split())
1116 Namespace(foo_bar='1', x='2')
1117 >>> parser.parse_args('--foo 1 -y 2'.split())
1118 Namespace(foo_bar='1', x='2')
1119
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001120``dest`` allows a custom attribute name to be provided::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001121
1122 >>> parser = argparse.ArgumentParser()
1123 >>> parser.add_argument('--foo', dest='bar')
1124 >>> parser.parse_args('--foo XXX'.split())
1125 Namespace(bar='XXX')
1126
1127
1128The parse_args() method
1129-----------------------
1130
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001131.. method:: ArgumentParser.parse_args([args], [namespace])
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001132
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001133 Convert argument strings to objects and assign them as attributes of the
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001134 namespace. Return the populated namespace.
1135
1136 Previous calls to :meth:`add_argument` determine exactly what objects are
1137 created and how they are assigned. See the documentation for
1138 :meth:`add_argument` for details.
1139
1140 By default, the arg strings are taken from :data:`sys.argv`, and a new empty
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001141 :class:`Namespace` object is created for the attributes.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001142
1143Option value syntax
1144^^^^^^^^^^^^^^^^^^^
1145
1146The :meth:`parse_args` method supports several ways of specifying the value of
1147an option (if it takes one). In the simplest case, the option and its value are
1148passed as two separate arguments::
1149
1150 >>> parser = argparse.ArgumentParser(prog='PROG')
1151 >>> parser.add_argument('-x')
1152 >>> parser.add_argument('--foo')
1153 >>> parser.parse_args('-x X'.split())
1154 Namespace(foo=None, x='X')
1155 >>> parser.parse_args('--foo FOO'.split())
1156 Namespace(foo='FOO', x=None)
1157
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001158For long options (options with names longer than a single character), the option
1159and value can also be passed as a single command line argument, using ``=`` to
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001160separate them::
1161
1162 >>> parser.parse_args('--foo=FOO'.split())
1163 Namespace(foo='FOO', x=None)
1164
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001165For short options (options only one character long), the option and its value
1166can be concatenated::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001167
1168 >>> parser.parse_args('-xX'.split())
1169 Namespace(foo=None, x='X')
1170
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001171Several short options can be joined together, using only a single ``-`` prefix,
1172as long as only the last option (or none of them) requires a value::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001173
1174 >>> parser = argparse.ArgumentParser(prog='PROG')
1175 >>> parser.add_argument('-x', action='store_true')
1176 >>> parser.add_argument('-y', action='store_true')
1177 >>> parser.add_argument('-z')
1178 >>> parser.parse_args('-xyzZ'.split())
1179 Namespace(x=True, y=True, z='Z')
1180
1181
1182Invalid arguments
1183^^^^^^^^^^^^^^^^^
1184
1185While parsing the command-line, ``parse_args`` checks for a variety of errors,
1186including ambiguous options, invalid types, invalid options, wrong number of
1187positional arguments, etc. When it encounters such an error, it exits and
1188prints the error along with a usage message::
1189
1190 >>> parser = argparse.ArgumentParser(prog='PROG')
1191 >>> parser.add_argument('--foo', type=int)
1192 >>> parser.add_argument('bar', nargs='?')
1193
1194 >>> # invalid type
1195 >>> parser.parse_args(['--foo', 'spam'])
1196 usage: PROG [-h] [--foo FOO] [bar]
1197 PROG: error: argument --foo: invalid int value: 'spam'
1198
1199 >>> # invalid option
1200 >>> parser.parse_args(['--bar'])
1201 usage: PROG [-h] [--foo FOO] [bar]
1202 PROG: error: no such option: --bar
1203
1204 >>> # wrong number of arguments
1205 >>> parser.parse_args(['spam', 'badger'])
1206 usage: PROG [-h] [--foo FOO] [bar]
1207 PROG: error: extra arguments found: badger
1208
1209
1210Arguments containing ``"-"``
1211^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1212
1213The ``parse_args`` method attempts to give errors whenever the user has clearly
1214made a mistake, but some situations are inherently ambiguous. For example, the
1215command-line arg ``'-1'`` could either be an attempt to specify an option or an
1216attempt to provide a positional argument. The ``parse_args`` method is cautious
1217here: positional arguments may only begin with ``'-'`` if they look like
1218negative numbers and there are no options in the parser that look like negative
1219numbers::
1220
1221 >>> parser = argparse.ArgumentParser(prog='PROG')
1222 >>> parser.add_argument('-x')
1223 >>> parser.add_argument('foo', nargs='?')
1224
1225 >>> # no negative number options, so -1 is a positional argument
1226 >>> parser.parse_args(['-x', '-1'])
1227 Namespace(foo=None, x='-1')
1228
1229 >>> # no negative number options, so -1 and -5 are positional arguments
1230 >>> parser.parse_args(['-x', '-1', '-5'])
1231 Namespace(foo='-5', x='-1')
1232
1233 >>> parser = argparse.ArgumentParser(prog='PROG')
1234 >>> parser.add_argument('-1', dest='one')
1235 >>> parser.add_argument('foo', nargs='?')
1236
1237 >>> # negative number options present, so -1 is an option
1238 >>> parser.parse_args(['-1', 'X'])
1239 Namespace(foo=None, one='X')
1240
1241 >>> # negative number options present, so -2 is an option
1242 >>> parser.parse_args(['-2'])
1243 usage: PROG [-h] [-1 ONE] [foo]
1244 PROG: error: no such option: -2
1245
1246 >>> # negative number options present, so both -1s are options
1247 >>> parser.parse_args(['-1', '-1'])
1248 usage: PROG [-h] [-1 ONE] [foo]
1249 PROG: error: argument -1: expected one argument
1250
1251If you have positional arguments that must begin with ``'-'`` and don't look
1252like negative numbers, you can insert the pseudo-argument ``'--'`` which tells
1253``parse_args`` that everything after that is a positional argument::
1254
1255 >>> parser.parse_args(['--', '-f'])
1256 Namespace(foo='-f', one=None)
1257
1258
1259Argument abbreviations
1260^^^^^^^^^^^^^^^^^^^^^^
1261
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001262The :meth:`parse_args` method allows long options to be abbreviated if the
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001263abbreviation is unambiguous::
1264
1265 >>> parser = argparse.ArgumentParser(prog='PROG')
1266 >>> parser.add_argument('-bacon')
1267 >>> parser.add_argument('-badger')
1268 >>> parser.parse_args('-bac MMM'.split())
1269 Namespace(bacon='MMM', badger=None)
1270 >>> parser.parse_args('-bad WOOD'.split())
1271 Namespace(bacon=None, badger='WOOD')
1272 >>> parser.parse_args('-ba BA'.split())
1273 usage: PROG [-h] [-bacon BACON] [-badger BADGER]
1274 PROG: error: ambiguous option: -ba could match -badger, -bacon
1275
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001276An error is produced for arguments that could produce more than one options.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001277
1278
1279Beyond ``sys.argv``
1280^^^^^^^^^^^^^^^^^^^
1281
1282Sometimes it may be useful to have an ArgumentParser parse args other than those
1283of :data:`sys.argv`. This can be accomplished by passing a list of strings to
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001284``parse_args``. This is useful for testing at the interactive prompt::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001285
1286 >>> parser = argparse.ArgumentParser()
1287 >>> parser.add_argument(
1288 ... 'integers', metavar='int', type=int, choices=xrange(10),
1289 ... nargs='+', help='an integer in the range 0..9')
1290 >>> parser.add_argument(
1291 ... '--sum', dest='accumulate', action='store_const', const=sum,
1292 ... default=max, help='sum the integers (default: find the max)')
1293 >>> parser.parse_args(['1', '2', '3', '4'])
1294 Namespace(accumulate=<built-in function max>, integers=[1, 2, 3, 4])
1295 >>> parser.parse_args('1 2 3 4 --sum'.split())
1296 Namespace(accumulate=<built-in function sum>, integers=[1, 2, 3, 4])
1297
1298
1299Custom namespaces
1300^^^^^^^^^^^^^^^^^
1301
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001302It may also be useful to have an :class:`ArgumentParser` assign attributes to an
1303already existing object, rather than the newly-created :class:`Namespace` object
1304that is normally used. This can be achieved by specifying the ``namespace=``
1305keyword argument::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001306
1307 >>> class C(object):
1308 ... pass
1309 ...
1310 >>> c = C()
1311 >>> parser = argparse.ArgumentParser()
1312 >>> parser.add_argument('--foo')
1313 >>> parser.parse_args(args=['--foo', 'BAR'], namespace=c)
1314 >>> c.foo
1315 'BAR'
1316
1317
1318Other utilities
1319---------------
1320
1321Sub-commands
1322^^^^^^^^^^^^
1323
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001324.. method:: ArgumentParser.add_subparsers()
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001325
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001326 Many programs split up their functionality into a number of sub-commands,
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001327 for example, the ``svn`` program can invoke sub-commands like ``svn
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001328 checkout``, ``svn update``, and ``svn commit``. Splitting up functionality
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001329 this way can be a particularly good idea when a program performs several
1330 different functions which require different kinds of command-line arguments.
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001331 :class:`ArgumentParser` supports the creation of such sub-commands with the
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001332 :meth:`add_subparsers` method. The :meth:`add_subparsers` method is normally
1333 called with no arguments and returns an special action object. This object
1334 has a single method, ``add_parser``, which takes a command name and any
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001335 :class:`ArgumentParser` constructor arguments, and returns an
1336 :class:`ArgumentParser` object that can be modified as usual.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001337
1338 Some example usage::
1339
1340 >>> # create the top-level parser
1341 >>> parser = argparse.ArgumentParser(prog='PROG')
1342 >>> parser.add_argument('--foo', action='store_true', help='foo help')
1343 >>> subparsers = parser.add_subparsers(help='sub-command help')
1344 >>>
1345 >>> # create the parser for the "a" command
1346 >>> parser_a = subparsers.add_parser('a', help='a help')
1347 >>> parser_a.add_argument('bar', type=int, help='bar help')
1348 >>>
1349 >>> # create the parser for the "b" command
1350 >>> parser_b = subparsers.add_parser('b', help='b help')
1351 >>> parser_b.add_argument('--baz', choices='XYZ', help='baz help')
1352 >>>
1353 >>> # parse some arg lists
1354 >>> parser.parse_args(['a', '12'])
1355 Namespace(bar=12, foo=False)
1356 >>> parser.parse_args(['--foo', 'b', '--baz', 'Z'])
1357 Namespace(baz='Z', foo=True)
1358
1359 Note that the object returned by :meth:`parse_args` will only contain
1360 attributes for the main parser and the subparser that was selected by the
1361 command line (and not any other subparsers). So in the example above, when
1362 the ``"a"`` command is specified, only the ``foo`` and ``bar`` attributes are
1363 present, and when the ``"b"`` command is specified, only the ``foo`` and
1364 ``baz`` attributes are present.
1365
1366 Similarly, when a help message is requested from a subparser, only the help
1367 for that particular parser will be printed. The help message will not
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001368 include parent parser or sibling parser messages. (A help message for each
1369 subparser command, however, can be given by supplying the ``help=`` argument
1370 to ``add_parser`` as above.)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001371
1372 ::
1373
1374 >>> parser.parse_args(['--help'])
1375 usage: PROG [-h] [--foo] {a,b} ...
1376
1377 positional arguments:
1378 {a,b} sub-command help
1379 a a help
1380 b b help
1381
1382 optional arguments:
1383 -h, --help show this help message and exit
1384 --foo foo help
1385
1386 >>> parser.parse_args(['a', '--help'])
1387 usage: PROG a [-h] bar
1388
1389 positional arguments:
1390 bar bar help
1391
1392 optional arguments:
1393 -h, --help show this help message and exit
1394
1395 >>> parser.parse_args(['b', '--help'])
1396 usage: PROG b [-h] [--baz {X,Y,Z}]
1397
1398 optional arguments:
1399 -h, --help show this help message and exit
1400 --baz {X,Y,Z} baz help
1401
1402 The :meth:`add_subparsers` method also supports ``title`` and ``description``
1403 keyword arguments. When either is present, the subparser's commands will
1404 appear in their own group in the help output. For example::
1405
1406 >>> parser = argparse.ArgumentParser()
1407 >>> subparsers = parser.add_subparsers(title='subcommands',
1408 ... description='valid subcommands',
1409 ... help='additional help')
1410 >>> subparsers.add_parser('foo')
1411 >>> subparsers.add_parser('bar')
1412 >>> parser.parse_args(['-h'])
1413 usage: [-h] {foo,bar} ...
1414
1415 optional arguments:
1416 -h, --help show this help message and exit
1417
1418 subcommands:
1419 valid subcommands
1420
1421 {foo,bar} additional help
1422
1423
1424 One particularly effective way of handling sub-commands is to combine the use
1425 of the :meth:`add_subparsers` method with calls to :meth:`set_defaults` so
1426 that each subparser knows which Python function it should execute. For
1427 example::
1428
1429 >>> # sub-command functions
1430 >>> def foo(args):
Benjamin Petersonb2deb112010-03-03 02:09:18 +00001431 ... print(args.x * args.y)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001432 ...
1433 >>> def bar(args):
Benjamin Petersonb2deb112010-03-03 02:09:18 +00001434 ... print('((%s))' % args.z)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001435 ...
1436 >>> # create the top-level parser
1437 >>> parser = argparse.ArgumentParser()
1438 >>> subparsers = parser.add_subparsers()
1439 >>>
1440 >>> # create the parser for the "foo" command
1441 >>> parser_foo = subparsers.add_parser('foo')
1442 >>> parser_foo.add_argument('-x', type=int, default=1)
1443 >>> parser_foo.add_argument('y', type=float)
1444 >>> parser_foo.set_defaults(func=foo)
1445 >>>
1446 >>> # create the parser for the "bar" command
1447 >>> parser_bar = subparsers.add_parser('bar')
1448 >>> parser_bar.add_argument('z')
1449 >>> parser_bar.set_defaults(func=bar)
1450 >>>
1451 >>> # parse the args and call whatever function was selected
1452 >>> args = parser.parse_args('foo 1 -x 2'.split())
1453 >>> args.func(args)
1454 2.0
1455 >>>
1456 >>> # parse the args and call whatever function was selected
1457 >>> args = parser.parse_args('bar XYZYX'.split())
1458 >>> args.func(args)
1459 ((XYZYX))
1460
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001461 This way, you can let :meth:`parse_args` does the job of calling the
1462 appropriate function after argument parsing is complete. Associating
1463 functions with actions like this is typically the easiest way to handle the
1464 different actions for each of your subparsers. However, if it is necessary
1465 to check the name of the subparser that was invoked, the ``dest`` keyword
1466 argument to the :meth:`add_subparsers` call will work::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001467
1468 >>> parser = argparse.ArgumentParser()
1469 >>> subparsers = parser.add_subparsers(dest='subparser_name')
1470 >>> subparser1 = subparsers.add_parser('1')
1471 >>> subparser1.add_argument('-x')
1472 >>> subparser2 = subparsers.add_parser('2')
1473 >>> subparser2.add_argument('y')
1474 >>> parser.parse_args(['2', 'frobble'])
1475 Namespace(subparser_name='2', y='frobble')
1476
1477
1478FileType objects
1479^^^^^^^^^^^^^^^^
1480
1481.. class:: FileType(mode='r', bufsize=None)
1482
1483 The :class:`FileType` factory creates objects that can be passed to the type
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001484 argument of :meth:`ArgumentParser.add_argument`. Arguments that have
1485 :class:`FileType` objects as their type will open command-line args as files
1486 with the requested modes and buffer sizes:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001487
1488 >>> parser = argparse.ArgumentParser()
1489 >>> parser.add_argument('--output', type=argparse.FileType('wb', 0))
1490 >>> parser.parse_args(['--output', 'out'])
1491 Namespace(output=<open file 'out', mode 'wb' at 0x...>)
1492
1493 FileType objects understand the pseudo-argument ``'-'`` and automatically
1494 convert this into ``sys.stdin`` for readable :class:`FileType` objects and
1495 ``sys.stdout`` for writable :class:`FileType` objects:
1496
1497 >>> parser = argparse.ArgumentParser()
1498 >>> parser.add_argument('infile', type=argparse.FileType('r'))
1499 >>> parser.parse_args(['-'])
1500 Namespace(infile=<open file '<stdin>', mode 'r' at 0x...>)
1501
1502
1503Argument groups
1504^^^^^^^^^^^^^^^
1505
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001506.. method:: ArgumentParser.add_argument_group([title], [description])
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001507
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001508 By default, :class:`ArgumentParser` groups command-line arguments into
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001509 "positional arguments" and "optional arguments" when displaying help
1510 messages. When there is a better conceptual grouping of arguments than this
1511 default one, appropriate groups can be created using the
1512 :meth:`add_argument_group` method::
1513
1514 >>> parser = argparse.ArgumentParser(prog='PROG', add_help=False)
1515 >>> group = parser.add_argument_group('group')
1516 >>> group.add_argument('--foo', help='foo help')
1517 >>> group.add_argument('bar', help='bar help')
1518 >>> parser.print_help()
1519 usage: PROG [--foo FOO] bar
1520
1521 group:
1522 bar bar help
1523 --foo FOO foo help
1524
1525 The :meth:`add_argument_group` method returns an argument group object which
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001526 has an :meth:`~ArgumentParser.add_argument` method just like a regular
1527 :class:`ArgumentParser`. When an argument is added to the group, the parser
1528 treats it just like a normal argument, but displays the argument in a
1529 separate group for help messages. The :meth:`add_argument_group` method
1530 accepts ``title`` and ``description`` arguments which can be used to
1531 customize this display::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001532
1533 >>> parser = argparse.ArgumentParser(prog='PROG', add_help=False)
1534 >>> group1 = parser.add_argument_group('group1', 'group1 description')
1535 >>> group1.add_argument('foo', help='foo help')
1536 >>> group2 = parser.add_argument_group('group2', 'group2 description')
1537 >>> group2.add_argument('--bar', help='bar help')
1538 >>> parser.print_help()
1539 usage: PROG [--bar BAR] foo
1540
1541 group1:
1542 group1 description
1543
1544 foo foo help
1545
1546 group2:
1547 group2 description
1548
1549 --bar BAR bar help
1550
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001551 Note that any arguments not your user defined groups will end up back in the
1552 usual "positional arguments" and "optional arguments" sections.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001553
1554
1555Mutual exclusion
1556^^^^^^^^^^^^^^^^
1557
1558.. method:: add_mutually_exclusive_group([required=False])
1559
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001560 Create a mutually exclusive group. argparse will make sure that only one of
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001561 the arguments in the mutually exclusive group was present on the command
1562 line::
1563
1564 >>> parser = argparse.ArgumentParser(prog='PROG')
1565 >>> group = parser.add_mutually_exclusive_group()
1566 >>> group.add_argument('--foo', action='store_true')
1567 >>> group.add_argument('--bar', action='store_false')
1568 >>> parser.parse_args(['--foo'])
1569 Namespace(bar=True, foo=True)
1570 >>> parser.parse_args(['--bar'])
1571 Namespace(bar=False, foo=False)
1572 >>> parser.parse_args(['--foo', '--bar'])
1573 usage: PROG [-h] [--foo | --bar]
1574 PROG: error: argument --bar: not allowed with argument --foo
1575
1576 The :meth:`add_mutually_exclusive_group` method also accepts a ``required``
1577 argument, to indicate that at least one of the mutually exclusive arguments
1578 is required::
1579
1580 >>> parser = argparse.ArgumentParser(prog='PROG')
1581 >>> group = parser.add_mutually_exclusive_group(required=True)
1582 >>> group.add_argument('--foo', action='store_true')
1583 >>> group.add_argument('--bar', action='store_false')
1584 >>> parser.parse_args([])
1585 usage: PROG [-h] (--foo | --bar)
1586 PROG: error: one of the arguments --foo --bar is required
1587
1588 Note that currently mutually exclusive argument groups do not support the
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001589 ``title`` and ``description`` arguments of :meth:`add_argument_group`.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001590
1591
1592Parser defaults
1593^^^^^^^^^^^^^^^
1594
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001595.. method:: ArgumentParser.set_defaults(**kwargs)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001596
1597 Most of the time, the attributes of the object returned by :meth:`parse_args`
1598 will be fully determined by inspecting the command-line args and the argument
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001599 actions. :meth:`ArgumentParser.set_defaults` allows some additional
1600 attributes that are determined without any inspection of the command-line to
1601 be added::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001602
1603 >>> parser = argparse.ArgumentParser()
1604 >>> parser.add_argument('foo', type=int)
1605 >>> parser.set_defaults(bar=42, baz='badger')
1606 >>> parser.parse_args(['736'])
1607 Namespace(bar=42, baz='badger', foo=736)
1608
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001609 Note that parser-level defaults always override argument-level defaults::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001610
1611 >>> parser = argparse.ArgumentParser()
1612 >>> parser.add_argument('--foo', default='bar')
1613 >>> parser.set_defaults(foo='spam')
1614 >>> parser.parse_args([])
1615 Namespace(foo='spam')
1616
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001617 Parser-level defaults can be particularly useful when working with multiple
1618 parsers. See the :meth:`~ArgumentParser.add_subparsers` method for an
1619 example of this type.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001620
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001621.. method:: ArgumentParser.get_default(dest)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001622
1623 Get the default value for a namespace attribute, as set by either
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001624 :meth:`~ArgumentParser.add_argument` or by
1625 :meth:`~ArgumentParser.set_defaults`::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001626
1627 >>> parser = argparse.ArgumentParser()
1628 >>> parser.add_argument('--foo', default='badger')
1629 >>> parser.get_default('foo')
1630 'badger'
1631
1632
1633Printing help
1634^^^^^^^^^^^^^
1635
1636In most typical applications, :meth:`parse_args` will take care of formatting
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001637and printing any usage or error messages. However, several formatting methods
1638are available:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001639
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001640.. method:: ArgumentParser.print_usage([file]):
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001641
1642 Print a brief description of how the :class:`ArgumentParser` should be
1643 invoked on the command line. If ``file`` is not present, ``sys.stderr`` is
1644 assumed.
1645
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001646.. method:: ArgumentParser.print_help([file]):
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001647
1648 Print a help message, including the program usage and information about the
1649 arguments registered with the :class:`ArgumentParser`. If ``file`` is not
1650 present, ``sys.stderr`` is assumed.
1651
1652There are also variants of these methods that simply return a string instead of
1653printing it:
1654
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001655.. method:: ArgumentParser.format_usage():
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001656
1657 Return a string containing a brief description of how the
1658 :class:`ArgumentParser` should be invoked on the command line.
1659
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001660.. method:: ArgumentParser.format_help():
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001661
1662 Return a string containing a help message, including the program usage and
1663 information about the arguments registered with the :class:`ArgumentParser`.
1664
1665
1666
1667Partial parsing
1668^^^^^^^^^^^^^^^
1669
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001670.. method:: ArgumentParser.parse_known_args([args], [namespace])
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001671
1672Sometimes a script may only parse a few of the command line arguments, passing
1673the remaining arguments on to another script or program. In these cases, the
1674:meth:`parse_known_args` method can be useful. It works much like
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001675:meth:`~ArgumentParser.parse_args` except that it does not produce an error when
1676extra arguments are present. Instead, it returns a two item tuple containing
1677the populated namespace and the list of remaining argument strings.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001678
1679::
1680
1681 >>> parser = argparse.ArgumentParser()
1682 >>> parser.add_argument('--foo', action='store_true')
1683 >>> parser.add_argument('bar')
1684 >>> parser.parse_known_args(['--foo', '--badger', 'BAR', 'spam'])
1685 (Namespace(bar='BAR', foo=True), ['--badger', 'spam'])
1686
1687
1688Customizing file parsing
1689^^^^^^^^^^^^^^^^^^^^^^^^
1690
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001691.. method:: ArgumentParser.convert_arg_line_to_args(arg_line)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001692
1693 Arguments that are read from a file (see the ``fromfile_prefix_chars``
1694 keyword argument to the :class:`ArgumentParser` constructor) are read one
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001695 argument per line. :meth:`convert_arg_line_to_args` can be overriden for
1696 fancier reading.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001697
1698 This method takes a single argument ``arg_line`` which is a string read from
1699 the argument file. It returns a list of arguments parsed from this string.
1700 The method is called once per line read from the argument file, in order.
1701
1702 A useful override of this method is one that treats each space-separated word
1703 as an argument::
1704
1705 def convert_arg_line_to_args(self, arg_line):
1706 for arg in arg_line.split():
1707 if not arg.strip():
1708 continue
1709 yield arg
1710
1711
1712Upgrading optparse code
1713-----------------------
1714
1715Originally, the argparse module had attempted to maintain compatibility with
1716optparse. However, optparse was difficult to extend transparently, particularly
1717with the changes required to support the new ``nargs=`` specifiers and better
Georg Brandl386bc6d2010-04-25 10:19:53 +00001718usage messages. When most everything in optparse had either been copy-pasted
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001719over or monkey-patched, it no longer seemed practical to try to maintain the
1720backwards compatibility.
1721
1722A partial upgrade path from optparse to argparse:
1723
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001724* Replace all ``add_option()`` calls with :meth:`ArgumentParser.add_argument` calls.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001725
1726* Replace ``options, args = parser.parse_args()`` with ``args =
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001727 parser.parse_args()`` and add additional :meth:`ArgumentParser.add_argument` calls for the
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001728 positional arguments.
1729
1730* Replace callback actions and the ``callback_*`` keyword arguments with
1731 ``type`` or ``action`` arguments.
1732
1733* Replace string names for ``type`` keyword arguments with the corresponding
1734 type objects (e.g. int, float, complex, etc).
1735
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001736* Replace :class:`optparse.Values` with :class:`Namespace` and
1737 :exc:`optparse.OptionError` and :exc:`optparse.OptionValueError` with
1738 :exc:`ArgumentError`.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001739
1740* Replace strings with implicit arguments such as ``%default`` or ``%prog`` with
1741 the standard python syntax to use dictionaries to format strings, that is,
1742 ``%(default)s`` and ``%(prog)s``.
Steven Bethard59710962010-05-24 03:21:08 +00001743
1744* Replace the OptionParser constructor ``version`` argument with a call to
1745 ``parser.add_argument('--version', action='version', version='<the version>')``