blob: d907203a027c458934de61b87d01793f1c4d45d8 [file] [log] [blame]
Georg Brandl69518bc2011-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
Éric Araujod9d7bca2011-08-10 04:19:03 +02005 :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.. versionadded:: 3.2
10
Éric Araujo19f9b712011-08-19 00:49:18 +020011**Source code:** :source:`Lib/argparse.py`
12
Raymond Hettingera1993682011-01-27 01:20:32 +000013--------------
Benjamin Peterson698a18a2010-03-02 22:34:37 +000014
Ezio Melotti6cc7a412012-05-06 16:15:35 +030015.. sidebar:: Tutorial
16
17 This page contains the API reference information. For a more gentle
18 introduction to Python command-line parsing, have a look at the
19 :ref:`argparse tutorial <argparse-tutorial>`.
20
Ezio Melotti2409d772011-04-16 23:13:50 +030021The :mod:`argparse` module makes it easy to write user-friendly command-line
Benjamin Peterson98047eb2010-03-03 02:07:08 +000022interfaces. The program defines what arguments it requires, and :mod:`argparse`
Benjamin Peterson698a18a2010-03-02 22:34:37 +000023will figure out how to parse those out of :data:`sys.argv`. The :mod:`argparse`
Benjamin Peterson98047eb2010-03-03 02:07:08 +000024module also automatically generates help and usage messages and issues errors
25when users give the program invalid arguments.
Benjamin Peterson698a18a2010-03-02 22:34:37 +000026
Georg Brandle0bf91d2010-10-17 10:34:28 +000027
Benjamin Peterson698a18a2010-03-02 22:34:37 +000028Example
29-------
30
Benjamin Peterson98047eb2010-03-03 02:07:08 +000031The following code is a Python program that takes a list of integers and
32produces either the sum or the max::
Benjamin Peterson698a18a2010-03-02 22:34:37 +000033
34 import argparse
35
36 parser = argparse.ArgumentParser(description='Process some integers.')
37 parser.add_argument('integers', metavar='N', type=int, nargs='+',
38 help='an integer for the accumulator')
39 parser.add_argument('--sum', dest='accumulate', action='store_const',
40 const=sum, default=max,
41 help='sum the integers (default: find the max)')
42
43 args = parser.parse_args()
Benjamin Petersonb2deb112010-03-03 02:09:18 +000044 print(args.accumulate(args.integers))
Benjamin Peterson698a18a2010-03-02 22:34:37 +000045
46Assuming the Python code above is saved into a file called ``prog.py``, it can
47be run at the command line and provides useful help messages::
48
Georg Brandl29fc4bf2013-10-06 19:33:56 +020049 $ python prog.py -h
Benjamin Peterson698a18a2010-03-02 22:34:37 +000050 usage: prog.py [-h] [--sum] N [N ...]
51
52 Process some integers.
53
54 positional arguments:
55 N an integer for the accumulator
56
57 optional arguments:
58 -h, --help show this help message and exit
59 --sum sum the integers (default: find the max)
60
61When run with the appropriate arguments, it prints either the sum or the max of
62the command-line integers::
63
Georg Brandl29fc4bf2013-10-06 19:33:56 +020064 $ python prog.py 1 2 3 4
Benjamin Peterson698a18a2010-03-02 22:34:37 +000065 4
66
Georg Brandl29fc4bf2013-10-06 19:33:56 +020067 $ python prog.py 1 2 3 4 --sum
Benjamin Peterson698a18a2010-03-02 22:34:37 +000068 10
69
70If invalid arguments are passed in, it will issue an error::
71
Georg Brandl29fc4bf2013-10-06 19:33:56 +020072 $ python prog.py a b c
Benjamin Peterson698a18a2010-03-02 22:34:37 +000073 usage: prog.py [-h] [--sum] N [N ...]
74 prog.py: error: argument N: invalid int value: 'a'
75
76The following sections walk you through this example.
77
Georg Brandle0bf91d2010-10-17 10:34:28 +000078
Benjamin Peterson698a18a2010-03-02 22:34:37 +000079Creating a parser
80^^^^^^^^^^^^^^^^^
81
Benjamin Peterson2614cda2010-03-21 22:36:19 +000082The first step in using the :mod:`argparse` is creating an
Benjamin Peterson98047eb2010-03-03 02:07:08 +000083:class:`ArgumentParser` object::
Benjamin Peterson698a18a2010-03-02 22:34:37 +000084
85 >>> parser = argparse.ArgumentParser(description='Process some integers.')
86
87The :class:`ArgumentParser` object will hold all the information necessary to
Ezio Melotticca4ef82011-04-21 15:26:46 +030088parse the command line into Python data types.
Benjamin Peterson698a18a2010-03-02 22:34:37 +000089
90
91Adding arguments
92^^^^^^^^^^^^^^^^
93
Benjamin Peterson98047eb2010-03-03 02:07:08 +000094Filling an :class:`ArgumentParser` with information about program arguments is
95done by making calls to the :meth:`~ArgumentParser.add_argument` method.
96Generally, these calls tell the :class:`ArgumentParser` how to take the strings
97on the command line and turn them into objects. This information is stored and
98used when :meth:`~ArgumentParser.parse_args` is called. For example::
Benjamin Peterson698a18a2010-03-02 22:34:37 +000099
100 >>> parser.add_argument('integers', metavar='N', type=int, nargs='+',
101 ... help='an integer for the accumulator')
102 >>> parser.add_argument('--sum', dest='accumulate', action='store_const',
103 ... const=sum, default=max,
104 ... help='sum the integers (default: find the max)')
105
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300106Later, calling :meth:`~ArgumentParser.parse_args` will return an object with
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000107two attributes, ``integers`` and ``accumulate``. The ``integers`` attribute
108will be a list of one or more ints, and the ``accumulate`` attribute will be
109either the :func:`sum` function, if ``--sum`` was specified at the command line,
110or the :func:`max` function if it was not.
111
Georg Brandle0bf91d2010-10-17 10:34:28 +0000112
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000113Parsing arguments
114^^^^^^^^^^^^^^^^^
115
Éric Araujod9d7bca2011-08-10 04:19:03 +0200116:class:`ArgumentParser` parses arguments through the
Georg Brandl69518bc2011-04-16 16:44:54 +0200117:meth:`~ArgumentParser.parse_args` method. This will inspect the command line,
Éric Araujofde92422011-08-19 01:30:26 +0200118convert each argument to the appropriate type and then invoke the appropriate action.
Éric Araujo63b18a42011-07-29 17:59:17 +0200119In most cases, this means a simple :class:`Namespace` object will be built up from
Georg Brandl69518bc2011-04-16 16:44:54 +0200120attributes parsed out of the command line::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000121
122 >>> parser.parse_args(['--sum', '7', '-1', '42'])
123 Namespace(accumulate=<built-in function sum>, integers=[7, -1, 42])
124
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000125In a script, :meth:`~ArgumentParser.parse_args` will typically be called with no
126arguments, and the :class:`ArgumentParser` will automatically determine the
Éric Araujod9d7bca2011-08-10 04:19:03 +0200127command-line arguments from :data:`sys.argv`.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000128
129
130ArgumentParser objects
131----------------------
132
Ezio Melottie0add762012-09-14 06:32:35 +0300133.. class:: ArgumentParser(prog=None, usage=None, description=None, \
134 epilog=None, parents=[], \
135 formatter_class=argparse.HelpFormatter, \
136 prefix_chars='-', fromfile_prefix_chars=None, \
137 argument_default=None, conflict_handler='error', \
138 add_help=True)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000139
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300140 Create a new :class:`ArgumentParser` object. All parameters should be passed
141 as keyword arguments. Each parameter has its own more detailed description
142 below, but in short they are:
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000143
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300144 * prog_ - The name of the program (default: ``sys.argv[0]``)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000145
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300146 * usage_ - The string describing the program usage (default: generated from
147 arguments added to parser)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000148
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300149 * description_ - Text to display before the argument help (default: none)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000150
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300151 * epilog_ - Text to display after the argument help (default: none)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000152
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000153 * parents_ - A list of :class:`ArgumentParser` objects whose arguments should
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300154 also be included
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000155
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300156 * formatter_class_ - A class for customizing the help output
157
158 * prefix_chars_ - The set of characters that prefix optional arguments
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000159 (default: '-')
160
161 * fromfile_prefix_chars_ - The set of characters that prefix files from
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300162 which additional arguments should be read (default: ``None``)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000163
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300164 * argument_default_ - The global default value for arguments
165 (default: ``None``)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000166
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300167 * conflict_handler_ - The strategy for resolving conflicting optionals
168 (usually unnecessary)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000169
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300170 * add_help_ - Add a -h/--help option to the parser (default: ``True``)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000171
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000172The following sections describe how each of these are used.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000173
174
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300175prog
176^^^^
177
178By default, :class:`ArgumentParser` objects uses ``sys.argv[0]`` to determine
179how to display the name of the program in help messages. This default is almost
180always desirable because it will make the help messages match how the program was
181invoked on the command line. For example, consider a file named
182``myprogram.py`` with the following code::
183
184 import argparse
185 parser = argparse.ArgumentParser()
186 parser.add_argument('--foo', help='foo help')
187 args = parser.parse_args()
188
189The help for this program will display ``myprogram.py`` as the program name
190(regardless of where the program was invoked from)::
191
192 $ python myprogram.py --help
193 usage: myprogram.py [-h] [--foo FOO]
194
195 optional arguments:
196 -h, --help show this help message and exit
197 --foo FOO foo help
198 $ cd ..
199 $ python subdir\myprogram.py --help
200 usage: myprogram.py [-h] [--foo FOO]
201
202 optional arguments:
203 -h, --help show this help message and exit
204 --foo FOO foo help
205
206To change this default behavior, another value can be supplied using the
207``prog=`` argument to :class:`ArgumentParser`::
208
209 >>> parser = argparse.ArgumentParser(prog='myprogram')
210 >>> parser.print_help()
211 usage: myprogram [-h]
212
213 optional arguments:
214 -h, --help show this help message and exit
215
216Note that the program name, whether determined from ``sys.argv[0]`` or from the
217``prog=`` argument, is available to help messages using the ``%(prog)s`` format
218specifier.
219
220::
221
222 >>> parser = argparse.ArgumentParser(prog='myprogram')
223 >>> parser.add_argument('--foo', help='foo of the %(prog)s program')
224 >>> parser.print_help()
225 usage: myprogram [-h] [--foo FOO]
226
227 optional arguments:
228 -h, --help show this help message and exit
229 --foo FOO foo of the myprogram program
230
231
232usage
233^^^^^
234
235By default, :class:`ArgumentParser` calculates the usage message from the
236arguments it contains::
237
238 >>> parser = argparse.ArgumentParser(prog='PROG')
239 >>> parser.add_argument('--foo', nargs='?', help='foo help')
240 >>> parser.add_argument('bar', nargs='+', help='bar help')
241 >>> parser.print_help()
242 usage: PROG [-h] [--foo [FOO]] bar [bar ...]
243
244 positional arguments:
245 bar bar help
246
247 optional arguments:
248 -h, --help show this help message and exit
249 --foo [FOO] foo help
250
251The default message can be overridden with the ``usage=`` keyword argument::
252
253 >>> parser = argparse.ArgumentParser(prog='PROG', usage='%(prog)s [options]')
254 >>> parser.add_argument('--foo', nargs='?', help='foo help')
255 >>> parser.add_argument('bar', nargs='+', help='bar help')
256 >>> parser.print_help()
257 usage: PROG [options]
258
259 positional arguments:
260 bar bar help
261
262 optional arguments:
263 -h, --help show this help message and exit
264 --foo [FOO] foo help
265
266The ``%(prog)s`` format specifier is available to fill in the program name in
267your usage messages.
268
269
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000270description
271^^^^^^^^^^^
272
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000273Most calls to the :class:`ArgumentParser` constructor will use the
274``description=`` keyword argument. This argument gives a brief description of
275what the program does and how it works. In help messages, the description is
276displayed between the command-line usage string and the help messages for the
277various arguments::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000278
279 >>> parser = argparse.ArgumentParser(description='A foo that bars')
280 >>> parser.print_help()
281 usage: argparse.py [-h]
282
283 A foo that bars
284
285 optional arguments:
286 -h, --help show this help message and exit
287
288By default, the description will be line-wrapped so that it fits within the
289given space. To change this behavior, see the formatter_class_ argument.
290
291
292epilog
293^^^^^^
294
295Some programs like to display additional description of the program after the
296description of the arguments. Such text can be specified using the ``epilog=``
297argument to :class:`ArgumentParser`::
298
299 >>> parser = argparse.ArgumentParser(
300 ... description='A foo that bars',
301 ... epilog="And that's how you'd foo a bar")
302 >>> parser.print_help()
303 usage: argparse.py [-h]
304
305 A foo that bars
306
307 optional arguments:
308 -h, --help show this help message and exit
309
310 And that's how you'd foo a bar
311
312As with the description_ argument, the ``epilog=`` text is by default
313line-wrapped, but this behavior can be adjusted with the formatter_class_
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000314argument to :class:`ArgumentParser`.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000315
316
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000317parents
318^^^^^^^
319
320Sometimes, several parsers share a common set of arguments. Rather than
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000321repeating the definitions of these arguments, a single parser with all the
322shared arguments and passed to ``parents=`` argument to :class:`ArgumentParser`
323can be used. The ``parents=`` argument takes a list of :class:`ArgumentParser`
324objects, collects all the positional and optional actions from them, and adds
325these actions to the :class:`ArgumentParser` object being constructed::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000326
327 >>> parent_parser = argparse.ArgumentParser(add_help=False)
328 >>> parent_parser.add_argument('--parent', type=int)
329
330 >>> foo_parser = argparse.ArgumentParser(parents=[parent_parser])
331 >>> foo_parser.add_argument('foo')
332 >>> foo_parser.parse_args(['--parent', '2', 'XXX'])
333 Namespace(foo='XXX', parent=2)
334
335 >>> bar_parser = argparse.ArgumentParser(parents=[parent_parser])
336 >>> bar_parser.add_argument('--bar')
337 >>> bar_parser.parse_args(['--bar', 'YYY'])
338 Namespace(bar='YYY', parent=None)
339
340Note that most parent parsers will specify ``add_help=False``. Otherwise, the
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000341:class:`ArgumentParser` will see two ``-h/--help`` options (one in the parent
342and one in the child) and raise an error.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000343
Steven Bethardd186f992011-03-26 21:49:00 +0100344.. note::
345 You must fully initialize the parsers before passing them via ``parents=``.
346 If you change the parent parsers after the child parser, those changes will
347 not be reflected in the child.
348
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000349
350formatter_class
351^^^^^^^^^^^^^^^
352
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000353:class:`ArgumentParser` objects allow the help formatting to be customized by
Ezio Melotti707d1e62011-04-22 01:57:47 +0300354specifying an alternate formatting class. Currently, there are four such
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300355classes:
356
357.. class:: RawDescriptionHelpFormatter
358 RawTextHelpFormatter
359 ArgumentDefaultsHelpFormatter
Ezio Melotti707d1e62011-04-22 01:57:47 +0300360 MetavarTypeHelpFormatter
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000361
Steven Bethard0331e902011-03-26 14:48:04 +0100362:class:`RawDescriptionHelpFormatter` and :class:`RawTextHelpFormatter` give
363more control over how textual descriptions are displayed.
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000364By default, :class:`ArgumentParser` objects line-wrap the description_ and
365epilog_ texts in command-line help messages::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000366
367 >>> parser = argparse.ArgumentParser(
368 ... prog='PROG',
369 ... description='''this description
370 ... was indented weird
371 ... but that is okay''',
372 ... epilog='''
373 ... likewise for this epilog whose whitespace will
374 ... be cleaned up and whose words will be wrapped
375 ... across a couple lines''')
376 >>> parser.print_help()
377 usage: PROG [-h]
378
379 this description was indented weird but that is okay
380
381 optional arguments:
382 -h, --help show this help message and exit
383
384 likewise for this epilog whose whitespace will be cleaned up and whose words
385 will be wrapped across a couple lines
386
Steven Bethard0331e902011-03-26 14:48:04 +0100387Passing :class:`RawDescriptionHelpFormatter` as ``formatter_class=``
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000388indicates that description_ and epilog_ are already correctly formatted and
389should not be line-wrapped::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000390
391 >>> parser = argparse.ArgumentParser(
392 ... prog='PROG',
393 ... formatter_class=argparse.RawDescriptionHelpFormatter,
394 ... description=textwrap.dedent('''\
395 ... Please do not mess up this text!
396 ... --------------------------------
397 ... I have indented it
398 ... exactly the way
399 ... I want it
400 ... '''))
401 >>> parser.print_help()
402 usage: PROG [-h]
403
404 Please do not mess up this text!
405 --------------------------------
406 I have indented it
407 exactly the way
408 I want it
409
410 optional arguments:
411 -h, --help show this help message and exit
412
Steven Bethard0331e902011-03-26 14:48:04 +0100413:class:`RawTextHelpFormatter` maintains whitespace for all sorts of help text,
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000414including argument descriptions.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000415
Steven Bethard0331e902011-03-26 14:48:04 +0100416:class:`ArgumentDefaultsHelpFormatter` automatically adds information about
417default values to each of the argument help messages::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000418
419 >>> parser = argparse.ArgumentParser(
420 ... prog='PROG',
421 ... formatter_class=argparse.ArgumentDefaultsHelpFormatter)
422 >>> parser.add_argument('--foo', type=int, default=42, help='FOO!')
423 >>> parser.add_argument('bar', nargs='*', default=[1, 2, 3], help='BAR!')
424 >>> parser.print_help()
425 usage: PROG [-h] [--foo FOO] [bar [bar ...]]
426
427 positional arguments:
428 bar BAR! (default: [1, 2, 3])
429
430 optional arguments:
431 -h, --help show this help message and exit
432 --foo FOO FOO! (default: 42)
433
Steven Bethard0331e902011-03-26 14:48:04 +0100434:class:`MetavarTypeHelpFormatter` uses the name of the type_ argument for each
Ezio Melottif1064492011-10-19 11:06:26 +0300435argument as the display name for its values (rather than using the dest_
Steven Bethard0331e902011-03-26 14:48:04 +0100436as the regular formatter does)::
437
438 >>> parser = argparse.ArgumentParser(
439 ... prog='PROG',
440 ... formatter_class=argparse.MetavarTypeHelpFormatter)
441 >>> parser.add_argument('--foo', type=int)
442 >>> parser.add_argument('bar', type=float)
443 >>> parser.print_help()
444 usage: PROG [-h] [--foo int] float
445
446 positional arguments:
447 float
448
449 optional arguments:
450 -h, --help show this help message and exit
451 --foo int
452
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000453
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300454prefix_chars
455^^^^^^^^^^^^
456
457Most command-line options will use ``-`` as the prefix, e.g. ``-f/--foo``.
458Parsers that need to support different or additional prefix
459characters, e.g. for options
460like ``+f`` or ``/foo``, may specify them using the ``prefix_chars=`` argument
461to the ArgumentParser constructor::
462
463 >>> parser = argparse.ArgumentParser(prog='PROG', prefix_chars='-+')
464 >>> parser.add_argument('+f')
465 >>> parser.add_argument('++bar')
466 >>> parser.parse_args('+f X ++bar Y'.split())
467 Namespace(bar='Y', f='X')
468
469The ``prefix_chars=`` argument defaults to ``'-'``. Supplying a set of
470characters that does not include ``-`` will cause ``-f/--foo`` options to be
471disallowed.
472
473
474fromfile_prefix_chars
475^^^^^^^^^^^^^^^^^^^^^
476
477Sometimes, for example when dealing with a particularly long argument lists, it
478may make sense to keep the list of arguments in a file rather than typing it out
479at the command line. If the ``fromfile_prefix_chars=`` argument is given to the
480:class:`ArgumentParser` constructor, then arguments that start with any of the
481specified characters will be treated as files, and will be replaced by the
482arguments they contain. For example::
483
484 >>> with open('args.txt', 'w') as fp:
485 ... fp.write('-f\nbar')
486 >>> parser = argparse.ArgumentParser(fromfile_prefix_chars='@')
487 >>> parser.add_argument('-f')
488 >>> parser.parse_args(['-f', 'foo', '@args.txt'])
489 Namespace(f='bar')
490
491Arguments read from a file must by default be one per line (but see also
492:meth:`~ArgumentParser.convert_arg_line_to_args`) and are treated as if they
493were in the same place as the original file referencing argument on the command
494line. So in the example above, the expression ``['-f', 'foo', '@args.txt']``
495is considered equivalent to the expression ``['-f', 'foo', '-f', 'bar']``.
496
497The ``fromfile_prefix_chars=`` argument defaults to ``None``, meaning that
498arguments will never be treated as file references.
499
500
501argument_default
502^^^^^^^^^^^^^^^^
503
504Generally, argument defaults are specified either by passing a default to
505:meth:`~ArgumentParser.add_argument` or by calling the
506:meth:`~ArgumentParser.set_defaults` methods with a specific set of name-value
507pairs. Sometimes however, it may be useful to specify a single parser-wide
508default for arguments. This can be accomplished by passing the
509``argument_default=`` keyword argument to :class:`ArgumentParser`. For example,
510to globally suppress attribute creation on :meth:`~ArgumentParser.parse_args`
511calls, we supply ``argument_default=SUPPRESS``::
512
513 >>> parser = argparse.ArgumentParser(argument_default=argparse.SUPPRESS)
514 >>> parser.add_argument('--foo')
515 >>> parser.add_argument('bar', nargs='?')
516 >>> parser.parse_args(['--foo', '1', 'BAR'])
517 Namespace(bar='BAR', foo='1')
518 >>> parser.parse_args([])
519 Namespace()
520
521
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000522conflict_handler
523^^^^^^^^^^^^^^^^
524
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000525:class:`ArgumentParser` objects do not allow two actions with the same option
526string. By default, :class:`ArgumentParser` objects raises an exception if an
527attempt is made to create an argument with an option string that is already in
528use::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000529
530 >>> parser = argparse.ArgumentParser(prog='PROG')
531 >>> parser.add_argument('-f', '--foo', help='old foo help')
532 >>> parser.add_argument('--foo', help='new foo help')
533 Traceback (most recent call last):
534 ..
535 ArgumentError: argument --foo: conflicting option string(s): --foo
536
537Sometimes (e.g. when using parents_) it may be useful to simply override any
538older arguments with the same option string. To get this behavior, the value
539``'resolve'`` can be supplied to the ``conflict_handler=`` argument of
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000540:class:`ArgumentParser`::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000541
542 >>> parser = argparse.ArgumentParser(prog='PROG', conflict_handler='resolve')
543 >>> parser.add_argument('-f', '--foo', help='old foo help')
544 >>> parser.add_argument('--foo', help='new foo help')
545 >>> parser.print_help()
546 usage: PROG [-h] [-f FOO] [--foo FOO]
547
548 optional arguments:
549 -h, --help show this help message and exit
550 -f FOO old foo help
551 --foo FOO new foo help
552
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000553Note that :class:`ArgumentParser` objects only remove an action if all of its
554option strings are overridden. So, in the example above, the old ``-f/--foo``
555action is retained as the ``-f`` action, because only the ``--foo`` option
556string was overridden.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000557
558
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300559add_help
560^^^^^^^^
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000561
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300562By default, ArgumentParser objects add an option which simply displays
563the parser's help message. For example, consider a file named
564``myprogram.py`` containing the following code::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000565
566 import argparse
567 parser = argparse.ArgumentParser()
568 parser.add_argument('--foo', help='foo help')
569 args = parser.parse_args()
570
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300571If ``-h`` or ``--help`` is supplied at the command line, the ArgumentParser
572help will be printed::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000573
574 $ python myprogram.py --help
575 usage: myprogram.py [-h] [--foo FOO]
576
577 optional arguments:
578 -h, --help show this help message and exit
579 --foo FOO foo help
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000580
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300581Occasionally, it may be useful to disable the addition of this help option.
582This can be achieved by passing ``False`` as the ``add_help=`` argument to
583:class:`ArgumentParser`::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000584
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300585 >>> parser = argparse.ArgumentParser(prog='PROG', add_help=False)
586 >>> parser.add_argument('--foo', help='foo help')
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000587 >>> parser.print_help()
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300588 usage: PROG [--foo FOO]
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000589
590 optional arguments:
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300591 --foo FOO foo help
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000592
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300593The help option is typically ``-h/--help``. The exception to this is
594if the ``prefix_chars=`` is specified and does not include ``-``, in
595which case ``-h`` and ``--help`` are not valid options. In
596this case, the first character in ``prefix_chars`` is used to prefix
597the help options::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000598
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300599 >>> parser = argparse.ArgumentParser(prog='PROG', prefix_chars='+/')
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000600 >>> parser.print_help()
Georg Brandld2914ce2013-10-06 09:50:36 +0200601 usage: PROG [+h]
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000602
603 optional arguments:
Georg Brandld2914ce2013-10-06 09:50:36 +0200604 +h, ++help show this help message and exit
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000605
606
607The add_argument() method
608-------------------------
609
Georg Brandlc9007082011-01-09 09:04:08 +0000610.. method:: ArgumentParser.add_argument(name or flags..., [action], [nargs], \
611 [const], [default], [type], [choices], [required], \
612 [help], [metavar], [dest])
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000613
Georg Brandl69518bc2011-04-16 16:44:54 +0200614 Define how a single command-line argument should be parsed. Each parameter
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000615 has its own more detailed description below, but in short they are:
616
617 * `name or flags`_ - Either a name or a list of option strings, e.g. ``foo``
Ezio Melottidca309d2011-04-21 23:09:27 +0300618 or ``-f, --foo``.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000619
620 * action_ - The basic type of action to be taken when this argument is
Georg Brandl69518bc2011-04-16 16:44:54 +0200621 encountered at the command line.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000622
623 * nargs_ - The number of command-line arguments that should be consumed.
624
625 * const_ - A constant value required by some action_ and nargs_ selections.
626
627 * default_ - The value produced if the argument is absent from the
Georg Brandl69518bc2011-04-16 16:44:54 +0200628 command line.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000629
Ezio Melotti2409d772011-04-16 23:13:50 +0300630 * type_ - The type to which the command-line argument should be converted.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000631
632 * choices_ - A container of the allowable values for the argument.
633
634 * required_ - Whether or not the command-line option may be omitted
635 (optionals only).
636
637 * help_ - A brief description of what the argument does.
638
639 * metavar_ - A name for the argument in usage messages.
640
641 * dest_ - The name of the attribute to be added to the object returned by
642 :meth:`parse_args`.
643
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000644The following sections describe how each of these are used.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000645
Georg Brandle0bf91d2010-10-17 10:34:28 +0000646
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000647name or flags
648^^^^^^^^^^^^^
649
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300650The :meth:`~ArgumentParser.add_argument` method must know whether an optional
651argument, like ``-f`` or ``--foo``, or a positional argument, like a list of
652filenames, is expected. The first arguments passed to
653:meth:`~ArgumentParser.add_argument` must therefore be either a series of
654flags, or a simple argument name. For example, an optional argument could
655be created like::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000656
657 >>> parser.add_argument('-f', '--foo')
658
659while a positional argument could be created like::
660
661 >>> parser.add_argument('bar')
662
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300663When :meth:`~ArgumentParser.parse_args` is called, optional arguments will be
664identified by the ``-`` prefix, and the remaining arguments will be assumed to
665be positional::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000666
667 >>> parser = argparse.ArgumentParser(prog='PROG')
668 >>> parser.add_argument('-f', '--foo')
669 >>> parser.add_argument('bar')
670 >>> parser.parse_args(['BAR'])
671 Namespace(bar='BAR', foo=None)
672 >>> parser.parse_args(['BAR', '--foo', 'FOO'])
673 Namespace(bar='BAR', foo='FOO')
674 >>> parser.parse_args(['--foo', 'FOO'])
675 usage: PROG [-h] [-f FOO] bar
676 PROG: error: too few arguments
677
Georg Brandle0bf91d2010-10-17 10:34:28 +0000678
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000679action
680^^^^^^
681
Éric Araujod9d7bca2011-08-10 04:19:03 +0200682:class:`ArgumentParser` objects associate command-line arguments with actions. These
683actions can do just about anything with the command-line arguments associated with
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000684them, though most actions simply add an attribute to the object returned by
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300685:meth:`~ArgumentParser.parse_args`. The ``action`` keyword argument specifies
Jason R. Coombsf28cf7a2011-12-13 23:36:45 -0500686how the command-line arguments should be handled. The supplied actions are:
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000687
688* ``'store'`` - This just stores the argument's value. This is the default
Ezio Melotti2f1db7d2011-04-21 23:06:48 +0300689 action. For example::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000690
691 >>> parser = argparse.ArgumentParser()
692 >>> parser.add_argument('--foo')
693 >>> parser.parse_args('--foo 1'.split())
694 Namespace(foo='1')
695
696* ``'store_const'`` - This stores the value specified by the const_ keyword
Ezio Melotti2f1db7d2011-04-21 23:06:48 +0300697 argument. (Note that the const_ keyword argument defaults to the rather
698 unhelpful ``None``.) The ``'store_const'`` action is most commonly used with
699 optional arguments that specify some sort of flag. For example::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000700
701 >>> parser = argparse.ArgumentParser()
702 >>> parser.add_argument('--foo', action='store_const', const=42)
703 >>> parser.parse_args('--foo'.split())
704 Namespace(foo=42)
705
706* ``'store_true'`` and ``'store_false'`` - These store the values ``True`` and
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000707 ``False`` respectively. These are special cases of ``'store_const'``. For
708 example::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000709
710 >>> parser = argparse.ArgumentParser()
711 >>> parser.add_argument('--foo', action='store_true')
712 >>> parser.add_argument('--bar', action='store_false')
713 >>> parser.parse_args('--foo --bar'.split())
714 Namespace(bar=False, foo=True)
715
716* ``'append'`` - This stores a list, and appends each argument value to the
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000717 list. This is useful to allow an option to be specified multiple times.
718 Example usage::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000719
720 >>> parser = argparse.ArgumentParser()
721 >>> parser.add_argument('--foo', action='append')
722 >>> parser.parse_args('--foo 1 --foo 2'.split())
723 Namespace(foo=['1', '2'])
724
725* ``'append_const'`` - This stores a list, and appends the value specified by
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000726 the const_ keyword argument to the list. (Note that the const_ keyword
727 argument defaults to ``None``.) The ``'append_const'`` action is typically
728 useful when multiple arguments need to store constants to the same list. For
729 example::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000730
731 >>> parser = argparse.ArgumentParser()
732 >>> parser.add_argument('--str', dest='types', action='append_const', const=str)
733 >>> parser.add_argument('--int', dest='types', action='append_const', const=int)
734 >>> parser.parse_args('--str --int'.split())
Florent Xicluna74e64952011-10-28 11:21:19 +0200735 Namespace(types=[<class 'str'>, <class 'int'>])
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000736
Sandro Tosi98492a52012-01-04 23:25:04 +0100737* ``'count'`` - This counts the number of times a keyword argument occurs. For
738 example, this is useful for increasing verbosity levels::
739
740 >>> parser = argparse.ArgumentParser()
741 >>> parser.add_argument('--verbose', '-v', action='count')
742 >>> parser.parse_args('-vvv'.split())
743 Namespace(verbose=3)
744
745* ``'help'`` - This prints a complete help message for all the options in the
746 current parser and then exits. By default a help action is automatically
747 added to the parser. See :class:`ArgumentParser` for details of how the
748 output is created.
749
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000750* ``'version'`` - This expects a ``version=`` keyword argument in the
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300751 :meth:`~ArgumentParser.add_argument` call, and prints version information
Éric Araujoc3ef0372012-02-20 01:44:55 +0100752 and exits when invoked::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000753
754 >>> import argparse
755 >>> parser = argparse.ArgumentParser(prog='PROG')
Steven Bethard59710962010-05-24 03:21:08 +0000756 >>> parser.add_argument('--version', action='version', version='%(prog)s 2.0')
757 >>> parser.parse_args(['--version'])
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000758 PROG 2.0
759
Jason R. Coombseb0ef412014-07-20 10:52:46 -0400760You may also specify an arbitrary action by passing an Action subclass or
761other object that implements the same interface. The recommended way to do
Jason R. Coombs79690ac2014-08-03 14:54:11 -0400762this is to extend :class:`Action`, overriding the ``__call__`` method
Jason R. Coombseb0ef412014-07-20 10:52:46 -0400763and optionally the ``__init__`` method.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000764
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000765An example of a custom action::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000766
767 >>> class FooAction(argparse.Action):
Jason R. Coombseb0ef412014-07-20 10:52:46 -0400768 ... def __init__(self, option_strings, dest, nargs=None, **kwargs):
769 ... if nargs is not None:
770 ... raise ValueError("nargs not allowed")
771 ... super(FooAction, self).__init__(option_strings, dest, **kwargs)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000772 ... def __call__(self, parser, namespace, values, option_string=None):
Georg Brandl571a9532010-07-26 17:00:20 +0000773 ... print('%r %r %r' % (namespace, values, option_string))
774 ... setattr(namespace, self.dest, values)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000775 ...
776 >>> parser = argparse.ArgumentParser()
777 >>> parser.add_argument('--foo', action=FooAction)
778 >>> parser.add_argument('bar', action=FooAction)
779 >>> args = parser.parse_args('1 --foo 2'.split())
780 Namespace(bar=None, foo=None) '1' None
781 Namespace(bar='1', foo=None) '2' '--foo'
782 >>> args
783 Namespace(bar='1', foo='2')
784
Jason R. Coombs79690ac2014-08-03 14:54:11 -0400785For more details, see :class:`Action`.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000786
787nargs
788^^^^^
789
790ArgumentParser objects usually associate a single command-line argument with a
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000791single action to be taken. The ``nargs`` keyword argument associates a
Ezio Melotti00f53af2011-04-21 22:56:51 +0300792different number of command-line arguments with a single action. The supported
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000793values are:
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000794
Éric Araujoc3ef0372012-02-20 01:44:55 +0100795* ``N`` (an integer). ``N`` arguments from the command line will be gathered
796 together into a list. For example::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000797
Georg Brandl682d7e02010-10-06 10:26:05 +0000798 >>> parser = argparse.ArgumentParser()
799 >>> parser.add_argument('--foo', nargs=2)
800 >>> parser.add_argument('bar', nargs=1)
801 >>> parser.parse_args('c --foo a b'.split())
802 Namespace(bar=['c'], foo=['a', 'b'])
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000803
Georg Brandl682d7e02010-10-06 10:26:05 +0000804 Note that ``nargs=1`` produces a list of one item. This is different from
805 the default, in which the item is produced by itself.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000806
Éric Araujofde92422011-08-19 01:30:26 +0200807* ``'?'``. One argument will be consumed from the command line if possible, and
808 produced as a single item. If no command-line argument is present, the value from
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000809 default_ will be produced. Note that for optional arguments, there is an
810 additional case - the option string is present but not followed by a
Éric Araujofde92422011-08-19 01:30:26 +0200811 command-line argument. In this case the value from const_ will be produced. Some
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000812 examples to illustrate this::
813
814 >>> parser = argparse.ArgumentParser()
815 >>> parser.add_argument('--foo', nargs='?', const='c', default='d')
816 >>> parser.add_argument('bar', nargs='?', default='d')
817 >>> parser.parse_args('XX --foo YY'.split())
818 Namespace(bar='XX', foo='YY')
819 >>> parser.parse_args('XX --foo'.split())
820 Namespace(bar='XX', foo='c')
821 >>> parser.parse_args(''.split())
822 Namespace(bar='d', foo='d')
823
824 One of the more common uses of ``nargs='?'`` is to allow optional input and
825 output files::
826
827 >>> parser = argparse.ArgumentParser()
Georg Brandle0bf91d2010-10-17 10:34:28 +0000828 >>> parser.add_argument('infile', nargs='?', type=argparse.FileType('r'),
829 ... default=sys.stdin)
830 >>> parser.add_argument('outfile', nargs='?', type=argparse.FileType('w'),
831 ... default=sys.stdout)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000832 >>> parser.parse_args(['input.txt', 'output.txt'])
Georg Brandl04536b02011-01-09 09:31:01 +0000833 Namespace(infile=<_io.TextIOWrapper name='input.txt' encoding='UTF-8'>,
834 outfile=<_io.TextIOWrapper name='output.txt' encoding='UTF-8'>)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000835 >>> parser.parse_args([])
Georg Brandl04536b02011-01-09 09:31:01 +0000836 Namespace(infile=<_io.TextIOWrapper name='<stdin>' encoding='UTF-8'>,
837 outfile=<_io.TextIOWrapper name='<stdout>' encoding='UTF-8'>)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000838
Éric Araujod9d7bca2011-08-10 04:19:03 +0200839* ``'*'``. All command-line arguments present are gathered into a list. Note that
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000840 it generally doesn't make much sense to have more than one positional argument
841 with ``nargs='*'``, but multiple optional arguments with ``nargs='*'`` is
842 possible. For example::
843
844 >>> parser = argparse.ArgumentParser()
845 >>> parser.add_argument('--foo', nargs='*')
846 >>> parser.add_argument('--bar', nargs='*')
847 >>> parser.add_argument('baz', nargs='*')
848 >>> parser.parse_args('a b --foo x y --bar 1 2'.split())
849 Namespace(bar=['1', '2'], baz=['a', 'b'], foo=['x', 'y'])
850
851* ``'+'``. Just like ``'*'``, all command-line args present are gathered into a
852 list. Additionally, an error message will be generated if there wasn't at
Éric Araujofde92422011-08-19 01:30:26 +0200853 least one command-line argument present. For example::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000854
855 >>> parser = argparse.ArgumentParser(prog='PROG')
856 >>> parser.add_argument('foo', nargs='+')
857 >>> parser.parse_args('a b'.split())
858 Namespace(foo=['a', 'b'])
859 >>> parser.parse_args(''.split())
860 usage: PROG [-h] foo [foo ...]
861 PROG: error: too few arguments
862
Sandro Tosida8e11a2012-01-19 22:23:00 +0100863* ``argparse.REMAINDER``. All the remaining command-line arguments are gathered
864 into a list. This is commonly useful for command line utilities that dispatch
Éric Araujoc3ef0372012-02-20 01:44:55 +0100865 to other command line utilities::
Sandro Tosi16bd0b42012-01-19 21:59:55 +0100866
867 >>> parser = argparse.ArgumentParser(prog='PROG')
868 >>> parser.add_argument('--foo')
869 >>> parser.add_argument('command')
870 >>> parser.add_argument('args', nargs=argparse.REMAINDER)
Sandro Tosi04676862012-02-19 19:54:00 +0100871 >>> print(parser.parse_args('--foo B cmd --arg1 XX ZZ'.split()))
Sandro Tosida8e11a2012-01-19 22:23:00 +0100872 Namespace(args=['--arg1', 'XX', 'ZZ'], command='cmd', foo='B')
Sandro Tosi16bd0b42012-01-19 21:59:55 +0100873
Éric Araujod9d7bca2011-08-10 04:19:03 +0200874If the ``nargs`` keyword argument is not provided, the number of arguments consumed
Éric Araujofde92422011-08-19 01:30:26 +0200875is determined by the action_. Generally this means a single command-line argument
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000876will be consumed and a single item (not a list) will be produced.
877
878
879const
880^^^^^
881
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300882The ``const`` argument of :meth:`~ArgumentParser.add_argument` is used to hold
883constant values that are not read from the command line but are required for
884the various :class:`ArgumentParser` actions. The two most common uses of it are:
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000885
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300886* When :meth:`~ArgumentParser.add_argument` is called with
887 ``action='store_const'`` or ``action='append_const'``. These actions add the
Éric Araujoc3ef0372012-02-20 01:44:55 +0100888 ``const`` value to one of the attributes of the object returned by
889 :meth:`~ArgumentParser.parse_args`. See the action_ description for examples.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000890
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300891* When :meth:`~ArgumentParser.add_argument` is called with option strings
892 (like ``-f`` or ``--foo``) and ``nargs='?'``. This creates an optional
Éric Araujod9d7bca2011-08-10 04:19:03 +0200893 argument that can be followed by zero or one command-line arguments.
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300894 When parsing the command line, if the option string is encountered with no
Éric Araujofde92422011-08-19 01:30:26 +0200895 command-line argument following it, the value of ``const`` will be assumed instead.
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300896 See the nargs_ description for examples.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000897
898The ``const`` keyword argument defaults to ``None``.
899
900
901default
902^^^^^^^
903
904All optional arguments and some positional arguments may be omitted at the
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300905command line. The ``default`` keyword argument of
906:meth:`~ArgumentParser.add_argument`, whose value defaults to ``None``,
Éric Araujofde92422011-08-19 01:30:26 +0200907specifies what value should be used if the command-line argument is not present.
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300908For optional arguments, the ``default`` value is used when the option string
909was not present at the command line::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000910
911 >>> parser = argparse.ArgumentParser()
912 >>> parser.add_argument('--foo', default=42)
913 >>> parser.parse_args('--foo 2'.split())
914 Namespace(foo='2')
915 >>> parser.parse_args(''.split())
916 Namespace(foo=42)
917
Barry Warsaw1dedd0a2012-09-25 10:37:58 -0400918If the ``default`` value is a string, the parser parses the value as if it
919were a command-line argument. In particular, the parser applies any type_
920conversion argument, if provided, before setting the attribute on the
921:class:`Namespace` return value. Otherwise, the parser uses the value as is::
922
923 >>> parser = argparse.ArgumentParser()
924 >>> parser.add_argument('--length', default='10', type=int)
925 >>> parser.add_argument('--width', default=10.5, type=int)
926 >>> parser.parse_args()
927 Namespace(length=10, width=10.5)
928
Éric Araujo543edbd2011-08-19 01:45:12 +0200929For positional arguments with nargs_ equal to ``?`` or ``*``, the ``default`` value
Éric Araujofde92422011-08-19 01:30:26 +0200930is used when no command-line argument was present::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000931
932 >>> parser = argparse.ArgumentParser()
933 >>> parser.add_argument('foo', nargs='?', default=42)
934 >>> parser.parse_args('a'.split())
935 Namespace(foo='a')
936 >>> parser.parse_args(''.split())
937 Namespace(foo=42)
938
939
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000940Providing ``default=argparse.SUPPRESS`` causes no attribute to be added if the
941command-line argument was not present.::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000942
943 >>> parser = argparse.ArgumentParser()
944 >>> parser.add_argument('--foo', default=argparse.SUPPRESS)
945 >>> parser.parse_args([])
946 Namespace()
947 >>> parser.parse_args(['--foo', '1'])
948 Namespace(foo='1')
949
950
951type
952^^^^
953
Éric Araujod9d7bca2011-08-10 04:19:03 +0200954By default, :class:`ArgumentParser` objects read command-line arguments in as simple
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300955strings. However, quite often the command-line string should instead be
956interpreted as another type, like a :class:`float` or :class:`int`. The
957``type`` keyword argument of :meth:`~ArgumentParser.add_argument` allows any
Éric Araujod9d7bca2011-08-10 04:19:03 +0200958necessary type-checking and type conversions to be performed. Common built-in
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300959types and functions can be used directly as the value of the ``type`` argument::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000960
961 >>> parser = argparse.ArgumentParser()
962 >>> parser.add_argument('foo', type=int)
Georg Brandl04536b02011-01-09 09:31:01 +0000963 >>> parser.add_argument('bar', type=open)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000964 >>> parser.parse_args('2 temp.txt'.split())
Georg Brandl04536b02011-01-09 09:31:01 +0000965 Namespace(bar=<_io.TextIOWrapper name='temp.txt' encoding='UTF-8'>, foo=2)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000966
Barry Warsaw1dedd0a2012-09-25 10:37:58 -0400967See the section on the default_ keyword argument for information on when the
968``type`` argument is applied to default arguments.
969
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000970To ease the use of various types of files, the argparse module provides the
Petri Lehtinen74d6c252012-12-15 22:39:32 +0200971factory FileType which takes the ``mode=``, ``bufsize=``, ``encoding=`` and
972``errors=`` arguments of the :func:`open` function. For example,
973``FileType('w')`` can be used to create a writable file::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000974
975 >>> parser = argparse.ArgumentParser()
976 >>> parser.add_argument('bar', type=argparse.FileType('w'))
977 >>> parser.parse_args(['out.txt'])
Georg Brandl04536b02011-01-09 09:31:01 +0000978 Namespace(bar=<_io.TextIOWrapper name='out.txt' encoding='UTF-8'>)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000979
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000980``type=`` can take any callable that takes a single string argument and returns
Éric Araujod9d7bca2011-08-10 04:19:03 +0200981the converted value::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000982
983 >>> def perfect_square(string):
984 ... value = int(string)
985 ... sqrt = math.sqrt(value)
986 ... if sqrt != int(sqrt):
987 ... msg = "%r is not a perfect square" % string
988 ... raise argparse.ArgumentTypeError(msg)
989 ... return value
990 ...
991 >>> parser = argparse.ArgumentParser(prog='PROG')
992 >>> parser.add_argument('foo', type=perfect_square)
993 >>> parser.parse_args('9'.split())
994 Namespace(foo=9)
995 >>> parser.parse_args('7'.split())
996 usage: PROG [-h] foo
997 PROG: error: argument foo: '7' is not a perfect square
998
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000999The choices_ keyword argument may be more convenient for type checkers that
1000simply check against a range of values::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001001
1002 >>> parser = argparse.ArgumentParser(prog='PROG')
Fred Drake44623062011-03-03 05:27:17 +00001003 >>> parser.add_argument('foo', type=int, choices=range(5, 10))
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001004 >>> parser.parse_args('7'.split())
1005 Namespace(foo=7)
1006 >>> parser.parse_args('11'.split())
1007 usage: PROG [-h] {5,6,7,8,9}
1008 PROG: error: argument foo: invalid choice: 11 (choose from 5, 6, 7, 8, 9)
1009
1010See the choices_ section for more details.
1011
1012
1013choices
1014^^^^^^^
1015
Éric Araujod9d7bca2011-08-10 04:19:03 +02001016Some command-line arguments should be selected from a restricted set of values.
Chris Jerdonek174ef672013-01-11 19:26:44 -08001017These can be handled by passing a container object as the *choices* keyword
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001018argument to :meth:`~ArgumentParser.add_argument`. When the command line is
Chris Jerdonek174ef672013-01-11 19:26:44 -08001019parsed, argument values will be checked, and an error message will be displayed
1020if the argument was not one of the acceptable values::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001021
Chris Jerdonek174ef672013-01-11 19:26:44 -08001022 >>> parser = argparse.ArgumentParser(prog='game.py')
1023 >>> parser.add_argument('move', choices=['rock', 'paper', 'scissors'])
1024 >>> parser.parse_args(['rock'])
1025 Namespace(move='rock')
1026 >>> parser.parse_args(['fire'])
1027 usage: game.py [-h] {rock,paper,scissors}
1028 game.py: error: argument move: invalid choice: 'fire' (choose from 'rock',
1029 'paper', 'scissors')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001030
Chris Jerdonek174ef672013-01-11 19:26:44 -08001031Note that inclusion in the *choices* container is checked after any type_
1032conversions have been performed, so the type of the objects in the *choices*
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001033container should match the type_ specified::
1034
Chris Jerdonek174ef672013-01-11 19:26:44 -08001035 >>> parser = argparse.ArgumentParser(prog='doors.py')
1036 >>> parser.add_argument('door', type=int, choices=range(1, 4))
1037 >>> print(parser.parse_args(['3']))
1038 Namespace(door=3)
1039 >>> parser.parse_args(['4'])
1040 usage: doors.py [-h] {1,2,3}
1041 doors.py: error: argument door: invalid choice: 4 (choose from 1, 2, 3)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001042
Chris Jerdonek174ef672013-01-11 19:26:44 -08001043Any object that supports the ``in`` operator can be passed as the *choices*
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001044value, so :class:`dict` objects, :class:`set` objects, custom containers,
1045etc. are all supported.
1046
1047
1048required
1049^^^^^^^^
1050
Ezio Melotti0ee9c1b2011-04-21 16:12:17 +03001051In general, the :mod:`argparse` module assumes that flags like ``-f`` and ``--bar``
Georg Brandl69518bc2011-04-16 16:44:54 +02001052indicate *optional* arguments, which can always be omitted at the command line.
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001053To make an option *required*, ``True`` can be specified for the ``required=``
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001054keyword argument to :meth:`~ArgumentParser.add_argument`::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001055
1056 >>> parser = argparse.ArgumentParser()
1057 >>> parser.add_argument('--foo', required=True)
1058 >>> parser.parse_args(['--foo', 'BAR'])
1059 Namespace(foo='BAR')
1060 >>> parser.parse_args([])
1061 usage: argparse.py [-h] [--foo FOO]
1062 argparse.py: error: option --foo is required
1063
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001064As the example shows, if an option is marked as ``required``,
1065:meth:`~ArgumentParser.parse_args` will report an error if that option is not
1066present at the command line.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001067
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001068.. note::
1069
1070 Required options are generally considered bad form because users expect
1071 *options* to be *optional*, and thus they should be avoided when possible.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001072
1073
1074help
1075^^^^
1076
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001077The ``help`` value is a string containing a brief description of the argument.
1078When a user requests help (usually by using ``-h`` or ``--help`` at the
Georg Brandl69518bc2011-04-16 16:44:54 +02001079command line), these ``help`` descriptions will be displayed with each
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001080argument::
1081
1082 >>> parser = argparse.ArgumentParser(prog='frobble')
1083 >>> parser.add_argument('--foo', action='store_true',
1084 ... help='foo the bars before frobbling')
1085 >>> parser.add_argument('bar', nargs='+',
1086 ... help='one of the bars to be frobbled')
1087 >>> parser.parse_args('-h'.split())
1088 usage: frobble [-h] [--foo] bar [bar ...]
1089
1090 positional arguments:
1091 bar one of the bars to be frobbled
1092
1093 optional arguments:
1094 -h, --help show this help message and exit
1095 --foo foo the bars before frobbling
1096
1097The ``help`` strings can include various format specifiers to avoid repetition
1098of things like the program name or the argument default_. The available
1099specifiers include the program name, ``%(prog)s`` and most keyword arguments to
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001100:meth:`~ArgumentParser.add_argument`, e.g. ``%(default)s``, ``%(type)s``, etc.::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001101
1102 >>> parser = argparse.ArgumentParser(prog='frobble')
1103 >>> parser.add_argument('bar', nargs='?', type=int, default=42,
1104 ... help='the bar to %(prog)s (default: %(default)s)')
1105 >>> parser.print_help()
1106 usage: frobble [-h] [bar]
1107
1108 positional arguments:
1109 bar the bar to frobble (default: 42)
1110
1111 optional arguments:
1112 -h, --help show this help message and exit
1113
Senthil Kumaranf21804a2012-06-26 14:17:19 +08001114As the help string supports %-formatting, if you want a literal ``%`` to appear
1115in the help string, you must escape it as ``%%``.
1116
Sandro Tosiea320ab2012-01-03 18:37:03 +01001117:mod:`argparse` supports silencing the help entry for certain options, by
1118setting the ``help`` value to ``argparse.SUPPRESS``::
1119
1120 >>> parser = argparse.ArgumentParser(prog='frobble')
1121 >>> parser.add_argument('--foo', help=argparse.SUPPRESS)
1122 >>> parser.print_help()
1123 usage: frobble [-h]
1124
1125 optional arguments:
1126 -h, --help show this help message and exit
1127
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001128
1129metavar
1130^^^^^^^
1131
Sandro Tosi32587fb2013-01-11 10:49:00 +01001132When :class:`ArgumentParser` generates help messages, it needs some way to refer
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001133to each expected argument. By default, ArgumentParser objects use the dest_
1134value as the "name" of each object. By default, for positional argument
1135actions, the dest_ value is used directly, and for optional argument actions,
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001136the dest_ value is uppercased. So, a single positional argument with
Eli Benderskya7795db2011-11-11 10:57:01 +02001137``dest='bar'`` will be referred to as ``bar``. A single
Éric Araujofde92422011-08-19 01:30:26 +02001138optional argument ``--foo`` that should be followed by a single command-line argument
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001139will be referred to as ``FOO``. An example::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001140
1141 >>> parser = argparse.ArgumentParser()
1142 >>> parser.add_argument('--foo')
1143 >>> parser.add_argument('bar')
1144 >>> parser.parse_args('X --foo Y'.split())
1145 Namespace(bar='X', foo='Y')
1146 >>> parser.print_help()
1147 usage: [-h] [--foo FOO] bar
1148
1149 positional arguments:
1150 bar
1151
1152 optional arguments:
1153 -h, --help show this help message and exit
1154 --foo FOO
1155
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001156An alternative name can be specified with ``metavar``::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001157
1158 >>> parser = argparse.ArgumentParser()
1159 >>> parser.add_argument('--foo', metavar='YYY')
1160 >>> parser.add_argument('bar', metavar='XXX')
1161 >>> parser.parse_args('X --foo Y'.split())
1162 Namespace(bar='X', foo='Y')
1163 >>> parser.print_help()
1164 usage: [-h] [--foo YYY] XXX
1165
1166 positional arguments:
1167 XXX
1168
1169 optional arguments:
1170 -h, --help show this help message and exit
1171 --foo YYY
1172
1173Note that ``metavar`` only changes the *displayed* name - the name of the
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001174attribute on the :meth:`~ArgumentParser.parse_args` object is still determined
1175by the dest_ value.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001176
1177Different values of ``nargs`` may cause the metavar to be used multiple times.
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001178Providing a tuple to ``metavar`` specifies a different display for each of the
1179arguments::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001180
1181 >>> parser = argparse.ArgumentParser(prog='PROG')
1182 >>> parser.add_argument('-x', nargs=2)
1183 >>> parser.add_argument('--foo', nargs=2, metavar=('bar', 'baz'))
1184 >>> parser.print_help()
1185 usage: PROG [-h] [-x X X] [--foo bar baz]
1186
1187 optional arguments:
1188 -h, --help show this help message and exit
1189 -x X X
1190 --foo bar baz
1191
1192
1193dest
1194^^^^
1195
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001196Most :class:`ArgumentParser` actions add some value as an attribute of the
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001197object returned by :meth:`~ArgumentParser.parse_args`. The name of this
1198attribute is determined by the ``dest`` keyword argument of
1199:meth:`~ArgumentParser.add_argument`. For positional argument actions,
1200``dest`` is normally supplied as the first argument to
1201:meth:`~ArgumentParser.add_argument`::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001202
1203 >>> parser = argparse.ArgumentParser()
1204 >>> parser.add_argument('bar')
1205 >>> parser.parse_args('XXX'.split())
1206 Namespace(bar='XXX')
1207
1208For optional argument actions, the value of ``dest`` is normally inferred from
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001209the option strings. :class:`ArgumentParser` generates the value of ``dest`` by
Éric Araujo543edbd2011-08-19 01:45:12 +02001210taking the first long option string and stripping away the initial ``--``
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001211string. If no long option strings were supplied, ``dest`` will be derived from
Éric Araujo543edbd2011-08-19 01:45:12 +02001212the first short option string by stripping the initial ``-`` character. Any
1213internal ``-`` characters will be converted to ``_`` characters to make sure
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001214the string is a valid attribute name. The examples below illustrate this
1215behavior::
1216
1217 >>> parser = argparse.ArgumentParser()
1218 >>> parser.add_argument('-f', '--foo-bar', '--foo')
1219 >>> parser.add_argument('-x', '-y')
1220 >>> parser.parse_args('-f 1 -x 2'.split())
1221 Namespace(foo_bar='1', x='2')
1222 >>> parser.parse_args('--foo 1 -y 2'.split())
1223 Namespace(foo_bar='1', x='2')
1224
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001225``dest`` allows a custom attribute name to be provided::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001226
1227 >>> parser = argparse.ArgumentParser()
1228 >>> parser.add_argument('--foo', dest='bar')
1229 >>> parser.parse_args('--foo XXX'.split())
1230 Namespace(bar='XXX')
1231
Jason R. Coombsf28cf7a2011-12-13 23:36:45 -05001232Action classes
1233^^^^^^^^^^^^^^
1234
Jason R. Coombseb0ef412014-07-20 10:52:46 -04001235Action classes implement the Action API, a callable which returns a callable
1236which processes arguments from the command-line. Any object which follows
1237this API may be passed as the ``action`` parameter to
Raymond Hettingerc0de59b2014-08-03 23:44:30 -07001238:meth:`add_argument`.
Jason R. Coombseb0ef412014-07-20 10:52:46 -04001239
Terry Jan Reedyee558262014-08-23 22:21:47 -04001240.. class:: Action(option_strings, dest, nargs=None, const=None, default=None, \
1241 type=None, choices=None, required=False, help=None, \
Jason R. Coombsf28cf7a2011-12-13 23:36:45 -05001242 metavar=None)
1243
1244Action objects are used by an ArgumentParser to represent the information
1245needed to parse a single argument from one or more strings from the
Jason R. Coombseb0ef412014-07-20 10:52:46 -04001246command line. The Action class must accept the two positional arguments
Raymond Hettingerc0de59b2014-08-03 23:44:30 -07001247plus any keyword arguments passed to :meth:`ArgumentParser.add_argument`
Jason R. Coombseb0ef412014-07-20 10:52:46 -04001248except for the ``action`` itself.
Jason R. Coombsf28cf7a2011-12-13 23:36:45 -05001249
Jason R. Coombseb0ef412014-07-20 10:52:46 -04001250Instances of Action (or return value of any callable to the ``action``
1251parameter) should have attributes "dest", "option_strings", "default", "type",
1252"required", "help", etc. defined. The easiest way to ensure these attributes
1253are defined is to call ``Action.__init__``.
Jason R. Coombsf28cf7a2011-12-13 23:36:45 -05001254
Jason R. Coombseb0ef412014-07-20 10:52:46 -04001255Action instances should be callable, so subclasses must override the
1256``__call__`` method, which should accept four parameters:
Jason R. Coombsf28cf7a2011-12-13 23:36:45 -05001257
1258* ``parser`` - The ArgumentParser object which contains this action.
1259
1260* ``namespace`` - The :class:`Namespace` object that will be returned by
1261 :meth:`~ArgumentParser.parse_args`. Most actions add an attribute to this
1262 object using :func:`setattr`.
1263
1264* ``values`` - The associated command-line arguments, with any type conversions
1265 applied. Type conversions are specified with the type_ keyword argument to
1266 :meth:`~ArgumentParser.add_argument`.
1267
1268* ``option_string`` - The option string that was used to invoke this action.
1269 The ``option_string`` argument is optional, and will be absent if the action
1270 is associated with a positional argument.
1271
Jason R. Coombseb0ef412014-07-20 10:52:46 -04001272The ``__call__`` method may perform arbitrary actions, but will typically set
1273attributes on the ``namespace`` based on ``dest`` and ``values``.
1274
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001275
1276The parse_args() method
1277-----------------------
1278
Georg Brandle0bf91d2010-10-17 10:34:28 +00001279.. method:: ArgumentParser.parse_args(args=None, namespace=None)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001280
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001281 Convert argument strings to objects and assign them as attributes of the
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001282 namespace. Return the populated namespace.
1283
1284 Previous calls to :meth:`add_argument` determine exactly what objects are
1285 created and how they are assigned. See the documentation for
1286 :meth:`add_argument` for details.
1287
Éric Araujofde92422011-08-19 01:30:26 +02001288 By default, the argument strings are taken from :data:`sys.argv`, and a new empty
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001289 :class:`Namespace` object is created for the attributes.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001290
Georg Brandle0bf91d2010-10-17 10:34:28 +00001291
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001292Option value syntax
1293^^^^^^^^^^^^^^^^^^^
1294
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001295The :meth:`~ArgumentParser.parse_args` method supports several ways of
1296specifying the value of an option (if it takes one). In the simplest case, the
1297option and its value are passed as two separate arguments::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001298
1299 >>> parser = argparse.ArgumentParser(prog='PROG')
1300 >>> parser.add_argument('-x')
1301 >>> parser.add_argument('--foo')
1302 >>> parser.parse_args('-x X'.split())
1303 Namespace(foo=None, x='X')
1304 >>> parser.parse_args('--foo FOO'.split())
1305 Namespace(foo='FOO', x=None)
1306
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001307For long options (options with names longer than a single character), the option
Georg Brandl69518bc2011-04-16 16:44:54 +02001308and value can also be passed as a single command-line argument, using ``=`` to
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001309separate them::
1310
1311 >>> parser.parse_args('--foo=FOO'.split())
1312 Namespace(foo='FOO', x=None)
1313
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001314For short options (options only one character long), the option and its value
1315can be concatenated::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001316
1317 >>> parser.parse_args('-xX'.split())
1318 Namespace(foo=None, x='X')
1319
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001320Several short options can be joined together, using only a single ``-`` prefix,
1321as long as only the last option (or none of them) requires a value::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001322
1323 >>> parser = argparse.ArgumentParser(prog='PROG')
1324 >>> parser.add_argument('-x', action='store_true')
1325 >>> parser.add_argument('-y', action='store_true')
1326 >>> parser.add_argument('-z')
1327 >>> parser.parse_args('-xyzZ'.split())
1328 Namespace(x=True, y=True, z='Z')
1329
1330
1331Invalid arguments
1332^^^^^^^^^^^^^^^^^
1333
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001334While parsing the command line, :meth:`~ArgumentParser.parse_args` checks for a
1335variety of errors, including ambiguous options, invalid types, invalid options,
1336wrong number of positional arguments, etc. When it encounters such an error,
1337it exits and prints the error along with a usage message::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001338
1339 >>> parser = argparse.ArgumentParser(prog='PROG')
1340 >>> parser.add_argument('--foo', type=int)
1341 >>> parser.add_argument('bar', nargs='?')
1342
1343 >>> # invalid type
1344 >>> parser.parse_args(['--foo', 'spam'])
1345 usage: PROG [-h] [--foo FOO] [bar]
1346 PROG: error: argument --foo: invalid int value: 'spam'
1347
1348 >>> # invalid option
1349 >>> parser.parse_args(['--bar'])
1350 usage: PROG [-h] [--foo FOO] [bar]
1351 PROG: error: no such option: --bar
1352
1353 >>> # wrong number of arguments
1354 >>> parser.parse_args(['spam', 'badger'])
1355 usage: PROG [-h] [--foo FOO] [bar]
1356 PROG: error: extra arguments found: badger
1357
1358
Éric Araujo543edbd2011-08-19 01:45:12 +02001359Arguments containing ``-``
1360^^^^^^^^^^^^^^^^^^^^^^^^^^
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001361
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001362The :meth:`~ArgumentParser.parse_args` method attempts to give errors whenever
1363the user has clearly made a mistake, but some situations are inherently
Éric Araujo543edbd2011-08-19 01:45:12 +02001364ambiguous. For example, the command-line argument ``-1`` could either be an
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001365attempt to specify an option or an attempt to provide a positional argument.
1366The :meth:`~ArgumentParser.parse_args` method is cautious here: positional
Éric Araujo543edbd2011-08-19 01:45:12 +02001367arguments may only begin with ``-`` if they look like negative numbers and
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001368there are no options in the parser that look like negative numbers::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001369
1370 >>> parser = argparse.ArgumentParser(prog='PROG')
1371 >>> parser.add_argument('-x')
1372 >>> parser.add_argument('foo', nargs='?')
1373
1374 >>> # no negative number options, so -1 is a positional argument
1375 >>> parser.parse_args(['-x', '-1'])
1376 Namespace(foo=None, x='-1')
1377
1378 >>> # no negative number options, so -1 and -5 are positional arguments
1379 >>> parser.parse_args(['-x', '-1', '-5'])
1380 Namespace(foo='-5', x='-1')
1381
1382 >>> parser = argparse.ArgumentParser(prog='PROG')
1383 >>> parser.add_argument('-1', dest='one')
1384 >>> parser.add_argument('foo', nargs='?')
1385
1386 >>> # negative number options present, so -1 is an option
1387 >>> parser.parse_args(['-1', 'X'])
1388 Namespace(foo=None, one='X')
1389
1390 >>> # negative number options present, so -2 is an option
1391 >>> parser.parse_args(['-2'])
1392 usage: PROG [-h] [-1 ONE] [foo]
1393 PROG: error: no such option: -2
1394
1395 >>> # negative number options present, so both -1s are options
1396 >>> parser.parse_args(['-1', '-1'])
1397 usage: PROG [-h] [-1 ONE] [foo]
1398 PROG: error: argument -1: expected one argument
1399
Éric Araujo543edbd2011-08-19 01:45:12 +02001400If you have positional arguments that must begin with ``-`` and don't look
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001401like negative numbers, you can insert the pseudo-argument ``'--'`` which tells
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001402:meth:`~ArgumentParser.parse_args` that everything after that is a positional
1403argument::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001404
1405 >>> parser.parse_args(['--', '-f'])
1406 Namespace(foo='-f', one=None)
1407
Eli Benderskyf3114532013-12-02 05:49:54 -08001408.. _prefix-matching:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001409
Eli Benderskyf3114532013-12-02 05:49:54 -08001410Argument abbreviations (prefix matching)
1411^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001412
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001413The :meth:`~ArgumentParser.parse_args` method allows long options to be
Eli Benderskyf3114532013-12-02 05:49:54 -08001414abbreviated to a prefix, if the abbreviation is unambiguous (the prefix matches
1415a unique option)::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001416
1417 >>> parser = argparse.ArgumentParser(prog='PROG')
1418 >>> parser.add_argument('-bacon')
1419 >>> parser.add_argument('-badger')
1420 >>> parser.parse_args('-bac MMM'.split())
1421 Namespace(bacon='MMM', badger=None)
1422 >>> parser.parse_args('-bad WOOD'.split())
1423 Namespace(bacon=None, badger='WOOD')
1424 >>> parser.parse_args('-ba BA'.split())
1425 usage: PROG [-h] [-bacon BACON] [-badger BADGER]
1426 PROG: error: ambiguous option: -ba could match -badger, -bacon
1427
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001428An error is produced for arguments that could produce more than one options.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001429
1430
1431Beyond ``sys.argv``
1432^^^^^^^^^^^^^^^^^^^
1433
Éric Araujod9d7bca2011-08-10 04:19:03 +02001434Sometimes it may be useful to have an ArgumentParser parse arguments other than those
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001435of :data:`sys.argv`. This can be accomplished by passing a list of strings to
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001436:meth:`~ArgumentParser.parse_args`. This is useful for testing at the
1437interactive prompt::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001438
1439 >>> parser = argparse.ArgumentParser()
1440 >>> parser.add_argument(
Fred Drake44623062011-03-03 05:27:17 +00001441 ... 'integers', metavar='int', type=int, choices=range(10),
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001442 ... nargs='+', help='an integer in the range 0..9')
1443 >>> parser.add_argument(
1444 ... '--sum', dest='accumulate', action='store_const', const=sum,
1445 ... default=max, help='sum the integers (default: find the max)')
1446 >>> parser.parse_args(['1', '2', '3', '4'])
1447 Namespace(accumulate=<built-in function max>, integers=[1, 2, 3, 4])
1448 >>> parser.parse_args('1 2 3 4 --sum'.split())
1449 Namespace(accumulate=<built-in function sum>, integers=[1, 2, 3, 4])
1450
1451
Steven Bethardd8f2d502011-03-26 19:50:06 +01001452The Namespace object
1453^^^^^^^^^^^^^^^^^^^^
1454
Éric Araujo63b18a42011-07-29 17:59:17 +02001455.. class:: Namespace
1456
1457 Simple class used by default by :meth:`~ArgumentParser.parse_args` to create
1458 an object holding attributes and return it.
1459
1460This class is deliberately simple, just an :class:`object` subclass with a
1461readable string representation. If you prefer to have dict-like view of the
1462attributes, you can use the standard Python idiom, :func:`vars`::
Steven Bethardd8f2d502011-03-26 19:50:06 +01001463
1464 >>> parser = argparse.ArgumentParser()
1465 >>> parser.add_argument('--foo')
1466 >>> args = parser.parse_args(['--foo', 'BAR'])
1467 >>> vars(args)
1468 {'foo': 'BAR'}
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001469
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001470It may also be useful to have an :class:`ArgumentParser` assign attributes to an
Steven Bethardd8f2d502011-03-26 19:50:06 +01001471already existing object, rather than a new :class:`Namespace` object. This can
1472be achieved by specifying the ``namespace=`` keyword argument::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001473
Éric Araujo28053fb2010-11-22 03:09:19 +00001474 >>> class C:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001475 ... pass
1476 ...
1477 >>> c = C()
1478 >>> parser = argparse.ArgumentParser()
1479 >>> parser.add_argument('--foo')
1480 >>> parser.parse_args(args=['--foo', 'BAR'], namespace=c)
1481 >>> c.foo
1482 'BAR'
1483
1484
1485Other utilities
1486---------------
1487
1488Sub-commands
1489^^^^^^^^^^^^
1490
Georg Brandlfc9a1132013-10-06 18:51:39 +02001491.. method:: ArgumentParser.add_subparsers([title], [description], [prog], \
1492 [parser_class], [action], \
1493 [option_string], [dest], [help], \
1494 [metavar])
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001495
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001496 Many programs split up their functionality into a number of sub-commands,
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001497 for example, the ``svn`` program can invoke sub-commands like ``svn
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001498 checkout``, ``svn update``, and ``svn commit``. Splitting up functionality
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001499 this way can be a particularly good idea when a program performs several
1500 different functions which require different kinds of command-line arguments.
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001501 :class:`ArgumentParser` supports the creation of such sub-commands with the
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001502 :meth:`add_subparsers` method. The :meth:`add_subparsers` method is normally
Ezio Melotti52336f02012-12-28 01:59:24 +02001503 called with no arguments and returns a special action object. This object
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001504 has a single method, :meth:`~ArgumentParser.add_parser`, which takes a
1505 command name and any :class:`ArgumentParser` constructor arguments, and
1506 returns an :class:`ArgumentParser` object that can be modified as usual.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001507
Georg Brandlfc9a1132013-10-06 18:51:39 +02001508 Description of parameters:
1509
1510 * title - title for the sub-parser group in help output; by default
1511 "subcommands" if description is provided, otherwise uses title for
1512 positional arguments
1513
1514 * description - description for the sub-parser group in help output, by
1515 default None
1516
1517 * prog - usage information that will be displayed with sub-command help,
1518 by default the name of the program and any positional arguments before the
1519 subparser argument
1520
1521 * parser_class - class which will be used to create sub-parser instances, by
1522 default the class of the current parser (e.g. ArgumentParser)
1523
Berker Peksag5a494f62015-01-20 06:45:53 +02001524 * action_ - the basic type of action to be taken when this argument is
1525 encountered at the command line
1526
1527 * dest_ - name of the attribute under which sub-command name will be
Georg Brandlfc9a1132013-10-06 18:51:39 +02001528 stored; by default None and no value is stored
1529
Berker Peksag5a494f62015-01-20 06:45:53 +02001530 * help_ - help for sub-parser group in help output, by default None
Georg Brandlfc9a1132013-10-06 18:51:39 +02001531
Berker Peksag5a494f62015-01-20 06:45:53 +02001532 * metavar_ - string presenting available sub-commands in help; by default it
Georg Brandlfc9a1132013-10-06 18:51:39 +02001533 is None and presents sub-commands in form {cmd1, cmd2, ..}
1534
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001535 Some example usage::
1536
1537 >>> # create the top-level parser
1538 >>> parser = argparse.ArgumentParser(prog='PROG')
1539 >>> parser.add_argument('--foo', action='store_true', help='foo help')
1540 >>> subparsers = parser.add_subparsers(help='sub-command help')
1541 >>>
1542 >>> # create the parser for the "a" command
1543 >>> parser_a = subparsers.add_parser('a', help='a help')
1544 >>> parser_a.add_argument('bar', type=int, help='bar help')
1545 >>>
1546 >>> # create the parser for the "b" command
1547 >>> parser_b = subparsers.add_parser('b', help='b help')
1548 >>> parser_b.add_argument('--baz', choices='XYZ', help='baz help')
1549 >>>
Éric Araujofde92422011-08-19 01:30:26 +02001550 >>> # parse some argument lists
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001551 >>> parser.parse_args(['a', '12'])
1552 Namespace(bar=12, foo=False)
1553 >>> parser.parse_args(['--foo', 'b', '--baz', 'Z'])
1554 Namespace(baz='Z', foo=True)
1555
1556 Note that the object returned by :meth:`parse_args` will only contain
1557 attributes for the main parser and the subparser that was selected by the
1558 command line (and not any other subparsers). So in the example above, when
Éric Araujo543edbd2011-08-19 01:45:12 +02001559 the ``a`` command is specified, only the ``foo`` and ``bar`` attributes are
1560 present, and when the ``b`` command is specified, only the ``foo`` and
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001561 ``baz`` attributes are present.
1562
1563 Similarly, when a help message is requested from a subparser, only the help
1564 for that particular parser will be printed. The help message will not
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001565 include parent parser or sibling parser messages. (A help message for each
1566 subparser command, however, can be given by supplying the ``help=`` argument
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001567 to :meth:`add_parser` as above.)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001568
1569 ::
1570
1571 >>> parser.parse_args(['--help'])
1572 usage: PROG [-h] [--foo] {a,b} ...
1573
1574 positional arguments:
1575 {a,b} sub-command help
Ezio Melotti7128e072013-01-12 10:39:45 +02001576 a a help
1577 b b help
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001578
1579 optional arguments:
1580 -h, --help show this help message and exit
1581 --foo foo help
1582
1583 >>> parser.parse_args(['a', '--help'])
1584 usage: PROG a [-h] bar
1585
1586 positional arguments:
1587 bar bar help
1588
1589 optional arguments:
1590 -h, --help show this help message and exit
1591
1592 >>> parser.parse_args(['b', '--help'])
1593 usage: PROG b [-h] [--baz {X,Y,Z}]
1594
1595 optional arguments:
1596 -h, --help show this help message and exit
1597 --baz {X,Y,Z} baz help
1598
1599 The :meth:`add_subparsers` method also supports ``title`` and ``description``
1600 keyword arguments. When either is present, the subparser's commands will
1601 appear in their own group in the help output. For example::
1602
1603 >>> parser = argparse.ArgumentParser()
1604 >>> subparsers = parser.add_subparsers(title='subcommands',
1605 ... description='valid subcommands',
1606 ... help='additional help')
1607 >>> subparsers.add_parser('foo')
1608 >>> subparsers.add_parser('bar')
1609 >>> parser.parse_args(['-h'])
1610 usage: [-h] {foo,bar} ...
1611
1612 optional arguments:
1613 -h, --help show this help message and exit
1614
1615 subcommands:
1616 valid subcommands
1617
1618 {foo,bar} additional help
1619
Steven Bethardfd311a72010-12-18 11:19:23 +00001620 Furthermore, ``add_parser`` supports an additional ``aliases`` argument,
1621 which allows multiple strings to refer to the same subparser. This example,
1622 like ``svn``, aliases ``co`` as a shorthand for ``checkout``::
1623
1624 >>> parser = argparse.ArgumentParser()
1625 >>> subparsers = parser.add_subparsers()
1626 >>> checkout = subparsers.add_parser('checkout', aliases=['co'])
1627 >>> checkout.add_argument('foo')
1628 >>> parser.parse_args(['co', 'bar'])
1629 Namespace(foo='bar')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001630
1631 One particularly effective way of handling sub-commands is to combine the use
1632 of the :meth:`add_subparsers` method with calls to :meth:`set_defaults` so
1633 that each subparser knows which Python function it should execute. For
1634 example::
1635
1636 >>> # sub-command functions
1637 >>> def foo(args):
Benjamin Petersonb2deb112010-03-03 02:09:18 +00001638 ... print(args.x * args.y)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001639 ...
1640 >>> def bar(args):
Benjamin Petersonb2deb112010-03-03 02:09:18 +00001641 ... print('((%s))' % args.z)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001642 ...
1643 >>> # create the top-level parser
1644 >>> parser = argparse.ArgumentParser()
1645 >>> subparsers = parser.add_subparsers()
1646 >>>
1647 >>> # create the parser for the "foo" command
1648 >>> parser_foo = subparsers.add_parser('foo')
1649 >>> parser_foo.add_argument('-x', type=int, default=1)
1650 >>> parser_foo.add_argument('y', type=float)
1651 >>> parser_foo.set_defaults(func=foo)
1652 >>>
1653 >>> # create the parser for the "bar" command
1654 >>> parser_bar = subparsers.add_parser('bar')
1655 >>> parser_bar.add_argument('z')
1656 >>> parser_bar.set_defaults(func=bar)
1657 >>>
1658 >>> # parse the args and call whatever function was selected
1659 >>> args = parser.parse_args('foo 1 -x 2'.split())
1660 >>> args.func(args)
1661 2.0
1662 >>>
1663 >>> # parse the args and call whatever function was selected
1664 >>> args = parser.parse_args('bar XYZYX'.split())
1665 >>> args.func(args)
1666 ((XYZYX))
1667
Steven Bethardfd311a72010-12-18 11:19:23 +00001668 This way, you can let :meth:`parse_args` do the job of calling the
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001669 appropriate function after argument parsing is complete. Associating
1670 functions with actions like this is typically the easiest way to handle the
1671 different actions for each of your subparsers. However, if it is necessary
1672 to check the name of the subparser that was invoked, the ``dest`` keyword
1673 argument to the :meth:`add_subparsers` call will work::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001674
1675 >>> parser = argparse.ArgumentParser()
1676 >>> subparsers = parser.add_subparsers(dest='subparser_name')
1677 >>> subparser1 = subparsers.add_parser('1')
1678 >>> subparser1.add_argument('-x')
1679 >>> subparser2 = subparsers.add_parser('2')
1680 >>> subparser2.add_argument('y')
1681 >>> parser.parse_args(['2', 'frobble'])
1682 Namespace(subparser_name='2', y='frobble')
1683
1684
1685FileType objects
1686^^^^^^^^^^^^^^^^
1687
Petri Lehtinen74d6c252012-12-15 22:39:32 +02001688.. class:: FileType(mode='r', bufsize=-1, encoding=None, errors=None)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001689
1690 The :class:`FileType` factory creates objects that can be passed to the type
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001691 argument of :meth:`ArgumentParser.add_argument`. Arguments that have
Petri Lehtinen74d6c252012-12-15 22:39:32 +02001692 :class:`FileType` objects as their type will open command-line arguments as
1693 files with the requested modes, buffer sizes, encodings and error handling
1694 (see the :func:`open` function for more details)::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001695
Éric Araujoc3ef0372012-02-20 01:44:55 +01001696 >>> parser = argparse.ArgumentParser()
Petri Lehtinen74d6c252012-12-15 22:39:32 +02001697 >>> parser.add_argument('--raw', type=argparse.FileType('wb', 0))
1698 >>> parser.add_argument('out', type=argparse.FileType('w', encoding='UTF-8'))
1699 >>> parser.parse_args(['--raw', 'raw.dat', 'file.txt'])
1700 Namespace(out=<_io.TextIOWrapper name='file.txt' mode='w' encoding='UTF-8'>, raw=<_io.FileIO name='raw.dat' mode='wb'>)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001701
1702 FileType objects understand the pseudo-argument ``'-'`` and automatically
1703 convert this into ``sys.stdin`` for readable :class:`FileType` objects and
Éric Araujoc3ef0372012-02-20 01:44:55 +01001704 ``sys.stdout`` for writable :class:`FileType` objects::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001705
Éric Araujoc3ef0372012-02-20 01:44:55 +01001706 >>> parser = argparse.ArgumentParser()
1707 >>> parser.add_argument('infile', type=argparse.FileType('r'))
1708 >>> parser.parse_args(['-'])
1709 Namespace(infile=<_io.TextIOWrapper name='<stdin>' encoding='UTF-8'>)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001710
R David Murrayfced3ec2013-12-31 11:18:01 -05001711 .. versionadded:: 3.4
1712 The *encodings* and *errors* keyword arguments.
1713
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001714
1715Argument groups
1716^^^^^^^^^^^^^^^
1717
Georg Brandle0bf91d2010-10-17 10:34:28 +00001718.. method:: ArgumentParser.add_argument_group(title=None, description=None)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001719
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001720 By default, :class:`ArgumentParser` groups command-line arguments into
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001721 "positional arguments" and "optional arguments" when displaying help
1722 messages. When there is a better conceptual grouping of arguments than this
1723 default one, appropriate groups can be created using the
1724 :meth:`add_argument_group` method::
1725
1726 >>> parser = argparse.ArgumentParser(prog='PROG', add_help=False)
1727 >>> group = parser.add_argument_group('group')
1728 >>> group.add_argument('--foo', help='foo help')
1729 >>> group.add_argument('bar', help='bar help')
1730 >>> parser.print_help()
1731 usage: PROG [--foo FOO] bar
1732
1733 group:
1734 bar bar help
1735 --foo FOO foo help
1736
1737 The :meth:`add_argument_group` method returns an argument group object which
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001738 has an :meth:`~ArgumentParser.add_argument` method just like a regular
1739 :class:`ArgumentParser`. When an argument is added to the group, the parser
1740 treats it just like a normal argument, but displays the argument in a
1741 separate group for help messages. The :meth:`add_argument_group` method
Georg Brandle0bf91d2010-10-17 10:34:28 +00001742 accepts *title* and *description* arguments which can be used to
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001743 customize this display::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001744
1745 >>> parser = argparse.ArgumentParser(prog='PROG', add_help=False)
1746 >>> group1 = parser.add_argument_group('group1', 'group1 description')
1747 >>> group1.add_argument('foo', help='foo help')
1748 >>> group2 = parser.add_argument_group('group2', 'group2 description')
1749 >>> group2.add_argument('--bar', help='bar help')
1750 >>> parser.print_help()
1751 usage: PROG [--bar BAR] foo
1752
1753 group1:
1754 group1 description
1755
1756 foo foo help
1757
1758 group2:
1759 group2 description
1760
1761 --bar BAR bar help
1762
Sandro Tosi99e7d072012-03-26 19:36:23 +02001763 Note that any arguments not in your user-defined groups will end up back
1764 in the usual "positional arguments" and "optional arguments" sections.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001765
1766
1767Mutual exclusion
1768^^^^^^^^^^^^^^^^
1769
Georg Brandled86ff82013-10-06 13:09:59 +02001770.. method:: ArgumentParser.add_mutually_exclusive_group(required=False)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001771
Ezio Melotti0ee9c1b2011-04-21 16:12:17 +03001772 Create a mutually exclusive group. :mod:`argparse` will make sure that only
1773 one of the arguments in the mutually exclusive group was present on the
1774 command line::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001775
1776 >>> parser = argparse.ArgumentParser(prog='PROG')
1777 >>> group = parser.add_mutually_exclusive_group()
1778 >>> group.add_argument('--foo', action='store_true')
1779 >>> group.add_argument('--bar', action='store_false')
1780 >>> parser.parse_args(['--foo'])
1781 Namespace(bar=True, foo=True)
1782 >>> parser.parse_args(['--bar'])
1783 Namespace(bar=False, foo=False)
1784 >>> parser.parse_args(['--foo', '--bar'])
1785 usage: PROG [-h] [--foo | --bar]
1786 PROG: error: argument --bar: not allowed with argument --foo
1787
Georg Brandle0bf91d2010-10-17 10:34:28 +00001788 The :meth:`add_mutually_exclusive_group` method also accepts a *required*
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001789 argument, to indicate that at least one of the mutually exclusive arguments
1790 is required::
1791
1792 >>> parser = argparse.ArgumentParser(prog='PROG')
1793 >>> group = parser.add_mutually_exclusive_group(required=True)
1794 >>> group.add_argument('--foo', action='store_true')
1795 >>> group.add_argument('--bar', action='store_false')
1796 >>> parser.parse_args([])
1797 usage: PROG [-h] (--foo | --bar)
1798 PROG: error: one of the arguments --foo --bar is required
1799
1800 Note that currently mutually exclusive argument groups do not support the
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001801 *title* and *description* arguments of
1802 :meth:`~ArgumentParser.add_argument_group`.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001803
1804
1805Parser defaults
1806^^^^^^^^^^^^^^^
1807
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001808.. method:: ArgumentParser.set_defaults(**kwargs)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001809
1810 Most of the time, the attributes of the object returned by :meth:`parse_args`
Éric Araujod9d7bca2011-08-10 04:19:03 +02001811 will be fully determined by inspecting the command-line arguments and the argument
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001812 actions. :meth:`set_defaults` allows some additional
Georg Brandl69518bc2011-04-16 16:44:54 +02001813 attributes that are determined without any inspection of the command line to
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001814 be added::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001815
1816 >>> parser = argparse.ArgumentParser()
1817 >>> parser.add_argument('foo', type=int)
1818 >>> parser.set_defaults(bar=42, baz='badger')
1819 >>> parser.parse_args(['736'])
1820 Namespace(bar=42, baz='badger', foo=736)
1821
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001822 Note that parser-level defaults always override argument-level defaults::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001823
1824 >>> parser = argparse.ArgumentParser()
1825 >>> parser.add_argument('--foo', default='bar')
1826 >>> parser.set_defaults(foo='spam')
1827 >>> parser.parse_args([])
1828 Namespace(foo='spam')
1829
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001830 Parser-level defaults can be particularly useful when working with multiple
1831 parsers. See the :meth:`~ArgumentParser.add_subparsers` method for an
1832 example of this type.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001833
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001834.. method:: ArgumentParser.get_default(dest)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001835
1836 Get the default value for a namespace attribute, as set by either
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001837 :meth:`~ArgumentParser.add_argument` or by
1838 :meth:`~ArgumentParser.set_defaults`::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001839
1840 >>> parser = argparse.ArgumentParser()
1841 >>> parser.add_argument('--foo', default='badger')
1842 >>> parser.get_default('foo')
1843 'badger'
1844
1845
1846Printing help
1847^^^^^^^^^^^^^
1848
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001849In most typical applications, :meth:`~ArgumentParser.parse_args` will take
1850care of formatting and printing any usage or error messages. However, several
1851formatting methods are available:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001852
Georg Brandle0bf91d2010-10-17 10:34:28 +00001853.. method:: ArgumentParser.print_usage(file=None)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001854
1855 Print a brief description of how the :class:`ArgumentParser` should be
R. David Murray32e17712010-12-18 16:39:06 +00001856 invoked on the command line. If *file* is ``None``, :data:`sys.stdout` is
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001857 assumed.
1858
Georg Brandle0bf91d2010-10-17 10:34:28 +00001859.. method:: ArgumentParser.print_help(file=None)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001860
1861 Print a help message, including the program usage and information about the
Georg Brandle0bf91d2010-10-17 10:34:28 +00001862 arguments registered with the :class:`ArgumentParser`. If *file* is
R. David Murray32e17712010-12-18 16:39:06 +00001863 ``None``, :data:`sys.stdout` is assumed.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001864
1865There are also variants of these methods that simply return a string instead of
1866printing it:
1867
Georg Brandle0bf91d2010-10-17 10:34:28 +00001868.. method:: ArgumentParser.format_usage()
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001869
1870 Return a string containing a brief description of how the
1871 :class:`ArgumentParser` should be invoked on the command line.
1872
Georg Brandle0bf91d2010-10-17 10:34:28 +00001873.. method:: ArgumentParser.format_help()
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001874
1875 Return a string containing a help message, including the program usage and
1876 information about the arguments registered with the :class:`ArgumentParser`.
1877
1878
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001879Partial parsing
1880^^^^^^^^^^^^^^^
1881
Georg Brandle0bf91d2010-10-17 10:34:28 +00001882.. method:: ArgumentParser.parse_known_args(args=None, namespace=None)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001883
Georg Brandl69518bc2011-04-16 16:44:54 +02001884Sometimes a script may only parse a few of the command-line arguments, passing
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001885the remaining arguments on to another script or program. In these cases, the
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001886:meth:`~ArgumentParser.parse_known_args` method can be useful. It works much like
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001887:meth:`~ArgumentParser.parse_args` except that it does not produce an error when
1888extra arguments are present. Instead, it returns a two item tuple containing
1889the populated namespace and the list of remaining argument strings.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001890
1891::
1892
1893 >>> parser = argparse.ArgumentParser()
1894 >>> parser.add_argument('--foo', action='store_true')
1895 >>> parser.add_argument('bar')
1896 >>> parser.parse_known_args(['--foo', '--badger', 'BAR', 'spam'])
1897 (Namespace(bar='BAR', foo=True), ['--badger', 'spam'])
1898
Eli Benderskyf3114532013-12-02 05:49:54 -08001899.. warning::
1900 :ref:`Prefix matching <prefix-matching>` rules apply to
1901 :meth:`parse_known_args`. The parser may consume an option even if it's just
1902 a prefix of one of its known options, instead of leaving it in the remaining
1903 arguments list.
1904
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001905
1906Customizing file parsing
1907^^^^^^^^^^^^^^^^^^^^^^^^
1908
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001909.. method:: ArgumentParser.convert_arg_line_to_args(arg_line)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001910
Georg Brandle0bf91d2010-10-17 10:34:28 +00001911 Arguments that are read from a file (see the *fromfile_prefix_chars*
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001912 keyword argument to the :class:`ArgumentParser` constructor) are read one
Senthil Kumaranb4760ef2015-06-14 17:35:37 -07001913 argument per line. :meth:`convert_arg_line_to_args` can be overridden for
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001914 fancier reading.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001915
Georg Brandle0bf91d2010-10-17 10:34:28 +00001916 This method takes a single argument *arg_line* which is a string read from
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001917 the argument file. It returns a list of arguments parsed from this string.
1918 The method is called once per line read from the argument file, in order.
1919
1920 A useful override of this method is one that treats each space-separated word
1921 as an argument::
1922
1923 def convert_arg_line_to_args(self, arg_line):
Berker Peksag8c99a6d2015-04-26 12:09:54 +03001924 return arg_line.split()
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001925
1926
Georg Brandl93754922010-10-17 10:28:04 +00001927Exiting methods
1928^^^^^^^^^^^^^^^
1929
1930.. method:: ArgumentParser.exit(status=0, message=None)
1931
1932 This method terminates the program, exiting with the specified *status*
1933 and, if given, it prints a *message* before that.
1934
1935.. method:: ArgumentParser.error(message)
1936
1937 This method prints a usage message including the *message* to the
Senthil Kumaran86a1a892011-08-03 07:42:18 +08001938 standard error and terminates the program with a status code of 2.
Georg Brandl93754922010-10-17 10:28:04 +00001939
Raymond Hettinger677e10a2010-12-07 06:45:30 +00001940.. _upgrading-optparse-code:
Georg Brandl93754922010-10-17 10:28:04 +00001941
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001942Upgrading optparse code
1943-----------------------
1944
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001945Originally, the :mod:`argparse` module had attempted to maintain compatibility
Ezio Melotti0ee9c1b2011-04-21 16:12:17 +03001946with :mod:`optparse`. However, :mod:`optparse` was difficult to extend
1947transparently, particularly with the changes required to support the new
1948``nargs=`` specifiers and better usage messages. When most everything in
1949:mod:`optparse` had either been copy-pasted over or monkey-patched, it no
1950longer seemed practical to try to maintain the backwards compatibility.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001951
Berker Peksag6c1f0ad2014-09-26 15:34:26 +03001952The :mod:`argparse` module improves on the standard library :mod:`optparse`
1953module in a number of ways including:
1954
1955* Handling positional arguments.
1956* Supporting sub-commands.
1957* Allowing alternative option prefixes like ``+`` and ``/``.
1958* Handling zero-or-more and one-or-more style arguments.
1959* Producing more informative usage messages.
1960* Providing a much simpler interface for custom ``type`` and ``action``.
1961
Ezio Melotti0ee9c1b2011-04-21 16:12:17 +03001962A partial upgrade path from :mod:`optparse` to :mod:`argparse`:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001963
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001964* Replace all :meth:`optparse.OptionParser.add_option` calls with
1965 :meth:`ArgumentParser.add_argument` calls.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001966
R David Murray5e0c5712012-03-30 18:07:42 -04001967* Replace ``(options, args) = parser.parse_args()`` with ``args =
Georg Brandlc9007082011-01-09 09:04:08 +00001968 parser.parse_args()`` and add additional :meth:`ArgumentParser.add_argument`
R David Murray5e0c5712012-03-30 18:07:42 -04001969 calls for the positional arguments. Keep in mind that what was previously
1970 called ``options``, now in :mod:`argparse` context is called ``args``.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001971
1972* Replace callback actions and the ``callback_*`` keyword arguments with
1973 ``type`` or ``action`` arguments.
1974
1975* Replace string names for ``type`` keyword arguments with the corresponding
1976 type objects (e.g. int, float, complex, etc).
1977
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001978* Replace :class:`optparse.Values` with :class:`Namespace` and
1979 :exc:`optparse.OptionError` and :exc:`optparse.OptionValueError` with
1980 :exc:`ArgumentError`.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001981
1982* Replace strings with implicit arguments such as ``%default`` or ``%prog`` with
Ezio Melotticca4ef82011-04-21 15:26:46 +03001983 the standard Python syntax to use dictionaries to format strings, that is,
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001984 ``%(default)s`` and ``%(prog)s``.
Steven Bethard59710962010-05-24 03:21:08 +00001985
1986* Replace the OptionParser constructor ``version`` argument with a call to
Martin Panterd21e0b52015-10-10 10:36:22 +00001987 ``parser.add_argument('--version', action='version', version='<the version>')``.