blob: ab095e4d424691867a13e72f152b32f6aaf74f74 [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
49 $ prog.py -h
50 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
64 $ prog.py 1 2 3 4
65 4
66
67 $ prog.py 1 2 3 4 --sum
68 10
69
70If invalid arguments are passed in, it will issue an error::
71
72 $ prog.py a b c
73 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
140 Create a new :class:`ArgumentParser` object. Each parameter has its own more
141 detailed description below, but in short they are:
142
143 * description_ - Text to display before the argument help.
144
145 * epilog_ - Text to display after the argument help.
146
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000147 * add_help_ - Add a -h/--help option to the parser. (default: ``True``)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000148
149 * argument_default_ - Set the global default value for arguments.
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000150 (default: ``None``)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000151
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000152 * parents_ - A list of :class:`ArgumentParser` objects whose arguments should
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000153 also be included.
154
155 * prefix_chars_ - The set of characters that prefix optional arguments.
156 (default: '-')
157
158 * fromfile_prefix_chars_ - The set of characters that prefix files from
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000159 which additional arguments should be read. (default: ``None``)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000160
161 * formatter_class_ - A class for customizing the help output.
162
163 * conflict_handler_ - Usually unnecessary, defines strategy for resolving
164 conflicting optionals.
165
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000166 * prog_ - The name of the program (default:
Éric Araujo37b5f9e2011-09-01 03:19:30 +0200167 ``sys.argv[0]``)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000168
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000169 * usage_ - The string describing the program usage (default: generated)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000170
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000171The following sections describe how each of these are used.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000172
173
174description
175^^^^^^^^^^^
176
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000177Most calls to the :class:`ArgumentParser` constructor will use the
178``description=`` keyword argument. This argument gives a brief description of
179what the program does and how it works. In help messages, the description is
180displayed between the command-line usage string and the help messages for the
181various arguments::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000182
183 >>> parser = argparse.ArgumentParser(description='A foo that bars')
184 >>> parser.print_help()
185 usage: argparse.py [-h]
186
187 A foo that bars
188
189 optional arguments:
190 -h, --help show this help message and exit
191
192By default, the description will be line-wrapped so that it fits within the
193given space. To change this behavior, see the formatter_class_ argument.
194
195
196epilog
197^^^^^^
198
199Some programs like to display additional description of the program after the
200description of the arguments. Such text can be specified using the ``epilog=``
201argument to :class:`ArgumentParser`::
202
203 >>> parser = argparse.ArgumentParser(
204 ... description='A foo that bars',
205 ... epilog="And that's how you'd foo a bar")
206 >>> parser.print_help()
207 usage: argparse.py [-h]
208
209 A foo that bars
210
211 optional arguments:
212 -h, --help show this help message and exit
213
214 And that's how you'd foo a bar
215
216As with the description_ argument, the ``epilog=`` text is by default
217line-wrapped, but this behavior can be adjusted with the formatter_class_
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000218argument to :class:`ArgumentParser`.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000219
220
221add_help
222^^^^^^^^
223
R. David Murray88c49fe2010-08-03 17:56:09 +0000224By default, ArgumentParser objects add an option which simply displays
225the parser's help message. For example, consider a file named
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000226``myprogram.py`` containing the following code::
227
228 import argparse
229 parser = argparse.ArgumentParser()
230 parser.add_argument('--foo', help='foo help')
231 args = parser.parse_args()
232
Georg Brandl884843d2011-04-16 17:02:58 +0200233If ``-h`` or ``--help`` is supplied at the command line, the ArgumentParser
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000234help will be printed::
235
236 $ python myprogram.py --help
237 usage: myprogram.py [-h] [--foo FOO]
238
239 optional arguments:
240 -h, --help show this help message and exit
241 --foo FOO foo help
242
243Occasionally, it may be useful to disable the addition of this help option.
244This can be achieved by passing ``False`` as the ``add_help=`` argument to
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000245:class:`ArgumentParser`::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000246
247 >>> parser = argparse.ArgumentParser(prog='PROG', add_help=False)
248 >>> parser.add_argument('--foo', help='foo help')
249 >>> parser.print_help()
250 usage: PROG [--foo FOO]
251
252 optional arguments:
253 --foo FOO foo help
254
R. David Murray88c49fe2010-08-03 17:56:09 +0000255The help option is typically ``-h/--help``. The exception to this is
Éric Araujo543edbd2011-08-19 01:45:12 +0200256if the ``prefix_chars=`` is specified and does not include ``-``, in
R. David Murray88c49fe2010-08-03 17:56:09 +0000257which case ``-h`` and ``--help`` are not valid options. In
258this case, the first character in ``prefix_chars`` is used to prefix
259the help options::
260
261 >>> parser = argparse.ArgumentParser(prog='PROG', prefix_chars='+/')
262 >>> parser.print_help()
263 usage: PROG [+h]
264
265 optional arguments:
266 +h, ++help show this help message and exit
267
268
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000269prefix_chars
270^^^^^^^^^^^^
271
Éric Araujo543edbd2011-08-19 01:45:12 +0200272Most command-line options will use ``-`` as the prefix, e.g. ``-f/--foo``.
R. David Murray88c49fe2010-08-03 17:56:09 +0000273Parsers that need to support different or additional prefix
274characters, e.g. for options
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000275like ``+f`` or ``/foo``, may specify them using the ``prefix_chars=`` argument
276to the ArgumentParser constructor::
277
278 >>> parser = argparse.ArgumentParser(prog='PROG', prefix_chars='-+')
279 >>> parser.add_argument('+f')
280 >>> parser.add_argument('++bar')
281 >>> parser.parse_args('+f X ++bar Y'.split())
282 Namespace(bar='Y', f='X')
283
284The ``prefix_chars=`` argument defaults to ``'-'``. Supplying a set of
Éric Araujo543edbd2011-08-19 01:45:12 +0200285characters that does not include ``-`` will cause ``-f/--foo`` options to be
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000286disallowed.
287
288
289fromfile_prefix_chars
290^^^^^^^^^^^^^^^^^^^^^
291
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000292Sometimes, for example when dealing with a particularly long argument lists, it
293may make sense to keep the list of arguments in a file rather than typing it out
294at the command line. If the ``fromfile_prefix_chars=`` argument is given to the
295:class:`ArgumentParser` constructor, then arguments that start with any of the
296specified characters will be treated as files, and will be replaced by the
297arguments they contain. For example::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000298
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000299 >>> with open('args.txt', 'w') as fp:
300 ... fp.write('-f\nbar')
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000301 >>> parser = argparse.ArgumentParser(fromfile_prefix_chars='@')
302 >>> parser.add_argument('-f')
303 >>> parser.parse_args(['-f', 'foo', '@args.txt'])
304 Namespace(f='bar')
305
306Arguments read from a file must by default be one per line (but see also
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300307:meth:`~ArgumentParser.convert_arg_line_to_args`) and are treated as if they
308were in the same place as the original file referencing argument on the command
309line. So in the example above, the expression ``['-f', 'foo', '@args.txt']``
310is considered equivalent to the expression ``['-f', 'foo', '-f', 'bar']``.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000311
312The ``fromfile_prefix_chars=`` argument defaults to ``None``, meaning that
313arguments will never be treated as file references.
314
Georg Brandle0bf91d2010-10-17 10:34:28 +0000315
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000316argument_default
317^^^^^^^^^^^^^^^^
318
319Generally, argument defaults are specified either by passing a default to
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300320:meth:`~ArgumentParser.add_argument` or by calling the
321:meth:`~ArgumentParser.set_defaults` methods with a specific set of name-value
322pairs. Sometimes however, it may be useful to specify a single parser-wide
323default for arguments. This can be accomplished by passing the
324``argument_default=`` keyword argument to :class:`ArgumentParser`. For example,
325to globally suppress attribute creation on :meth:`~ArgumentParser.parse_args`
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000326calls, we supply ``argument_default=SUPPRESS``::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000327
328 >>> parser = argparse.ArgumentParser(argument_default=argparse.SUPPRESS)
329 >>> parser.add_argument('--foo')
330 >>> parser.add_argument('bar', nargs='?')
331 >>> parser.parse_args(['--foo', '1', 'BAR'])
332 Namespace(bar='BAR', foo='1')
333 >>> parser.parse_args([])
334 Namespace()
335
336
337parents
338^^^^^^^
339
340Sometimes, several parsers share a common set of arguments. Rather than
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000341repeating the definitions of these arguments, a single parser with all the
342shared arguments and passed to ``parents=`` argument to :class:`ArgumentParser`
343can be used. The ``parents=`` argument takes a list of :class:`ArgumentParser`
344objects, collects all the positional and optional actions from them, and adds
345these actions to the :class:`ArgumentParser` object being constructed::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000346
347 >>> parent_parser = argparse.ArgumentParser(add_help=False)
348 >>> parent_parser.add_argument('--parent', type=int)
349
350 >>> foo_parser = argparse.ArgumentParser(parents=[parent_parser])
351 >>> foo_parser.add_argument('foo')
352 >>> foo_parser.parse_args(['--parent', '2', 'XXX'])
353 Namespace(foo='XXX', parent=2)
354
355 >>> bar_parser = argparse.ArgumentParser(parents=[parent_parser])
356 >>> bar_parser.add_argument('--bar')
357 >>> bar_parser.parse_args(['--bar', 'YYY'])
358 Namespace(bar='YYY', parent=None)
359
360Note that most parent parsers will specify ``add_help=False``. Otherwise, the
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000361:class:`ArgumentParser` will see two ``-h/--help`` options (one in the parent
362and one in the child) and raise an error.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000363
Steven Bethardd186f992011-03-26 21:49:00 +0100364.. note::
365 You must fully initialize the parsers before passing them via ``parents=``.
366 If you change the parent parsers after the child parser, those changes will
367 not be reflected in the child.
368
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000369
370formatter_class
371^^^^^^^^^^^^^^^
372
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000373:class:`ArgumentParser` objects allow the help formatting to be customized by
Ezio Melotti707d1e62011-04-22 01:57:47 +0300374specifying an alternate formatting class. Currently, there are four such
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300375classes:
376
377.. class:: RawDescriptionHelpFormatter
378 RawTextHelpFormatter
379 ArgumentDefaultsHelpFormatter
Ezio Melotti707d1e62011-04-22 01:57:47 +0300380 MetavarTypeHelpFormatter
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000381
Steven Bethard0331e902011-03-26 14:48:04 +0100382:class:`RawDescriptionHelpFormatter` and :class:`RawTextHelpFormatter` give
383more control over how textual descriptions are displayed.
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000384By default, :class:`ArgumentParser` objects line-wrap the description_ and
385epilog_ texts in command-line help messages::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000386
387 >>> parser = argparse.ArgumentParser(
388 ... prog='PROG',
389 ... description='''this description
390 ... was indented weird
391 ... but that is okay''',
392 ... epilog='''
393 ... likewise for this epilog whose whitespace will
394 ... be cleaned up and whose words will be wrapped
395 ... across a couple lines''')
396 >>> parser.print_help()
397 usage: PROG [-h]
398
399 this description was indented weird but that is okay
400
401 optional arguments:
402 -h, --help show this help message and exit
403
404 likewise for this epilog whose whitespace will be cleaned up and whose words
405 will be wrapped across a couple lines
406
Steven Bethard0331e902011-03-26 14:48:04 +0100407Passing :class:`RawDescriptionHelpFormatter` as ``formatter_class=``
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000408indicates that description_ and epilog_ are already correctly formatted and
409should not be line-wrapped::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000410
411 >>> parser = argparse.ArgumentParser(
412 ... prog='PROG',
413 ... formatter_class=argparse.RawDescriptionHelpFormatter,
414 ... description=textwrap.dedent('''\
415 ... Please do not mess up this text!
416 ... --------------------------------
417 ... I have indented it
418 ... exactly the way
419 ... I want it
420 ... '''))
421 >>> parser.print_help()
422 usage: PROG [-h]
423
424 Please do not mess up this text!
425 --------------------------------
426 I have indented it
427 exactly the way
428 I want it
429
430 optional arguments:
431 -h, --help show this help message and exit
432
Steven Bethard0331e902011-03-26 14:48:04 +0100433:class:`RawTextHelpFormatter` maintains whitespace for all sorts of help text,
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000434including argument descriptions.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000435
Steven Bethard0331e902011-03-26 14:48:04 +0100436:class:`ArgumentDefaultsHelpFormatter` automatically adds information about
437default values to each of the argument help messages::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000438
439 >>> parser = argparse.ArgumentParser(
440 ... prog='PROG',
441 ... formatter_class=argparse.ArgumentDefaultsHelpFormatter)
442 >>> parser.add_argument('--foo', type=int, default=42, help='FOO!')
443 >>> parser.add_argument('bar', nargs='*', default=[1, 2, 3], help='BAR!')
444 >>> parser.print_help()
445 usage: PROG [-h] [--foo FOO] [bar [bar ...]]
446
447 positional arguments:
448 bar BAR! (default: [1, 2, 3])
449
450 optional arguments:
451 -h, --help show this help message and exit
452 --foo FOO FOO! (default: 42)
453
Steven Bethard0331e902011-03-26 14:48:04 +0100454:class:`MetavarTypeHelpFormatter` uses the name of the type_ argument for each
Ezio Melottif1064492011-10-19 11:06:26 +0300455argument as the display name for its values (rather than using the dest_
Steven Bethard0331e902011-03-26 14:48:04 +0100456as the regular formatter does)::
457
458 >>> parser = argparse.ArgumentParser(
459 ... prog='PROG',
460 ... formatter_class=argparse.MetavarTypeHelpFormatter)
461 >>> parser.add_argument('--foo', type=int)
462 >>> parser.add_argument('bar', type=float)
463 >>> parser.print_help()
464 usage: PROG [-h] [--foo int] float
465
466 positional arguments:
467 float
468
469 optional arguments:
470 -h, --help show this help message and exit
471 --foo int
472
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000473
474conflict_handler
475^^^^^^^^^^^^^^^^
476
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000477:class:`ArgumentParser` objects do not allow two actions with the same option
478string. By default, :class:`ArgumentParser` objects raises an exception if an
479attempt is made to create an argument with an option string that is already in
480use::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000481
482 >>> parser = argparse.ArgumentParser(prog='PROG')
483 >>> parser.add_argument('-f', '--foo', help='old foo help')
484 >>> parser.add_argument('--foo', help='new foo help')
485 Traceback (most recent call last):
486 ..
487 ArgumentError: argument --foo: conflicting option string(s): --foo
488
489Sometimes (e.g. when using parents_) it may be useful to simply override any
490older arguments with the same option string. To get this behavior, the value
491``'resolve'`` can be supplied to the ``conflict_handler=`` argument of
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000492:class:`ArgumentParser`::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000493
494 >>> parser = argparse.ArgumentParser(prog='PROG', conflict_handler='resolve')
495 >>> parser.add_argument('-f', '--foo', help='old foo help')
496 >>> parser.add_argument('--foo', help='new foo help')
497 >>> parser.print_help()
498 usage: PROG [-h] [-f FOO] [--foo FOO]
499
500 optional arguments:
501 -h, --help show this help message and exit
502 -f FOO old foo help
503 --foo FOO new foo help
504
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000505Note that :class:`ArgumentParser` objects only remove an action if all of its
506option strings are overridden. So, in the example above, the old ``-f/--foo``
507action is retained as the ``-f`` action, because only the ``--foo`` option
508string was overridden.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000509
510
511prog
512^^^^
513
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000514By default, :class:`ArgumentParser` objects uses ``sys.argv[0]`` to determine
515how to display the name of the program in help messages. This default is almost
Ezio Melottif82340d2010-05-27 22:38:16 +0000516always desirable because it will make the help messages match how the program was
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000517invoked on the command line. For example, consider a file named
518``myprogram.py`` with the following code::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000519
520 import argparse
521 parser = argparse.ArgumentParser()
522 parser.add_argument('--foo', help='foo help')
523 args = parser.parse_args()
524
525The help for this program will display ``myprogram.py`` as the program name
526(regardless of where the program was invoked from)::
527
528 $ python myprogram.py --help
529 usage: myprogram.py [-h] [--foo FOO]
530
531 optional arguments:
532 -h, --help show this help message and exit
533 --foo FOO foo help
534 $ cd ..
535 $ python subdir\myprogram.py --help
536 usage: myprogram.py [-h] [--foo FOO]
537
538 optional arguments:
539 -h, --help show this help message and exit
540 --foo FOO foo help
541
542To change this default behavior, another value can be supplied using the
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000543``prog=`` argument to :class:`ArgumentParser`::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000544
545 >>> parser = argparse.ArgumentParser(prog='myprogram')
546 >>> parser.print_help()
547 usage: myprogram [-h]
548
549 optional arguments:
550 -h, --help show this help message and exit
551
552Note that the program name, whether determined from ``sys.argv[0]`` or from the
553``prog=`` argument, is available to help messages using the ``%(prog)s`` format
554specifier.
555
556::
557
558 >>> parser = argparse.ArgumentParser(prog='myprogram')
559 >>> parser.add_argument('--foo', help='foo of the %(prog)s program')
560 >>> parser.print_help()
561 usage: myprogram [-h] [--foo FOO]
562
563 optional arguments:
564 -h, --help show this help message and exit
565 --foo FOO foo of the myprogram program
566
567
568usage
569^^^^^
570
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000571By default, :class:`ArgumentParser` calculates the usage message from the
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000572arguments it contains::
573
574 >>> parser = argparse.ArgumentParser(prog='PROG')
575 >>> parser.add_argument('--foo', nargs='?', help='foo help')
576 >>> parser.add_argument('bar', nargs='+', help='bar help')
577 >>> parser.print_help()
578 usage: PROG [-h] [--foo [FOO]] bar [bar ...]
579
580 positional arguments:
581 bar bar help
582
583 optional arguments:
584 -h, --help show this help message and exit
585 --foo [FOO] foo help
586
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000587The default message can be overridden with the ``usage=`` keyword argument::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000588
589 >>> parser = argparse.ArgumentParser(prog='PROG', usage='%(prog)s [options]')
590 >>> parser.add_argument('--foo', nargs='?', help='foo help')
591 >>> parser.add_argument('bar', nargs='+', help='bar help')
592 >>> parser.print_help()
593 usage: PROG [options]
594
595 positional arguments:
596 bar bar help
597
598 optional arguments:
599 -h, --help show this help message and exit
600 --foo [FOO] foo help
601
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000602The ``%(prog)s`` format specifier is available to fill in the program name in
603your usage messages.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000604
605
606The add_argument() method
607-------------------------
608
Georg Brandlc9007082011-01-09 09:04:08 +0000609.. method:: ArgumentParser.add_argument(name or flags..., [action], [nargs], \
610 [const], [default], [type], [choices], [required], \
611 [help], [metavar], [dest])
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000612
Georg Brandl69518bc2011-04-16 16:44:54 +0200613 Define how a single command-line argument should be parsed. Each parameter
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000614 has its own more detailed description below, but in short they are:
615
616 * `name or flags`_ - Either a name or a list of option strings, e.g. ``foo``
Ezio Melottidca309d2011-04-21 23:09:27 +0300617 or ``-f, --foo``.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000618
619 * action_ - The basic type of action to be taken when this argument is
Georg Brandl69518bc2011-04-16 16:44:54 +0200620 encountered at the command line.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000621
622 * nargs_ - The number of command-line arguments that should be consumed.
623
624 * const_ - A constant value required by some action_ and nargs_ selections.
625
626 * default_ - The value produced if the argument is absent from the
Georg Brandl69518bc2011-04-16 16:44:54 +0200627 command line.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000628
Ezio Melotti2409d772011-04-16 23:13:50 +0300629 * type_ - The type to which the command-line argument should be converted.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000630
631 * choices_ - A container of the allowable values for the argument.
632
633 * required_ - Whether or not the command-line option may be omitted
634 (optionals only).
635
636 * help_ - A brief description of what the argument does.
637
638 * metavar_ - A name for the argument in usage messages.
639
640 * dest_ - The name of the attribute to be added to the object returned by
641 :meth:`parse_args`.
642
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000643The following sections describe how each of these are used.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000644
Georg Brandle0bf91d2010-10-17 10:34:28 +0000645
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000646name or flags
647^^^^^^^^^^^^^
648
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300649The :meth:`~ArgumentParser.add_argument` method must know whether an optional
650argument, like ``-f`` or ``--foo``, or a positional argument, like a list of
651filenames, is expected. The first arguments passed to
652:meth:`~ArgumentParser.add_argument` must therefore be either a series of
653flags, or a simple argument name. For example, an optional argument could
654be created like::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000655
656 >>> parser.add_argument('-f', '--foo')
657
658while a positional argument could be created like::
659
660 >>> parser.add_argument('bar')
661
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300662When :meth:`~ArgumentParser.parse_args` is called, optional arguments will be
663identified by the ``-`` prefix, and the remaining arguments will be assumed to
664be positional::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000665
666 >>> parser = argparse.ArgumentParser(prog='PROG')
667 >>> parser.add_argument('-f', '--foo')
668 >>> parser.add_argument('bar')
669 >>> parser.parse_args(['BAR'])
670 Namespace(bar='BAR', foo=None)
671 >>> parser.parse_args(['BAR', '--foo', 'FOO'])
672 Namespace(bar='BAR', foo='FOO')
673 >>> parser.parse_args(['--foo', 'FOO'])
674 usage: PROG [-h] [-f FOO] bar
675 PROG: error: too few arguments
676
Georg Brandle0bf91d2010-10-17 10:34:28 +0000677
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000678action
679^^^^^^
680
Éric Araujod9d7bca2011-08-10 04:19:03 +0200681:class:`ArgumentParser` objects associate command-line arguments with actions. These
682actions can do just about anything with the command-line arguments associated with
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000683them, though most actions simply add an attribute to the object returned by
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300684:meth:`~ArgumentParser.parse_args`. The ``action`` keyword argument specifies
Éric Araujod9d7bca2011-08-10 04:19:03 +0200685how the command-line arguments should be handled. The supported actions are:
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000686
687* ``'store'`` - This just stores the argument's value. This is the default
Ezio Melotti2f1db7d2011-04-21 23:06:48 +0300688 action. For example::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000689
690 >>> parser = argparse.ArgumentParser()
691 >>> parser.add_argument('--foo')
692 >>> parser.parse_args('--foo 1'.split())
693 Namespace(foo='1')
694
695* ``'store_const'`` - This stores the value specified by the const_ keyword
Ezio Melotti2f1db7d2011-04-21 23:06:48 +0300696 argument. (Note that the const_ keyword argument defaults to the rather
697 unhelpful ``None``.) The ``'store_const'`` action is most commonly used with
698 optional arguments that specify some sort of flag. For example::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000699
700 >>> parser = argparse.ArgumentParser()
701 >>> parser.add_argument('--foo', action='store_const', const=42)
702 >>> parser.parse_args('--foo'.split())
703 Namespace(foo=42)
704
705* ``'store_true'`` and ``'store_false'`` - These store the values ``True`` and
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000706 ``False`` respectively. These are special cases of ``'store_const'``. For
707 example::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000708
709 >>> parser = argparse.ArgumentParser()
710 >>> parser.add_argument('--foo', action='store_true')
711 >>> parser.add_argument('--bar', action='store_false')
712 >>> parser.parse_args('--foo --bar'.split())
713 Namespace(bar=False, foo=True)
714
715* ``'append'`` - This stores a list, and appends each argument value to the
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000716 list. This is useful to allow an option to be specified multiple times.
717 Example usage::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000718
719 >>> parser = argparse.ArgumentParser()
720 >>> parser.add_argument('--foo', action='append')
721 >>> parser.parse_args('--foo 1 --foo 2'.split())
722 Namespace(foo=['1', '2'])
723
724* ``'append_const'`` - This stores a list, and appends the value specified by
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000725 the const_ keyword argument to the list. (Note that the const_ keyword
726 argument defaults to ``None``.) The ``'append_const'`` action is typically
727 useful when multiple arguments need to store constants to the same list. For
728 example::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000729
730 >>> parser = argparse.ArgumentParser()
731 >>> parser.add_argument('--str', dest='types', action='append_const', const=str)
732 >>> parser.add_argument('--int', dest='types', action='append_const', const=int)
733 >>> parser.parse_args('--str --int'.split())
Florent Xicluna74e64952011-10-28 11:21:19 +0200734 Namespace(types=[<class 'str'>, <class 'int'>])
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000735
Sandro Tosi98492a52012-01-04 23:25:04 +0100736* ``'count'`` - This counts the number of times a keyword argument occurs. For
737 example, this is useful for increasing verbosity levels::
738
739 >>> parser = argparse.ArgumentParser()
740 >>> parser.add_argument('--verbose', '-v', action='count')
741 >>> parser.parse_args('-vvv'.split())
742 Namespace(verbose=3)
743
744* ``'help'`` - This prints a complete help message for all the options in the
745 current parser and then exits. By default a help action is automatically
746 added to the parser. See :class:`ArgumentParser` for details of how the
747 output is created.
748
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000749* ``'version'`` - This expects a ``version=`` keyword argument in the
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300750 :meth:`~ArgumentParser.add_argument` call, and prints version information
Éric Araujoc3ef0372012-02-20 01:44:55 +0100751 and exits when invoked::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000752
753 >>> import argparse
754 >>> parser = argparse.ArgumentParser(prog='PROG')
Steven Bethard59710962010-05-24 03:21:08 +0000755 >>> parser.add_argument('--version', action='version', version='%(prog)s 2.0')
756 >>> parser.parse_args(['--version'])
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000757 PROG 2.0
758
759You can also specify an arbitrary action by passing an object that implements
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000760the Action API. The easiest way to do this is to extend
761:class:`argparse.Action`, supplying an appropriate ``__call__`` method. The
762``__call__`` method should accept four parameters:
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000763
764* ``parser`` - The ArgumentParser object which contains this action.
765
Éric Araujo63b18a42011-07-29 17:59:17 +0200766* ``namespace`` - The :class:`Namespace` object that will be returned by
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300767 :meth:`~ArgumentParser.parse_args`. Most actions add an attribute to this
768 object.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000769
Éric Araujod9d7bca2011-08-10 04:19:03 +0200770* ``values`` - The associated command-line arguments, with any type conversions
771 applied. (Type conversions are specified with the type_ keyword argument to
Sandro Tosiee903c52012-08-12 10:49:26 +0200772 :meth:`~ArgumentParser.add_argument`.)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000773
774* ``option_string`` - The option string that was used to invoke this action.
775 The ``option_string`` argument is optional, and will be absent if the action
776 is associated with a positional argument.
777
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000778An example of a custom action::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000779
780 >>> class FooAction(argparse.Action):
781 ... def __call__(self, parser, namespace, values, option_string=None):
Georg Brandl571a9532010-07-26 17:00:20 +0000782 ... print('%r %r %r' % (namespace, values, option_string))
783 ... setattr(namespace, self.dest, values)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000784 ...
785 >>> parser = argparse.ArgumentParser()
786 >>> parser.add_argument('--foo', action=FooAction)
787 >>> parser.add_argument('bar', action=FooAction)
788 >>> args = parser.parse_args('1 --foo 2'.split())
789 Namespace(bar=None, foo=None) '1' None
790 Namespace(bar='1', foo=None) '2' '--foo'
791 >>> args
792 Namespace(bar='1', foo='2')
793
794
795nargs
796^^^^^
797
798ArgumentParser objects usually associate a single command-line argument with a
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000799single action to be taken. The ``nargs`` keyword argument associates a
Ezio Melotti00f53af2011-04-21 22:56:51 +0300800different number of command-line arguments with a single action. The supported
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000801values are:
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000802
Éric Araujoc3ef0372012-02-20 01:44:55 +0100803* ``N`` (an integer). ``N`` arguments from the command line will be gathered
804 together into a list. For example::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000805
Georg Brandl682d7e02010-10-06 10:26:05 +0000806 >>> parser = argparse.ArgumentParser()
807 >>> parser.add_argument('--foo', nargs=2)
808 >>> parser.add_argument('bar', nargs=1)
809 >>> parser.parse_args('c --foo a b'.split())
810 Namespace(bar=['c'], foo=['a', 'b'])
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000811
Georg Brandl682d7e02010-10-06 10:26:05 +0000812 Note that ``nargs=1`` produces a list of one item. This is different from
813 the default, in which the item is produced by itself.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000814
Éric Araujofde92422011-08-19 01:30:26 +0200815* ``'?'``. One argument will be consumed from the command line if possible, and
816 produced as a single item. If no command-line argument is present, the value from
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000817 default_ will be produced. Note that for optional arguments, there is an
818 additional case - the option string is present but not followed by a
Éric Araujofde92422011-08-19 01:30:26 +0200819 command-line argument. In this case the value from const_ will be produced. Some
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000820 examples to illustrate this::
821
822 >>> parser = argparse.ArgumentParser()
823 >>> parser.add_argument('--foo', nargs='?', const='c', default='d')
824 >>> parser.add_argument('bar', nargs='?', default='d')
825 >>> parser.parse_args('XX --foo YY'.split())
826 Namespace(bar='XX', foo='YY')
827 >>> parser.parse_args('XX --foo'.split())
828 Namespace(bar='XX', foo='c')
829 >>> parser.parse_args(''.split())
830 Namespace(bar='d', foo='d')
831
832 One of the more common uses of ``nargs='?'`` is to allow optional input and
833 output files::
834
835 >>> parser = argparse.ArgumentParser()
Georg Brandle0bf91d2010-10-17 10:34:28 +0000836 >>> parser.add_argument('infile', nargs='?', type=argparse.FileType('r'),
837 ... default=sys.stdin)
838 >>> parser.add_argument('outfile', nargs='?', type=argparse.FileType('w'),
839 ... default=sys.stdout)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000840 >>> parser.parse_args(['input.txt', 'output.txt'])
Georg Brandl04536b02011-01-09 09:31:01 +0000841 Namespace(infile=<_io.TextIOWrapper name='input.txt' encoding='UTF-8'>,
842 outfile=<_io.TextIOWrapper name='output.txt' encoding='UTF-8'>)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000843 >>> parser.parse_args([])
Georg Brandl04536b02011-01-09 09:31:01 +0000844 Namespace(infile=<_io.TextIOWrapper name='<stdin>' encoding='UTF-8'>,
845 outfile=<_io.TextIOWrapper name='<stdout>' encoding='UTF-8'>)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000846
Éric Araujod9d7bca2011-08-10 04:19:03 +0200847* ``'*'``. All command-line arguments present are gathered into a list. Note that
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000848 it generally doesn't make much sense to have more than one positional argument
849 with ``nargs='*'``, but multiple optional arguments with ``nargs='*'`` is
850 possible. For example::
851
852 >>> parser = argparse.ArgumentParser()
853 >>> parser.add_argument('--foo', nargs='*')
854 >>> parser.add_argument('--bar', nargs='*')
855 >>> parser.add_argument('baz', nargs='*')
856 >>> parser.parse_args('a b --foo x y --bar 1 2'.split())
857 Namespace(bar=['1', '2'], baz=['a', 'b'], foo=['x', 'y'])
858
859* ``'+'``. Just like ``'*'``, all command-line args present are gathered into a
860 list. Additionally, an error message will be generated if there wasn't at
Éric Araujofde92422011-08-19 01:30:26 +0200861 least one command-line argument present. For example::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000862
863 >>> parser = argparse.ArgumentParser(prog='PROG')
864 >>> parser.add_argument('foo', nargs='+')
865 >>> parser.parse_args('a b'.split())
866 Namespace(foo=['a', 'b'])
867 >>> parser.parse_args(''.split())
868 usage: PROG [-h] foo [foo ...]
869 PROG: error: too few arguments
870
Sandro Tosida8e11a2012-01-19 22:23:00 +0100871* ``argparse.REMAINDER``. All the remaining command-line arguments are gathered
872 into a list. This is commonly useful for command line utilities that dispatch
Éric Araujoc3ef0372012-02-20 01:44:55 +0100873 to other command line utilities::
Sandro Tosi16bd0b42012-01-19 21:59:55 +0100874
875 >>> parser = argparse.ArgumentParser(prog='PROG')
876 >>> parser.add_argument('--foo')
877 >>> parser.add_argument('command')
878 >>> parser.add_argument('args', nargs=argparse.REMAINDER)
Sandro Tosi04676862012-02-19 19:54:00 +0100879 >>> print(parser.parse_args('--foo B cmd --arg1 XX ZZ'.split()))
Sandro Tosida8e11a2012-01-19 22:23:00 +0100880 Namespace(args=['--arg1', 'XX', 'ZZ'], command='cmd', foo='B')
Sandro Tosi16bd0b42012-01-19 21:59:55 +0100881
Éric Araujod9d7bca2011-08-10 04:19:03 +0200882If the ``nargs`` keyword argument is not provided, the number of arguments consumed
Éric Araujofde92422011-08-19 01:30:26 +0200883is determined by the action_. Generally this means a single command-line argument
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000884will be consumed and a single item (not a list) will be produced.
885
886
887const
888^^^^^
889
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300890The ``const`` argument of :meth:`~ArgumentParser.add_argument` is used to hold
891constant values that are not read from the command line but are required for
892the various :class:`ArgumentParser` actions. The two most common uses of it are:
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000893
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300894* When :meth:`~ArgumentParser.add_argument` is called with
895 ``action='store_const'`` or ``action='append_const'``. These actions add the
Éric Araujoc3ef0372012-02-20 01:44:55 +0100896 ``const`` value to one of the attributes of the object returned by
897 :meth:`~ArgumentParser.parse_args`. See the action_ description for examples.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000898
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300899* When :meth:`~ArgumentParser.add_argument` is called with option strings
900 (like ``-f`` or ``--foo``) and ``nargs='?'``. This creates an optional
Éric Araujod9d7bca2011-08-10 04:19:03 +0200901 argument that can be followed by zero or one command-line arguments.
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300902 When parsing the command line, if the option string is encountered with no
Éric Araujofde92422011-08-19 01:30:26 +0200903 command-line argument following it, the value of ``const`` will be assumed instead.
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300904 See the nargs_ description for examples.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000905
906The ``const`` keyword argument defaults to ``None``.
907
908
909default
910^^^^^^^
911
912All optional arguments and some positional arguments may be omitted at the
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300913command line. The ``default`` keyword argument of
914:meth:`~ArgumentParser.add_argument`, whose value defaults to ``None``,
Éric Araujofde92422011-08-19 01:30:26 +0200915specifies what value should be used if the command-line argument is not present.
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300916For optional arguments, the ``default`` value is used when the option string
917was not present at the command line::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000918
919 >>> parser = argparse.ArgumentParser()
920 >>> parser.add_argument('--foo', default=42)
921 >>> parser.parse_args('--foo 2'.split())
922 Namespace(foo='2')
923 >>> parser.parse_args(''.split())
924 Namespace(foo=42)
925
Barry Warsaw1dedd0a2012-09-25 10:37:58 -0400926If the ``default`` value is a string, the parser parses the value as if it
927were a command-line argument. In particular, the parser applies any type_
928conversion argument, if provided, before setting the attribute on the
929:class:`Namespace` return value. Otherwise, the parser uses the value as is::
930
931 >>> parser = argparse.ArgumentParser()
932 >>> parser.add_argument('--length', default='10', type=int)
933 >>> parser.add_argument('--width', default=10.5, type=int)
934 >>> parser.parse_args()
935 Namespace(length=10, width=10.5)
936
Éric Araujo543edbd2011-08-19 01:45:12 +0200937For positional arguments with nargs_ equal to ``?`` or ``*``, the ``default`` value
Éric Araujofde92422011-08-19 01:30:26 +0200938is used when no command-line argument was present::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000939
940 >>> parser = argparse.ArgumentParser()
941 >>> parser.add_argument('foo', nargs='?', default=42)
942 >>> parser.parse_args('a'.split())
943 Namespace(foo='a')
944 >>> parser.parse_args(''.split())
945 Namespace(foo=42)
946
947
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000948Providing ``default=argparse.SUPPRESS`` causes no attribute to be added if the
949command-line argument was not present.::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000950
951 >>> parser = argparse.ArgumentParser()
952 >>> parser.add_argument('--foo', default=argparse.SUPPRESS)
953 >>> parser.parse_args([])
954 Namespace()
955 >>> parser.parse_args(['--foo', '1'])
956 Namespace(foo='1')
957
958
959type
960^^^^
961
Éric Araujod9d7bca2011-08-10 04:19:03 +0200962By default, :class:`ArgumentParser` objects read command-line arguments in as simple
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300963strings. However, quite often the command-line string should instead be
964interpreted as another type, like a :class:`float` or :class:`int`. The
965``type`` keyword argument of :meth:`~ArgumentParser.add_argument` allows any
Éric Araujod9d7bca2011-08-10 04:19:03 +0200966necessary type-checking and type conversions to be performed. Common built-in
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300967types and functions can be used directly as the value of the ``type`` argument::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000968
969 >>> parser = argparse.ArgumentParser()
970 >>> parser.add_argument('foo', type=int)
Georg Brandl04536b02011-01-09 09:31:01 +0000971 >>> parser.add_argument('bar', type=open)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000972 >>> parser.parse_args('2 temp.txt'.split())
Georg Brandl04536b02011-01-09 09:31:01 +0000973 Namespace(bar=<_io.TextIOWrapper name='temp.txt' encoding='UTF-8'>, foo=2)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000974
Barry Warsaw1dedd0a2012-09-25 10:37:58 -0400975See the section on the default_ keyword argument for information on when the
976``type`` argument is applied to default arguments.
977
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000978To ease the use of various types of files, the argparse module provides the
979factory FileType which takes the ``mode=`` and ``bufsize=`` arguments of the
Georg Brandl04536b02011-01-09 09:31:01 +0000980:func:`open` function. For example, ``FileType('w')`` can be used to create a
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000981writable file::
982
983 >>> parser = argparse.ArgumentParser()
984 >>> parser.add_argument('bar', type=argparse.FileType('w'))
985 >>> parser.parse_args(['out.txt'])
Georg Brandl04536b02011-01-09 09:31:01 +0000986 Namespace(bar=<_io.TextIOWrapper name='out.txt' encoding='UTF-8'>)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000987
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000988``type=`` can take any callable that takes a single string argument and returns
Éric Araujod9d7bca2011-08-10 04:19:03 +0200989the converted value::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000990
991 >>> def perfect_square(string):
992 ... value = int(string)
993 ... sqrt = math.sqrt(value)
994 ... if sqrt != int(sqrt):
995 ... msg = "%r is not a perfect square" % string
996 ... raise argparse.ArgumentTypeError(msg)
997 ... return value
998 ...
999 >>> parser = argparse.ArgumentParser(prog='PROG')
1000 >>> parser.add_argument('foo', type=perfect_square)
1001 >>> parser.parse_args('9'.split())
1002 Namespace(foo=9)
1003 >>> parser.parse_args('7'.split())
1004 usage: PROG [-h] foo
1005 PROG: error: argument foo: '7' is not a perfect square
1006
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001007The choices_ keyword argument may be more convenient for type checkers that
1008simply check against a range of values::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001009
1010 >>> parser = argparse.ArgumentParser(prog='PROG')
Fred Drake44623062011-03-03 05:27:17 +00001011 >>> parser.add_argument('foo', type=int, choices=range(5, 10))
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001012 >>> parser.parse_args('7'.split())
1013 Namespace(foo=7)
1014 >>> parser.parse_args('11'.split())
1015 usage: PROG [-h] {5,6,7,8,9}
1016 PROG: error: argument foo: invalid choice: 11 (choose from 5, 6, 7, 8, 9)
1017
1018See the choices_ section for more details.
1019
1020
1021choices
1022^^^^^^^
1023
Éric Araujod9d7bca2011-08-10 04:19:03 +02001024Some command-line arguments should be selected from a restricted set of values.
Chris Jerdonek174ef672013-01-11 19:26:44 -08001025These can be handled by passing a container object as the *choices* keyword
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001026argument to :meth:`~ArgumentParser.add_argument`. When the command line is
Chris Jerdonek174ef672013-01-11 19:26:44 -08001027parsed, argument values will be checked, and an error message will be displayed
1028if the argument was not one of the acceptable values::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001029
Chris Jerdonek174ef672013-01-11 19:26:44 -08001030 >>> parser = argparse.ArgumentParser(prog='game.py')
1031 >>> parser.add_argument('move', choices=['rock', 'paper', 'scissors'])
1032 >>> parser.parse_args(['rock'])
1033 Namespace(move='rock')
1034 >>> parser.parse_args(['fire'])
1035 usage: game.py [-h] {rock,paper,scissors}
1036 game.py: error: argument move: invalid choice: 'fire' (choose from 'rock',
1037 'paper', 'scissors')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001038
Chris Jerdonek174ef672013-01-11 19:26:44 -08001039Note that inclusion in the *choices* container is checked after any type_
1040conversions have been performed, so the type of the objects in the *choices*
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001041container should match the type_ specified::
1042
Chris Jerdonek174ef672013-01-11 19:26:44 -08001043 >>> parser = argparse.ArgumentParser(prog='doors.py')
1044 >>> parser.add_argument('door', type=int, choices=range(1, 4))
1045 >>> print(parser.parse_args(['3']))
1046 Namespace(door=3)
1047 >>> parser.parse_args(['4'])
1048 usage: doors.py [-h] {1,2,3}
1049 doors.py: error: argument door: invalid choice: 4 (choose from 1, 2, 3)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001050
Chris Jerdonek174ef672013-01-11 19:26:44 -08001051Any object that supports the ``in`` operator can be passed as the *choices*
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001052value, so :class:`dict` objects, :class:`set` objects, custom containers,
1053etc. are all supported.
1054
1055
1056required
1057^^^^^^^^
1058
Ezio Melotti0ee9c1b2011-04-21 16:12:17 +03001059In general, the :mod:`argparse` module assumes that flags like ``-f`` and ``--bar``
Georg Brandl69518bc2011-04-16 16:44:54 +02001060indicate *optional* arguments, which can always be omitted at the command line.
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001061To make an option *required*, ``True`` can be specified for the ``required=``
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001062keyword argument to :meth:`~ArgumentParser.add_argument`::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001063
1064 >>> parser = argparse.ArgumentParser()
1065 >>> parser.add_argument('--foo', required=True)
1066 >>> parser.parse_args(['--foo', 'BAR'])
1067 Namespace(foo='BAR')
1068 >>> parser.parse_args([])
1069 usage: argparse.py [-h] [--foo FOO]
1070 argparse.py: error: option --foo is required
1071
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001072As the example shows, if an option is marked as ``required``,
1073:meth:`~ArgumentParser.parse_args` will report an error if that option is not
1074present at the command line.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001075
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001076.. note::
1077
1078 Required options are generally considered bad form because users expect
1079 *options* to be *optional*, and thus they should be avoided when possible.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001080
1081
1082help
1083^^^^
1084
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001085The ``help`` value is a string containing a brief description of the argument.
1086When a user requests help (usually by using ``-h`` or ``--help`` at the
Georg Brandl69518bc2011-04-16 16:44:54 +02001087command line), these ``help`` descriptions will be displayed with each
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001088argument::
1089
1090 >>> parser = argparse.ArgumentParser(prog='frobble')
1091 >>> parser.add_argument('--foo', action='store_true',
1092 ... help='foo the bars before frobbling')
1093 >>> parser.add_argument('bar', nargs='+',
1094 ... help='one of the bars to be frobbled')
1095 >>> parser.parse_args('-h'.split())
1096 usage: frobble [-h] [--foo] bar [bar ...]
1097
1098 positional arguments:
1099 bar one of the bars to be frobbled
1100
1101 optional arguments:
1102 -h, --help show this help message and exit
1103 --foo foo the bars before frobbling
1104
1105The ``help`` strings can include various format specifiers to avoid repetition
1106of things like the program name or the argument default_. The available
1107specifiers include the program name, ``%(prog)s`` and most keyword arguments to
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001108:meth:`~ArgumentParser.add_argument`, e.g. ``%(default)s``, ``%(type)s``, etc.::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001109
1110 >>> parser = argparse.ArgumentParser(prog='frobble')
1111 >>> parser.add_argument('bar', nargs='?', type=int, default=42,
1112 ... help='the bar to %(prog)s (default: %(default)s)')
1113 >>> parser.print_help()
1114 usage: frobble [-h] [bar]
1115
1116 positional arguments:
1117 bar the bar to frobble (default: 42)
1118
1119 optional arguments:
1120 -h, --help show this help message and exit
1121
Senthil Kumaranf21804a2012-06-26 14:17:19 +08001122As the help string supports %-formatting, if you want a literal ``%`` to appear
1123in the help string, you must escape it as ``%%``.
1124
Sandro Tosiea320ab2012-01-03 18:37:03 +01001125:mod:`argparse` supports silencing the help entry for certain options, by
1126setting the ``help`` value to ``argparse.SUPPRESS``::
1127
1128 >>> parser = argparse.ArgumentParser(prog='frobble')
1129 >>> parser.add_argument('--foo', help=argparse.SUPPRESS)
1130 >>> parser.print_help()
1131 usage: frobble [-h]
1132
1133 optional arguments:
1134 -h, --help show this help message and exit
1135
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001136
1137metavar
1138^^^^^^^
1139
Sandro Tosi32587fb2013-01-11 10:49:00 +01001140When :class:`ArgumentParser` generates help messages, it needs some way to refer
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001141to each expected argument. By default, ArgumentParser objects use the dest_
1142value as the "name" of each object. By default, for positional argument
1143actions, the dest_ value is used directly, and for optional argument actions,
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001144the dest_ value is uppercased. So, a single positional argument with
Eli Benderskya7795db2011-11-11 10:57:01 +02001145``dest='bar'`` will be referred to as ``bar``. A single
Éric Araujofde92422011-08-19 01:30:26 +02001146optional argument ``--foo`` that should be followed by a single command-line argument
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001147will be referred to as ``FOO``. An example::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001148
1149 >>> parser = argparse.ArgumentParser()
1150 >>> parser.add_argument('--foo')
1151 >>> parser.add_argument('bar')
1152 >>> parser.parse_args('X --foo Y'.split())
1153 Namespace(bar='X', foo='Y')
1154 >>> parser.print_help()
1155 usage: [-h] [--foo FOO] bar
1156
1157 positional arguments:
1158 bar
1159
1160 optional arguments:
1161 -h, --help show this help message and exit
1162 --foo FOO
1163
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001164An alternative name can be specified with ``metavar``::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001165
1166 >>> parser = argparse.ArgumentParser()
1167 >>> parser.add_argument('--foo', metavar='YYY')
1168 >>> parser.add_argument('bar', metavar='XXX')
1169 >>> parser.parse_args('X --foo Y'.split())
1170 Namespace(bar='X', foo='Y')
1171 >>> parser.print_help()
1172 usage: [-h] [--foo YYY] XXX
1173
1174 positional arguments:
1175 XXX
1176
1177 optional arguments:
1178 -h, --help show this help message and exit
1179 --foo YYY
1180
1181Note that ``metavar`` only changes the *displayed* name - the name of the
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001182attribute on the :meth:`~ArgumentParser.parse_args` object is still determined
1183by the dest_ value.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001184
1185Different values of ``nargs`` may cause the metavar to be used multiple times.
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001186Providing a tuple to ``metavar`` specifies a different display for each of the
1187arguments::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001188
1189 >>> parser = argparse.ArgumentParser(prog='PROG')
1190 >>> parser.add_argument('-x', nargs=2)
1191 >>> parser.add_argument('--foo', nargs=2, metavar=('bar', 'baz'))
1192 >>> parser.print_help()
1193 usage: PROG [-h] [-x X X] [--foo bar baz]
1194
1195 optional arguments:
1196 -h, --help show this help message and exit
1197 -x X X
1198 --foo bar baz
1199
1200
1201dest
1202^^^^
1203
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001204Most :class:`ArgumentParser` actions add some value as an attribute of the
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001205object returned by :meth:`~ArgumentParser.parse_args`. The name of this
1206attribute is determined by the ``dest`` keyword argument of
1207:meth:`~ArgumentParser.add_argument`. For positional argument actions,
1208``dest`` is normally supplied as the first argument to
1209:meth:`~ArgumentParser.add_argument`::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001210
1211 >>> parser = argparse.ArgumentParser()
1212 >>> parser.add_argument('bar')
1213 >>> parser.parse_args('XXX'.split())
1214 Namespace(bar='XXX')
1215
1216For optional argument actions, the value of ``dest`` is normally inferred from
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001217the option strings. :class:`ArgumentParser` generates the value of ``dest`` by
Éric Araujo543edbd2011-08-19 01:45:12 +02001218taking the first long option string and stripping away the initial ``--``
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001219string. If no long option strings were supplied, ``dest`` will be derived from
Éric Araujo543edbd2011-08-19 01:45:12 +02001220the first short option string by stripping the initial ``-`` character. Any
1221internal ``-`` characters will be converted to ``_`` characters to make sure
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001222the string is a valid attribute name. The examples below illustrate this
1223behavior::
1224
1225 >>> parser = argparse.ArgumentParser()
1226 >>> parser.add_argument('-f', '--foo-bar', '--foo')
1227 >>> parser.add_argument('-x', '-y')
1228 >>> parser.parse_args('-f 1 -x 2'.split())
1229 Namespace(foo_bar='1', x='2')
1230 >>> parser.parse_args('--foo 1 -y 2'.split())
1231 Namespace(foo_bar='1', x='2')
1232
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001233``dest`` allows a custom attribute name to be provided::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001234
1235 >>> parser = argparse.ArgumentParser()
1236 >>> parser.add_argument('--foo', dest='bar')
1237 >>> parser.parse_args('--foo XXX'.split())
1238 Namespace(bar='XXX')
1239
1240
1241The parse_args() method
1242-----------------------
1243
Georg Brandle0bf91d2010-10-17 10:34:28 +00001244.. method:: ArgumentParser.parse_args(args=None, namespace=None)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001245
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001246 Convert argument strings to objects and assign them as attributes of the
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001247 namespace. Return the populated namespace.
1248
1249 Previous calls to :meth:`add_argument` determine exactly what objects are
1250 created and how they are assigned. See the documentation for
1251 :meth:`add_argument` for details.
1252
Éric Araujofde92422011-08-19 01:30:26 +02001253 By default, the argument strings are taken from :data:`sys.argv`, and a new empty
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001254 :class:`Namespace` object is created for the attributes.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001255
Georg Brandle0bf91d2010-10-17 10:34:28 +00001256
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001257Option value syntax
1258^^^^^^^^^^^^^^^^^^^
1259
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001260The :meth:`~ArgumentParser.parse_args` method supports several ways of
1261specifying the value of an option (if it takes one). In the simplest case, the
1262option and its value are passed as two separate arguments::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001263
1264 >>> parser = argparse.ArgumentParser(prog='PROG')
1265 >>> parser.add_argument('-x')
1266 >>> parser.add_argument('--foo')
1267 >>> parser.parse_args('-x X'.split())
1268 Namespace(foo=None, x='X')
1269 >>> parser.parse_args('--foo FOO'.split())
1270 Namespace(foo='FOO', x=None)
1271
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001272For long options (options with names longer than a single character), the option
Georg Brandl69518bc2011-04-16 16:44:54 +02001273and value can also be passed as a single command-line argument, using ``=`` to
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001274separate them::
1275
1276 >>> parser.parse_args('--foo=FOO'.split())
1277 Namespace(foo='FOO', x=None)
1278
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001279For short options (options only one character long), the option and its value
1280can be concatenated::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001281
1282 >>> parser.parse_args('-xX'.split())
1283 Namespace(foo=None, x='X')
1284
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001285Several short options can be joined together, using only a single ``-`` prefix,
1286as long as only the last option (or none of them) requires a value::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001287
1288 >>> parser = argparse.ArgumentParser(prog='PROG')
1289 >>> parser.add_argument('-x', action='store_true')
1290 >>> parser.add_argument('-y', action='store_true')
1291 >>> parser.add_argument('-z')
1292 >>> parser.parse_args('-xyzZ'.split())
1293 Namespace(x=True, y=True, z='Z')
1294
1295
1296Invalid arguments
1297^^^^^^^^^^^^^^^^^
1298
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001299While parsing the command line, :meth:`~ArgumentParser.parse_args` checks for a
1300variety of errors, including ambiguous options, invalid types, invalid options,
1301wrong number of positional arguments, etc. When it encounters such an error,
1302it exits and prints the error along with a usage message::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001303
1304 >>> parser = argparse.ArgumentParser(prog='PROG')
1305 >>> parser.add_argument('--foo', type=int)
1306 >>> parser.add_argument('bar', nargs='?')
1307
1308 >>> # invalid type
1309 >>> parser.parse_args(['--foo', 'spam'])
1310 usage: PROG [-h] [--foo FOO] [bar]
1311 PROG: error: argument --foo: invalid int value: 'spam'
1312
1313 >>> # invalid option
1314 >>> parser.parse_args(['--bar'])
1315 usage: PROG [-h] [--foo FOO] [bar]
1316 PROG: error: no such option: --bar
1317
1318 >>> # wrong number of arguments
1319 >>> parser.parse_args(['spam', 'badger'])
1320 usage: PROG [-h] [--foo FOO] [bar]
1321 PROG: error: extra arguments found: badger
1322
1323
Éric Araujo543edbd2011-08-19 01:45:12 +02001324Arguments containing ``-``
1325^^^^^^^^^^^^^^^^^^^^^^^^^^
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001326
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001327The :meth:`~ArgumentParser.parse_args` method attempts to give errors whenever
1328the user has clearly made a mistake, but some situations are inherently
Éric Araujo543edbd2011-08-19 01:45:12 +02001329ambiguous. For example, the command-line argument ``-1`` could either be an
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001330attempt to specify an option or an attempt to provide a positional argument.
1331The :meth:`~ArgumentParser.parse_args` method is cautious here: positional
Éric Araujo543edbd2011-08-19 01:45:12 +02001332arguments may only begin with ``-`` if they look like negative numbers and
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001333there are no options in the parser that look like negative numbers::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001334
1335 >>> parser = argparse.ArgumentParser(prog='PROG')
1336 >>> parser.add_argument('-x')
1337 >>> parser.add_argument('foo', nargs='?')
1338
1339 >>> # no negative number options, so -1 is a positional argument
1340 >>> parser.parse_args(['-x', '-1'])
1341 Namespace(foo=None, x='-1')
1342
1343 >>> # no negative number options, so -1 and -5 are positional arguments
1344 >>> parser.parse_args(['-x', '-1', '-5'])
1345 Namespace(foo='-5', x='-1')
1346
1347 >>> parser = argparse.ArgumentParser(prog='PROG')
1348 >>> parser.add_argument('-1', dest='one')
1349 >>> parser.add_argument('foo', nargs='?')
1350
1351 >>> # negative number options present, so -1 is an option
1352 >>> parser.parse_args(['-1', 'X'])
1353 Namespace(foo=None, one='X')
1354
1355 >>> # negative number options present, so -2 is an option
1356 >>> parser.parse_args(['-2'])
1357 usage: PROG [-h] [-1 ONE] [foo]
1358 PROG: error: no such option: -2
1359
1360 >>> # negative number options present, so both -1s are options
1361 >>> parser.parse_args(['-1', '-1'])
1362 usage: PROG [-h] [-1 ONE] [foo]
1363 PROG: error: argument -1: expected one argument
1364
Éric Araujo543edbd2011-08-19 01:45:12 +02001365If you have positional arguments that must begin with ``-`` and don't look
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001366like negative numbers, you can insert the pseudo-argument ``'--'`` which tells
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001367:meth:`~ArgumentParser.parse_args` that everything after that is a positional
1368argument::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001369
1370 >>> parser.parse_args(['--', '-f'])
1371 Namespace(foo='-f', one=None)
1372
1373
1374Argument abbreviations
1375^^^^^^^^^^^^^^^^^^^^^^
1376
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001377The :meth:`~ArgumentParser.parse_args` method allows long options to be
1378abbreviated if the abbreviation is unambiguous::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001379
1380 >>> parser = argparse.ArgumentParser(prog='PROG')
1381 >>> parser.add_argument('-bacon')
1382 >>> parser.add_argument('-badger')
1383 >>> parser.parse_args('-bac MMM'.split())
1384 Namespace(bacon='MMM', badger=None)
1385 >>> parser.parse_args('-bad WOOD'.split())
1386 Namespace(bacon=None, badger='WOOD')
1387 >>> parser.parse_args('-ba BA'.split())
1388 usage: PROG [-h] [-bacon BACON] [-badger BADGER]
1389 PROG: error: ambiguous option: -ba could match -badger, -bacon
1390
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001391An error is produced for arguments that could produce more than one options.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001392
1393
1394Beyond ``sys.argv``
1395^^^^^^^^^^^^^^^^^^^
1396
Éric Araujod9d7bca2011-08-10 04:19:03 +02001397Sometimes it may be useful to have an ArgumentParser parse arguments other than those
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001398of :data:`sys.argv`. This can be accomplished by passing a list of strings to
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001399:meth:`~ArgumentParser.parse_args`. This is useful for testing at the
1400interactive prompt::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001401
1402 >>> parser = argparse.ArgumentParser()
1403 >>> parser.add_argument(
Fred Drake44623062011-03-03 05:27:17 +00001404 ... 'integers', metavar='int', type=int, choices=range(10),
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001405 ... nargs='+', help='an integer in the range 0..9')
1406 >>> parser.add_argument(
1407 ... '--sum', dest='accumulate', action='store_const', const=sum,
1408 ... default=max, help='sum the integers (default: find the max)')
1409 >>> parser.parse_args(['1', '2', '3', '4'])
1410 Namespace(accumulate=<built-in function max>, integers=[1, 2, 3, 4])
1411 >>> parser.parse_args('1 2 3 4 --sum'.split())
1412 Namespace(accumulate=<built-in function sum>, integers=[1, 2, 3, 4])
1413
1414
Steven Bethardd8f2d502011-03-26 19:50:06 +01001415The Namespace object
1416^^^^^^^^^^^^^^^^^^^^
1417
Éric Araujo63b18a42011-07-29 17:59:17 +02001418.. class:: Namespace
1419
1420 Simple class used by default by :meth:`~ArgumentParser.parse_args` to create
1421 an object holding attributes and return it.
1422
1423This class is deliberately simple, just an :class:`object` subclass with a
1424readable string representation. If you prefer to have dict-like view of the
1425attributes, you can use the standard Python idiom, :func:`vars`::
Steven Bethardd8f2d502011-03-26 19:50:06 +01001426
1427 >>> parser = argparse.ArgumentParser()
1428 >>> parser.add_argument('--foo')
1429 >>> args = parser.parse_args(['--foo', 'BAR'])
1430 >>> vars(args)
1431 {'foo': 'BAR'}
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001432
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001433It may also be useful to have an :class:`ArgumentParser` assign attributes to an
Steven Bethardd8f2d502011-03-26 19:50:06 +01001434already existing object, rather than a new :class:`Namespace` object. This can
1435be achieved by specifying the ``namespace=`` keyword argument::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001436
Éric Araujo28053fb2010-11-22 03:09:19 +00001437 >>> class C:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001438 ... pass
1439 ...
1440 >>> c = C()
1441 >>> parser = argparse.ArgumentParser()
1442 >>> parser.add_argument('--foo')
1443 >>> parser.parse_args(args=['--foo', 'BAR'], namespace=c)
1444 >>> c.foo
1445 'BAR'
1446
1447
1448Other utilities
1449---------------
1450
1451Sub-commands
1452^^^^^^^^^^^^
1453
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001454.. method:: ArgumentParser.add_subparsers()
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001455
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001456 Many programs split up their functionality into a number of sub-commands,
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001457 for example, the ``svn`` program can invoke sub-commands like ``svn
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001458 checkout``, ``svn update``, and ``svn commit``. Splitting up functionality
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001459 this way can be a particularly good idea when a program performs several
1460 different functions which require different kinds of command-line arguments.
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001461 :class:`ArgumentParser` supports the creation of such sub-commands with the
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001462 :meth:`add_subparsers` method. The :meth:`add_subparsers` method is normally
Ezio Melotti52336f02012-12-28 01:59:24 +02001463 called with no arguments and returns a special action object. This object
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001464 has a single method, :meth:`~ArgumentParser.add_parser`, which takes a
1465 command name and any :class:`ArgumentParser` constructor arguments, and
1466 returns an :class:`ArgumentParser` object that can be modified as usual.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001467
1468 Some example usage::
1469
1470 >>> # create the top-level parser
1471 >>> parser = argparse.ArgumentParser(prog='PROG')
1472 >>> parser.add_argument('--foo', action='store_true', help='foo help')
1473 >>> subparsers = parser.add_subparsers(help='sub-command help')
1474 >>>
1475 >>> # create the parser for the "a" command
1476 >>> parser_a = subparsers.add_parser('a', help='a help')
1477 >>> parser_a.add_argument('bar', type=int, help='bar help')
1478 >>>
1479 >>> # create the parser for the "b" command
1480 >>> parser_b = subparsers.add_parser('b', help='b help')
1481 >>> parser_b.add_argument('--baz', choices='XYZ', help='baz help')
1482 >>>
Éric Araujofde92422011-08-19 01:30:26 +02001483 >>> # parse some argument lists
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001484 >>> parser.parse_args(['a', '12'])
1485 Namespace(bar=12, foo=False)
1486 >>> parser.parse_args(['--foo', 'b', '--baz', 'Z'])
1487 Namespace(baz='Z', foo=True)
1488
1489 Note that the object returned by :meth:`parse_args` will only contain
1490 attributes for the main parser and the subparser that was selected by the
1491 command line (and not any other subparsers). So in the example above, when
Éric Araujo543edbd2011-08-19 01:45:12 +02001492 the ``a`` command is specified, only the ``foo`` and ``bar`` attributes are
1493 present, and when the ``b`` command is specified, only the ``foo`` and
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001494 ``baz`` attributes are present.
1495
1496 Similarly, when a help message is requested from a subparser, only the help
1497 for that particular parser will be printed. The help message will not
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001498 include parent parser or sibling parser messages. (A help message for each
1499 subparser command, however, can be given by supplying the ``help=`` argument
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001500 to :meth:`add_parser` as above.)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001501
1502 ::
1503
1504 >>> parser.parse_args(['--help'])
1505 usage: PROG [-h] [--foo] {a,b} ...
1506
1507 positional arguments:
1508 {a,b} sub-command help
Ezio Melotti7128e072013-01-12 10:39:45 +02001509 a a help
1510 b b help
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001511
1512 optional arguments:
1513 -h, --help show this help message and exit
1514 --foo foo help
1515
1516 >>> parser.parse_args(['a', '--help'])
1517 usage: PROG a [-h] bar
1518
1519 positional arguments:
1520 bar bar help
1521
1522 optional arguments:
1523 -h, --help show this help message and exit
1524
1525 >>> parser.parse_args(['b', '--help'])
1526 usage: PROG b [-h] [--baz {X,Y,Z}]
1527
1528 optional arguments:
1529 -h, --help show this help message and exit
1530 --baz {X,Y,Z} baz help
1531
1532 The :meth:`add_subparsers` method also supports ``title`` and ``description``
1533 keyword arguments. When either is present, the subparser's commands will
1534 appear in their own group in the help output. For example::
1535
1536 >>> parser = argparse.ArgumentParser()
1537 >>> subparsers = parser.add_subparsers(title='subcommands',
1538 ... description='valid subcommands',
1539 ... help='additional help')
1540 >>> subparsers.add_parser('foo')
1541 >>> subparsers.add_parser('bar')
1542 >>> parser.parse_args(['-h'])
1543 usage: [-h] {foo,bar} ...
1544
1545 optional arguments:
1546 -h, --help show this help message and exit
1547
1548 subcommands:
1549 valid subcommands
1550
1551 {foo,bar} additional help
1552
Steven Bethardfd311a72010-12-18 11:19:23 +00001553 Furthermore, ``add_parser`` supports an additional ``aliases`` argument,
1554 which allows multiple strings to refer to the same subparser. This example,
1555 like ``svn``, aliases ``co`` as a shorthand for ``checkout``::
1556
1557 >>> parser = argparse.ArgumentParser()
1558 >>> subparsers = parser.add_subparsers()
1559 >>> checkout = subparsers.add_parser('checkout', aliases=['co'])
1560 >>> checkout.add_argument('foo')
1561 >>> parser.parse_args(['co', 'bar'])
1562 Namespace(foo='bar')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001563
1564 One particularly effective way of handling sub-commands is to combine the use
1565 of the :meth:`add_subparsers` method with calls to :meth:`set_defaults` so
1566 that each subparser knows which Python function it should execute. For
1567 example::
1568
1569 >>> # sub-command functions
1570 >>> def foo(args):
Benjamin Petersonb2deb112010-03-03 02:09:18 +00001571 ... print(args.x * args.y)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001572 ...
1573 >>> def bar(args):
Benjamin Petersonb2deb112010-03-03 02:09:18 +00001574 ... print('((%s))' % args.z)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001575 ...
1576 >>> # create the top-level parser
1577 >>> parser = argparse.ArgumentParser()
1578 >>> subparsers = parser.add_subparsers()
1579 >>>
1580 >>> # create the parser for the "foo" command
1581 >>> parser_foo = subparsers.add_parser('foo')
1582 >>> parser_foo.add_argument('-x', type=int, default=1)
1583 >>> parser_foo.add_argument('y', type=float)
1584 >>> parser_foo.set_defaults(func=foo)
1585 >>>
1586 >>> # create the parser for the "bar" command
1587 >>> parser_bar = subparsers.add_parser('bar')
1588 >>> parser_bar.add_argument('z')
1589 >>> parser_bar.set_defaults(func=bar)
1590 >>>
1591 >>> # parse the args and call whatever function was selected
1592 >>> args = parser.parse_args('foo 1 -x 2'.split())
1593 >>> args.func(args)
1594 2.0
1595 >>>
1596 >>> # parse the args and call whatever function was selected
1597 >>> args = parser.parse_args('bar XYZYX'.split())
1598 >>> args.func(args)
1599 ((XYZYX))
1600
Steven Bethardfd311a72010-12-18 11:19:23 +00001601 This way, you can let :meth:`parse_args` do the job of calling the
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001602 appropriate function after argument parsing is complete. Associating
1603 functions with actions like this is typically the easiest way to handle the
1604 different actions for each of your subparsers. However, if it is necessary
1605 to check the name of the subparser that was invoked, the ``dest`` keyword
1606 argument to the :meth:`add_subparsers` call will work::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001607
1608 >>> parser = argparse.ArgumentParser()
1609 >>> subparsers = parser.add_subparsers(dest='subparser_name')
1610 >>> subparser1 = subparsers.add_parser('1')
1611 >>> subparser1.add_argument('-x')
1612 >>> subparser2 = subparsers.add_parser('2')
1613 >>> subparser2.add_argument('y')
1614 >>> parser.parse_args(['2', 'frobble'])
1615 Namespace(subparser_name='2', y='frobble')
1616
1617
1618FileType objects
1619^^^^^^^^^^^^^^^^
1620
1621.. class:: FileType(mode='r', bufsize=None)
1622
1623 The :class:`FileType` factory creates objects that can be passed to the type
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001624 argument of :meth:`ArgumentParser.add_argument`. Arguments that have
Éric Araujod9d7bca2011-08-10 04:19:03 +02001625 :class:`FileType` objects as their type will open command-line arguments as files
Éric Araujoc3ef0372012-02-20 01:44:55 +01001626 with the requested modes and buffer sizes::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001627
Éric Araujoc3ef0372012-02-20 01:44:55 +01001628 >>> parser = argparse.ArgumentParser()
1629 >>> parser.add_argument('--output', type=argparse.FileType('wb', 0))
1630 >>> parser.parse_args(['--output', 'out'])
1631 Namespace(output=<_io.BufferedWriter name='out'>)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001632
1633 FileType objects understand the pseudo-argument ``'-'`` and automatically
1634 convert this into ``sys.stdin`` for readable :class:`FileType` objects and
Éric Araujoc3ef0372012-02-20 01:44:55 +01001635 ``sys.stdout`` for writable :class:`FileType` objects::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001636
Éric Araujoc3ef0372012-02-20 01:44:55 +01001637 >>> parser = argparse.ArgumentParser()
1638 >>> parser.add_argument('infile', type=argparse.FileType('r'))
1639 >>> parser.parse_args(['-'])
1640 Namespace(infile=<_io.TextIOWrapper name='<stdin>' encoding='UTF-8'>)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001641
1642
1643Argument groups
1644^^^^^^^^^^^^^^^
1645
Georg Brandle0bf91d2010-10-17 10:34:28 +00001646.. method:: ArgumentParser.add_argument_group(title=None, description=None)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001647
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001648 By default, :class:`ArgumentParser` groups command-line arguments into
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001649 "positional arguments" and "optional arguments" when displaying help
1650 messages. When there is a better conceptual grouping of arguments than this
1651 default one, appropriate groups can be created using the
1652 :meth:`add_argument_group` method::
1653
1654 >>> parser = argparse.ArgumentParser(prog='PROG', add_help=False)
1655 >>> group = parser.add_argument_group('group')
1656 >>> group.add_argument('--foo', help='foo help')
1657 >>> group.add_argument('bar', help='bar help')
1658 >>> parser.print_help()
1659 usage: PROG [--foo FOO] bar
1660
1661 group:
1662 bar bar help
1663 --foo FOO foo help
1664
1665 The :meth:`add_argument_group` method returns an argument group object which
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001666 has an :meth:`~ArgumentParser.add_argument` method just like a regular
1667 :class:`ArgumentParser`. When an argument is added to the group, the parser
1668 treats it just like a normal argument, but displays the argument in a
1669 separate group for help messages. The :meth:`add_argument_group` method
Georg Brandle0bf91d2010-10-17 10:34:28 +00001670 accepts *title* and *description* arguments which can be used to
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001671 customize this display::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001672
1673 >>> parser = argparse.ArgumentParser(prog='PROG', add_help=False)
1674 >>> group1 = parser.add_argument_group('group1', 'group1 description')
1675 >>> group1.add_argument('foo', help='foo help')
1676 >>> group2 = parser.add_argument_group('group2', 'group2 description')
1677 >>> group2.add_argument('--bar', help='bar help')
1678 >>> parser.print_help()
1679 usage: PROG [--bar BAR] foo
1680
1681 group1:
1682 group1 description
1683
1684 foo foo help
1685
1686 group2:
1687 group2 description
1688
1689 --bar BAR bar help
1690
Sandro Tosi99e7d072012-03-26 19:36:23 +02001691 Note that any arguments not in your user-defined groups will end up back
1692 in the usual "positional arguments" and "optional arguments" sections.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001693
1694
1695Mutual exclusion
1696^^^^^^^^^^^^^^^^
1697
Georg Brandle0bf91d2010-10-17 10:34:28 +00001698.. method:: add_mutually_exclusive_group(required=False)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001699
Ezio Melotti0ee9c1b2011-04-21 16:12:17 +03001700 Create a mutually exclusive group. :mod:`argparse` will make sure that only
1701 one of the arguments in the mutually exclusive group was present on the
1702 command line::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001703
1704 >>> parser = argparse.ArgumentParser(prog='PROG')
1705 >>> group = parser.add_mutually_exclusive_group()
1706 >>> group.add_argument('--foo', action='store_true')
1707 >>> group.add_argument('--bar', action='store_false')
1708 >>> parser.parse_args(['--foo'])
1709 Namespace(bar=True, foo=True)
1710 >>> parser.parse_args(['--bar'])
1711 Namespace(bar=False, foo=False)
1712 >>> parser.parse_args(['--foo', '--bar'])
1713 usage: PROG [-h] [--foo | --bar]
1714 PROG: error: argument --bar: not allowed with argument --foo
1715
Georg Brandle0bf91d2010-10-17 10:34:28 +00001716 The :meth:`add_mutually_exclusive_group` method also accepts a *required*
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001717 argument, to indicate that at least one of the mutually exclusive arguments
1718 is required::
1719
1720 >>> parser = argparse.ArgumentParser(prog='PROG')
1721 >>> group = parser.add_mutually_exclusive_group(required=True)
1722 >>> group.add_argument('--foo', action='store_true')
1723 >>> group.add_argument('--bar', action='store_false')
1724 >>> parser.parse_args([])
1725 usage: PROG [-h] (--foo | --bar)
1726 PROG: error: one of the arguments --foo --bar is required
1727
1728 Note that currently mutually exclusive argument groups do not support the
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001729 *title* and *description* arguments of
1730 :meth:`~ArgumentParser.add_argument_group`.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001731
1732
1733Parser defaults
1734^^^^^^^^^^^^^^^
1735
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001736.. method:: ArgumentParser.set_defaults(**kwargs)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001737
1738 Most of the time, the attributes of the object returned by :meth:`parse_args`
Éric Araujod9d7bca2011-08-10 04:19:03 +02001739 will be fully determined by inspecting the command-line arguments and the argument
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001740 actions. :meth:`set_defaults` allows some additional
Georg Brandl69518bc2011-04-16 16:44:54 +02001741 attributes that are determined without any inspection of the command line to
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001742 be added::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001743
1744 >>> parser = argparse.ArgumentParser()
1745 >>> parser.add_argument('foo', type=int)
1746 >>> parser.set_defaults(bar=42, baz='badger')
1747 >>> parser.parse_args(['736'])
1748 Namespace(bar=42, baz='badger', foo=736)
1749
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001750 Note that parser-level defaults always override argument-level defaults::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001751
1752 >>> parser = argparse.ArgumentParser()
1753 >>> parser.add_argument('--foo', default='bar')
1754 >>> parser.set_defaults(foo='spam')
1755 >>> parser.parse_args([])
1756 Namespace(foo='spam')
1757
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001758 Parser-level defaults can be particularly useful when working with multiple
1759 parsers. See the :meth:`~ArgumentParser.add_subparsers` method for an
1760 example of this type.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001761
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001762.. method:: ArgumentParser.get_default(dest)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001763
1764 Get the default value for a namespace attribute, as set by either
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001765 :meth:`~ArgumentParser.add_argument` or by
1766 :meth:`~ArgumentParser.set_defaults`::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001767
1768 >>> parser = argparse.ArgumentParser()
1769 >>> parser.add_argument('--foo', default='badger')
1770 >>> parser.get_default('foo')
1771 'badger'
1772
1773
1774Printing help
1775^^^^^^^^^^^^^
1776
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001777In most typical applications, :meth:`~ArgumentParser.parse_args` will take
1778care of formatting and printing any usage or error messages. However, several
1779formatting methods are available:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001780
Georg Brandle0bf91d2010-10-17 10:34:28 +00001781.. method:: ArgumentParser.print_usage(file=None)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001782
1783 Print a brief description of how the :class:`ArgumentParser` should be
R. David Murray32e17712010-12-18 16:39:06 +00001784 invoked on the command line. If *file* is ``None``, :data:`sys.stdout` is
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001785 assumed.
1786
Georg Brandle0bf91d2010-10-17 10:34:28 +00001787.. method:: ArgumentParser.print_help(file=None)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001788
1789 Print a help message, including the program usage and information about the
Georg Brandle0bf91d2010-10-17 10:34:28 +00001790 arguments registered with the :class:`ArgumentParser`. If *file* is
R. David Murray32e17712010-12-18 16:39:06 +00001791 ``None``, :data:`sys.stdout` is assumed.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001792
1793There are also variants of these methods that simply return a string instead of
1794printing it:
1795
Georg Brandle0bf91d2010-10-17 10:34:28 +00001796.. method:: ArgumentParser.format_usage()
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001797
1798 Return a string containing a brief description of how the
1799 :class:`ArgumentParser` should be invoked on the command line.
1800
Georg Brandle0bf91d2010-10-17 10:34:28 +00001801.. method:: ArgumentParser.format_help()
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001802
1803 Return a string containing a help message, including the program usage and
1804 information about the arguments registered with the :class:`ArgumentParser`.
1805
1806
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001807Partial parsing
1808^^^^^^^^^^^^^^^
1809
Georg Brandle0bf91d2010-10-17 10:34:28 +00001810.. method:: ArgumentParser.parse_known_args(args=None, namespace=None)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001811
Georg Brandl69518bc2011-04-16 16:44:54 +02001812Sometimes a script may only parse a few of the command-line arguments, passing
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001813the remaining arguments on to another script or program. In these cases, the
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001814:meth:`~ArgumentParser.parse_known_args` method can be useful. It works much like
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001815:meth:`~ArgumentParser.parse_args` except that it does not produce an error when
1816extra arguments are present. Instead, it returns a two item tuple containing
1817the populated namespace and the list of remaining argument strings.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001818
1819::
1820
1821 >>> parser = argparse.ArgumentParser()
1822 >>> parser.add_argument('--foo', action='store_true')
1823 >>> parser.add_argument('bar')
1824 >>> parser.parse_known_args(['--foo', '--badger', 'BAR', 'spam'])
1825 (Namespace(bar='BAR', foo=True), ['--badger', 'spam'])
1826
1827
1828Customizing file parsing
1829^^^^^^^^^^^^^^^^^^^^^^^^
1830
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001831.. method:: ArgumentParser.convert_arg_line_to_args(arg_line)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001832
Georg Brandle0bf91d2010-10-17 10:34:28 +00001833 Arguments that are read from a file (see the *fromfile_prefix_chars*
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001834 keyword argument to the :class:`ArgumentParser` constructor) are read one
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001835 argument per line. :meth:`convert_arg_line_to_args` can be overriden for
1836 fancier reading.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001837
Georg Brandle0bf91d2010-10-17 10:34:28 +00001838 This method takes a single argument *arg_line* which is a string read from
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001839 the argument file. It returns a list of arguments parsed from this string.
1840 The method is called once per line read from the argument file, in order.
1841
1842 A useful override of this method is one that treats each space-separated word
1843 as an argument::
1844
1845 def convert_arg_line_to_args(self, arg_line):
1846 for arg in arg_line.split():
1847 if not arg.strip():
1848 continue
1849 yield arg
1850
1851
Georg Brandl93754922010-10-17 10:28:04 +00001852Exiting methods
1853^^^^^^^^^^^^^^^
1854
1855.. method:: ArgumentParser.exit(status=0, message=None)
1856
1857 This method terminates the program, exiting with the specified *status*
1858 and, if given, it prints a *message* before that.
1859
1860.. method:: ArgumentParser.error(message)
1861
1862 This method prints a usage message including the *message* to the
Senthil Kumaran86a1a892011-08-03 07:42:18 +08001863 standard error and terminates the program with a status code of 2.
Georg Brandl93754922010-10-17 10:28:04 +00001864
Raymond Hettinger677e10a2010-12-07 06:45:30 +00001865.. _upgrading-optparse-code:
Georg Brandl93754922010-10-17 10:28:04 +00001866
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001867Upgrading optparse code
1868-----------------------
1869
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001870Originally, the :mod:`argparse` module had attempted to maintain compatibility
Ezio Melotti0ee9c1b2011-04-21 16:12:17 +03001871with :mod:`optparse`. However, :mod:`optparse` was difficult to extend
1872transparently, particularly with the changes required to support the new
1873``nargs=`` specifiers and better usage messages. When most everything in
1874:mod:`optparse` had either been copy-pasted over or monkey-patched, it no
1875longer seemed practical to try to maintain the backwards compatibility.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001876
Ezio Melotti0ee9c1b2011-04-21 16:12:17 +03001877A partial upgrade path from :mod:`optparse` to :mod:`argparse`:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001878
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001879* Replace all :meth:`optparse.OptionParser.add_option` calls with
1880 :meth:`ArgumentParser.add_argument` calls.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001881
R David Murray5e0c5712012-03-30 18:07:42 -04001882* Replace ``(options, args) = parser.parse_args()`` with ``args =
Georg Brandlc9007082011-01-09 09:04:08 +00001883 parser.parse_args()`` and add additional :meth:`ArgumentParser.add_argument`
R David Murray5e0c5712012-03-30 18:07:42 -04001884 calls for the positional arguments. Keep in mind that what was previously
1885 called ``options``, now in :mod:`argparse` context is called ``args``.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001886
1887* Replace callback actions and the ``callback_*`` keyword arguments with
1888 ``type`` or ``action`` arguments.
1889
1890* Replace string names for ``type`` keyword arguments with the corresponding
1891 type objects (e.g. int, float, complex, etc).
1892
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001893* Replace :class:`optparse.Values` with :class:`Namespace` and
1894 :exc:`optparse.OptionError` and :exc:`optparse.OptionValueError` with
1895 :exc:`ArgumentError`.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001896
1897* Replace strings with implicit arguments such as ``%default`` or ``%prog`` with
Ezio Melotticca4ef82011-04-21 15:26:46 +03001898 the standard Python syntax to use dictionaries to format strings, that is,
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001899 ``%(default)s`` and ``%(prog)s``.
Steven Bethard59710962010-05-24 03:21:08 +00001900
1901* Replace the OptionParser constructor ``version`` argument with a call to
1902 ``parser.add_argument('--version', action='version', version='<the version>')``