blob: f3eb9dd59eec608002e79c2bfbb515cb94f43f78 [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
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300140 Create a new :class:`ArgumentParser` object. All parameters should be passed
141 as keyword arguments. Each parameter has its own more detailed description
142 below, but in short they are:
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000143
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300144 * prog_ - The name of the program (default: ``sys.argv[0]``)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000145
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300146 * usage_ - The string describing the program usage (default: generated from
147 arguments added to parser)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000148
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300149 * description_ - Text to display before the argument help (default: none)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000150
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300151 * epilog_ - Text to display after the argument help (default: none)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000152
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000153 * parents_ - A list of :class:`ArgumentParser` objects whose arguments should
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300154 also be included
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000155
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300156 * formatter_class_ - A class for customizing the help output
157
158 * prefix_chars_ - The set of characters that prefix optional arguments
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000159 (default: '-')
160
161 * fromfile_prefix_chars_ - The set of characters that prefix files from
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300162 which additional arguments should be read (default: ``None``)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000163
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300164 * argument_default_ - The global default value for arguments
165 (default: ``None``)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000166
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300167 * conflict_handler_ - The strategy for resolving conflicting optionals
168 (usually unnecessary)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000169
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300170 * add_help_ - Add a -h/--help option to the parser (default: ``True``)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000171
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000172The following sections describe how each of these are used.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000173
174
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300175prog
176^^^^
177
178By default, :class:`ArgumentParser` objects uses ``sys.argv[0]`` to determine
179how to display the name of the program in help messages. This default is almost
180always desirable because it will make the help messages match how the program was
181invoked on the command line. For example, consider a file named
182``myprogram.py`` with the following code::
183
184 import argparse
185 parser = argparse.ArgumentParser()
186 parser.add_argument('--foo', help='foo help')
187 args = parser.parse_args()
188
189The help for this program will display ``myprogram.py`` as the program name
190(regardless of where the program was invoked from)::
191
192 $ python myprogram.py --help
193 usage: myprogram.py [-h] [--foo FOO]
194
195 optional arguments:
196 -h, --help show this help message and exit
197 --foo FOO foo help
198 $ cd ..
199 $ python subdir\myprogram.py --help
200 usage: myprogram.py [-h] [--foo FOO]
201
202 optional arguments:
203 -h, --help show this help message and exit
204 --foo FOO foo help
205
206To change this default behavior, another value can be supplied using the
207``prog=`` argument to :class:`ArgumentParser`::
208
209 >>> parser = argparse.ArgumentParser(prog='myprogram')
210 >>> parser.print_help()
211 usage: myprogram [-h]
212
213 optional arguments:
214 -h, --help show this help message and exit
215
216Note that the program name, whether determined from ``sys.argv[0]`` or from the
217``prog=`` argument, is available to help messages using the ``%(prog)s`` format
218specifier.
219
220::
221
222 >>> parser = argparse.ArgumentParser(prog='myprogram')
223 >>> parser.add_argument('--foo', help='foo of the %(prog)s program')
224 >>> parser.print_help()
225 usage: myprogram [-h] [--foo FOO]
226
227 optional arguments:
228 -h, --help show this help message and exit
229 --foo FOO foo of the myprogram program
230
231
232usage
233^^^^^
234
235By default, :class:`ArgumentParser` calculates the usage message from the
236arguments it contains::
237
238 >>> parser = argparse.ArgumentParser(prog='PROG')
239 >>> parser.add_argument('--foo', nargs='?', help='foo help')
240 >>> parser.add_argument('bar', nargs='+', help='bar help')
241 >>> parser.print_help()
242 usage: PROG [-h] [--foo [FOO]] bar [bar ...]
243
244 positional arguments:
245 bar bar help
246
247 optional arguments:
248 -h, --help show this help message and exit
249 --foo [FOO] foo help
250
251The default message can be overridden with the ``usage=`` keyword argument::
252
253 >>> parser = argparse.ArgumentParser(prog='PROG', usage='%(prog)s [options]')
254 >>> parser.add_argument('--foo', nargs='?', help='foo help')
255 >>> parser.add_argument('bar', nargs='+', help='bar help')
256 >>> parser.print_help()
257 usage: PROG [options]
258
259 positional arguments:
260 bar bar help
261
262 optional arguments:
263 -h, --help show this help message and exit
264 --foo [FOO] foo help
265
266The ``%(prog)s`` format specifier is available to fill in the program name in
267your usage messages.
268
269
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000270description
271^^^^^^^^^^^
272
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000273Most calls to the :class:`ArgumentParser` constructor will use the
274``description=`` keyword argument. This argument gives a brief description of
275what the program does and how it works. In help messages, the description is
276displayed between the command-line usage string and the help messages for the
277various arguments::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000278
279 >>> parser = argparse.ArgumentParser(description='A foo that bars')
280 >>> parser.print_help()
281 usage: argparse.py [-h]
282
283 A foo that bars
284
285 optional arguments:
286 -h, --help show this help message and exit
287
288By default, the description will be line-wrapped so that it fits within the
289given space. To change this behavior, see the formatter_class_ argument.
290
291
292epilog
293^^^^^^
294
295Some programs like to display additional description of the program after the
296description of the arguments. Such text can be specified using the ``epilog=``
297argument to :class:`ArgumentParser`::
298
299 >>> parser = argparse.ArgumentParser(
300 ... description='A foo that bars',
301 ... epilog="And that's how you'd foo a bar")
302 >>> parser.print_help()
303 usage: argparse.py [-h]
304
305 A foo that bars
306
307 optional arguments:
308 -h, --help show this help message and exit
309
310 And that's how you'd foo a bar
311
312As with the description_ argument, the ``epilog=`` text is by default
313line-wrapped, but this behavior can be adjusted with the formatter_class_
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000314argument to :class:`ArgumentParser`.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000315
316
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000317parents
318^^^^^^^
319
320Sometimes, several parsers share a common set of arguments. Rather than
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000321repeating the definitions of these arguments, a single parser with all the
322shared arguments and passed to ``parents=`` argument to :class:`ArgumentParser`
323can be used. The ``parents=`` argument takes a list of :class:`ArgumentParser`
324objects, collects all the positional and optional actions from them, and adds
325these actions to the :class:`ArgumentParser` object being constructed::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000326
327 >>> parent_parser = argparse.ArgumentParser(add_help=False)
328 >>> parent_parser.add_argument('--parent', type=int)
329
330 >>> foo_parser = argparse.ArgumentParser(parents=[parent_parser])
331 >>> foo_parser.add_argument('foo')
332 >>> foo_parser.parse_args(['--parent', '2', 'XXX'])
333 Namespace(foo='XXX', parent=2)
334
335 >>> bar_parser = argparse.ArgumentParser(parents=[parent_parser])
336 >>> bar_parser.add_argument('--bar')
337 >>> bar_parser.parse_args(['--bar', 'YYY'])
338 Namespace(bar='YYY', parent=None)
339
340Note that most parent parsers will specify ``add_help=False``. Otherwise, the
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000341:class:`ArgumentParser` will see two ``-h/--help`` options (one in the parent
342and one in the child) and raise an error.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000343
Steven Bethardd186f992011-03-26 21:49:00 +0100344.. note::
345 You must fully initialize the parsers before passing them via ``parents=``.
346 If you change the parent parsers after the child parser, those changes will
347 not be reflected in the child.
348
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000349
350formatter_class
351^^^^^^^^^^^^^^^
352
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000353:class:`ArgumentParser` objects allow the help formatting to be customized by
Ezio Melotti707d1e62011-04-22 01:57:47 +0300354specifying an alternate formatting class. Currently, there are four such
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300355classes:
356
357.. class:: RawDescriptionHelpFormatter
358 RawTextHelpFormatter
359 ArgumentDefaultsHelpFormatter
Ezio Melotti707d1e62011-04-22 01:57:47 +0300360 MetavarTypeHelpFormatter
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000361
Steven Bethard0331e902011-03-26 14:48:04 +0100362:class:`RawDescriptionHelpFormatter` and :class:`RawTextHelpFormatter` give
363more control over how textual descriptions are displayed.
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000364By default, :class:`ArgumentParser` objects line-wrap the description_ and
365epilog_ texts in command-line help messages::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000366
367 >>> parser = argparse.ArgumentParser(
368 ... prog='PROG',
369 ... description='''this description
370 ... was indented weird
371 ... but that is okay''',
372 ... epilog='''
373 ... likewise for this epilog whose whitespace will
374 ... be cleaned up and whose words will be wrapped
375 ... across a couple lines''')
376 >>> parser.print_help()
377 usage: PROG [-h]
378
379 this description was indented weird but that is okay
380
381 optional arguments:
382 -h, --help show this help message and exit
383
384 likewise for this epilog whose whitespace will be cleaned up and whose words
385 will be wrapped across a couple lines
386
Steven Bethard0331e902011-03-26 14:48:04 +0100387Passing :class:`RawDescriptionHelpFormatter` as ``formatter_class=``
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000388indicates that description_ and epilog_ are already correctly formatted and
389should not be line-wrapped::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000390
391 >>> parser = argparse.ArgumentParser(
392 ... prog='PROG',
393 ... formatter_class=argparse.RawDescriptionHelpFormatter,
394 ... description=textwrap.dedent('''\
395 ... Please do not mess up this text!
396 ... --------------------------------
397 ... I have indented it
398 ... exactly the way
399 ... I want it
400 ... '''))
401 >>> parser.print_help()
402 usage: PROG [-h]
403
404 Please do not mess up this text!
405 --------------------------------
406 I have indented it
407 exactly the way
408 I want it
409
410 optional arguments:
411 -h, --help show this help message and exit
412
Steven Bethard0331e902011-03-26 14:48:04 +0100413:class:`RawTextHelpFormatter` maintains whitespace for all sorts of help text,
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000414including argument descriptions.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000415
Steven Bethard0331e902011-03-26 14:48:04 +0100416:class:`ArgumentDefaultsHelpFormatter` automatically adds information about
417default values to each of the argument help messages::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000418
419 >>> parser = argparse.ArgumentParser(
420 ... prog='PROG',
421 ... formatter_class=argparse.ArgumentDefaultsHelpFormatter)
422 >>> parser.add_argument('--foo', type=int, default=42, help='FOO!')
423 >>> parser.add_argument('bar', nargs='*', default=[1, 2, 3], help='BAR!')
424 >>> parser.print_help()
425 usage: PROG [-h] [--foo FOO] [bar [bar ...]]
426
427 positional arguments:
428 bar BAR! (default: [1, 2, 3])
429
430 optional arguments:
431 -h, --help show this help message and exit
432 --foo FOO FOO! (default: 42)
433
Steven Bethard0331e902011-03-26 14:48:04 +0100434:class:`MetavarTypeHelpFormatter` uses the name of the type_ argument for each
Ezio Melottif1064492011-10-19 11:06:26 +0300435argument as the display name for its values (rather than using the dest_
Steven Bethard0331e902011-03-26 14:48:04 +0100436as the regular formatter does)::
437
438 >>> parser = argparse.ArgumentParser(
439 ... prog='PROG',
440 ... formatter_class=argparse.MetavarTypeHelpFormatter)
441 >>> parser.add_argument('--foo', type=int)
442 >>> parser.add_argument('bar', type=float)
443 >>> parser.print_help()
444 usage: PROG [-h] [--foo int] float
445
446 positional arguments:
447 float
448
449 optional arguments:
450 -h, --help show this help message and exit
451 --foo int
452
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000453
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300454prefix_chars
455^^^^^^^^^^^^
456
457Most command-line options will use ``-`` as the prefix, e.g. ``-f/--foo``.
458Parsers that need to support different or additional prefix
459characters, e.g. for options
460like ``+f`` or ``/foo``, may specify them using the ``prefix_chars=`` argument
461to the ArgumentParser constructor::
462
463 >>> parser = argparse.ArgumentParser(prog='PROG', prefix_chars='-+')
464 >>> parser.add_argument('+f')
465 >>> parser.add_argument('++bar')
466 >>> parser.parse_args('+f X ++bar Y'.split())
467 Namespace(bar='Y', f='X')
468
469The ``prefix_chars=`` argument defaults to ``'-'``. Supplying a set of
470characters that does not include ``-`` will cause ``-f/--foo`` options to be
471disallowed.
472
473
474fromfile_prefix_chars
475^^^^^^^^^^^^^^^^^^^^^
476
477Sometimes, for example when dealing with a particularly long argument lists, it
478may make sense to keep the list of arguments in a file rather than typing it out
479at the command line. If the ``fromfile_prefix_chars=`` argument is given to the
480:class:`ArgumentParser` constructor, then arguments that start with any of the
481specified characters will be treated as files, and will be replaced by the
482arguments they contain. For example::
483
484 >>> with open('args.txt', 'w') as fp:
485 ... fp.write('-f\nbar')
486 >>> parser = argparse.ArgumentParser(fromfile_prefix_chars='@')
487 >>> parser.add_argument('-f')
488 >>> parser.parse_args(['-f', 'foo', '@args.txt'])
489 Namespace(f='bar')
490
491Arguments read from a file must by default be one per line (but see also
492:meth:`~ArgumentParser.convert_arg_line_to_args`) and are treated as if they
493were in the same place as the original file referencing argument on the command
494line. So in the example above, the expression ``['-f', 'foo', '@args.txt']``
495is considered equivalent to the expression ``['-f', 'foo', '-f', 'bar']``.
496
497The ``fromfile_prefix_chars=`` argument defaults to ``None``, meaning that
498arguments will never be treated as file references.
499
500
501argument_default
502^^^^^^^^^^^^^^^^
503
504Generally, argument defaults are specified either by passing a default to
505:meth:`~ArgumentParser.add_argument` or by calling the
506:meth:`~ArgumentParser.set_defaults` methods with a specific set of name-value
507pairs. Sometimes however, it may be useful to specify a single parser-wide
508default for arguments. This can be accomplished by passing the
509``argument_default=`` keyword argument to :class:`ArgumentParser`. For example,
510to globally suppress attribute creation on :meth:`~ArgumentParser.parse_args`
511calls, we supply ``argument_default=SUPPRESS``::
512
513 >>> parser = argparse.ArgumentParser(argument_default=argparse.SUPPRESS)
514 >>> parser.add_argument('--foo')
515 >>> parser.add_argument('bar', nargs='?')
516 >>> parser.parse_args(['--foo', '1', 'BAR'])
517 Namespace(bar='BAR', foo='1')
518 >>> parser.parse_args([])
519 Namespace()
520
521
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000522conflict_handler
523^^^^^^^^^^^^^^^^
524
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000525:class:`ArgumentParser` objects do not allow two actions with the same option
526string. By default, :class:`ArgumentParser` objects raises an exception if an
527attempt is made to create an argument with an option string that is already in
528use::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000529
530 >>> parser = argparse.ArgumentParser(prog='PROG')
531 >>> parser.add_argument('-f', '--foo', help='old foo help')
532 >>> parser.add_argument('--foo', help='new foo help')
533 Traceback (most recent call last):
534 ..
535 ArgumentError: argument --foo: conflicting option string(s): --foo
536
537Sometimes (e.g. when using parents_) it may be useful to simply override any
538older arguments with the same option string. To get this behavior, the value
539``'resolve'`` can be supplied to the ``conflict_handler=`` argument of
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000540:class:`ArgumentParser`::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000541
542 >>> parser = argparse.ArgumentParser(prog='PROG', conflict_handler='resolve')
543 >>> parser.add_argument('-f', '--foo', help='old foo help')
544 >>> parser.add_argument('--foo', help='new foo help')
545 >>> parser.print_help()
546 usage: PROG [-h] [-f FOO] [--foo FOO]
547
548 optional arguments:
549 -h, --help show this help message and exit
550 -f FOO old foo help
551 --foo FOO new foo help
552
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000553Note that :class:`ArgumentParser` objects only remove an action if all of its
554option strings are overridden. So, in the example above, the old ``-f/--foo``
555action is retained as the ``-f`` action, because only the ``--foo`` option
556string was overridden.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000557
558
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300559add_help
560^^^^^^^^
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000561
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300562By default, ArgumentParser objects add an option which simply displays
563the parser's help message. For example, consider a file named
564``myprogram.py`` containing the following code::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000565
566 import argparse
567 parser = argparse.ArgumentParser()
568 parser.add_argument('--foo', help='foo help')
569 args = parser.parse_args()
570
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300571If ``-h`` or ``--help`` is supplied at the command line, the ArgumentParser
572help will be printed::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000573
574 $ python myprogram.py --help
575 usage: myprogram.py [-h] [--foo FOO]
576
577 optional arguments:
578 -h, --help show this help message and exit
579 --foo FOO foo help
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000580
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300581Occasionally, it may be useful to disable the addition of this help option.
582This can be achieved by passing ``False`` as the ``add_help=`` argument to
583:class:`ArgumentParser`::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000584
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300585 >>> parser = argparse.ArgumentParser(prog='PROG', add_help=False)
586 >>> parser.add_argument('--foo', help='foo help')
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000587 >>> parser.print_help()
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300588 usage: PROG [--foo FOO]
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000589
590 optional arguments:
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300591 --foo FOO foo help
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000592
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300593The help option is typically ``-h/--help``. The exception to this is
594if the ``prefix_chars=`` is specified and does not include ``-``, in
595which case ``-h`` and ``--help`` are not valid options. In
596this case, the first character in ``prefix_chars`` is used to prefix
597the help options::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000598
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300599 >>> parser = argparse.ArgumentParser(prog='PROG', prefix_chars='+/')
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000600 >>> parser.print_help()
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300601 usage: PROG [-h]
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000602
603 optional arguments:
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300604 -h, --help show this help message and exit
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000605
606
607The add_argument() method
608-------------------------
609
Georg Brandlc9007082011-01-09 09:04:08 +0000610.. method:: ArgumentParser.add_argument(name or flags..., [action], [nargs], \
611 [const], [default], [type], [choices], [required], \
612 [help], [metavar], [dest])
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000613
Georg Brandl69518bc2011-04-16 16:44:54 +0200614 Define how a single command-line argument should be parsed. Each parameter
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000615 has its own more detailed description below, but in short they are:
616
617 * `name or flags`_ - Either a name or a list of option strings, e.g. ``foo``
Ezio Melottidca309d2011-04-21 23:09:27 +0300618 or ``-f, --foo``.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000619
620 * action_ - The basic type of action to be taken when this argument is
Georg Brandl69518bc2011-04-16 16:44:54 +0200621 encountered at the command line.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000622
623 * nargs_ - The number of command-line arguments that should be consumed.
624
625 * const_ - A constant value required by some action_ and nargs_ selections.
626
627 * default_ - The value produced if the argument is absent from the
Georg Brandl69518bc2011-04-16 16:44:54 +0200628 command line.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000629
Ezio Melotti2409d772011-04-16 23:13:50 +0300630 * type_ - The type to which the command-line argument should be converted.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000631
632 * choices_ - A container of the allowable values for the argument.
633
634 * required_ - Whether or not the command-line option may be omitted
635 (optionals only).
636
637 * help_ - A brief description of what the argument does.
638
639 * metavar_ - A name for the argument in usage messages.
640
641 * dest_ - The name of the attribute to be added to the object returned by
642 :meth:`parse_args`.
643
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000644The following sections describe how each of these are used.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000645
Georg Brandle0bf91d2010-10-17 10:34:28 +0000646
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000647name or flags
648^^^^^^^^^^^^^
649
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300650The :meth:`~ArgumentParser.add_argument` method must know whether an optional
651argument, like ``-f`` or ``--foo``, or a positional argument, like a list of
652filenames, is expected. The first arguments passed to
653:meth:`~ArgumentParser.add_argument` must therefore be either a series of
654flags, or a simple argument name. For example, an optional argument could
655be created like::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000656
657 >>> parser.add_argument('-f', '--foo')
658
659while a positional argument could be created like::
660
661 >>> parser.add_argument('bar')
662
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300663When :meth:`~ArgumentParser.parse_args` is called, optional arguments will be
664identified by the ``-`` prefix, and the remaining arguments will be assumed to
665be positional::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000666
667 >>> parser = argparse.ArgumentParser(prog='PROG')
668 >>> parser.add_argument('-f', '--foo')
669 >>> parser.add_argument('bar')
670 >>> parser.parse_args(['BAR'])
671 Namespace(bar='BAR', foo=None)
672 >>> parser.parse_args(['BAR', '--foo', 'FOO'])
673 Namespace(bar='BAR', foo='FOO')
674 >>> parser.parse_args(['--foo', 'FOO'])
675 usage: PROG [-h] [-f FOO] bar
676 PROG: error: too few arguments
677
Georg Brandle0bf91d2010-10-17 10:34:28 +0000678
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000679action
680^^^^^^
681
Éric Araujod9d7bca2011-08-10 04:19:03 +0200682:class:`ArgumentParser` objects associate command-line arguments with actions. These
683actions can do just about anything with the command-line arguments associated with
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000684them, though most actions simply add an attribute to the object returned by
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300685:meth:`~ArgumentParser.parse_args`. The ``action`` keyword argument specifies
Éric Araujod9d7bca2011-08-10 04:19:03 +0200686how the command-line arguments should be handled. The supported actions are:
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000687
688* ``'store'`` - This just stores the argument's value. This is the default
Ezio Melotti2f1db7d2011-04-21 23:06:48 +0300689 action. For example::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000690
691 >>> parser = argparse.ArgumentParser()
692 >>> parser.add_argument('--foo')
693 >>> parser.parse_args('--foo 1'.split())
694 Namespace(foo='1')
695
696* ``'store_const'`` - This stores the value specified by the const_ keyword
Ezio Melotti2f1db7d2011-04-21 23:06:48 +0300697 argument. (Note that the const_ keyword argument defaults to the rather
698 unhelpful ``None``.) The ``'store_const'`` action is most commonly used with
699 optional arguments that specify some sort of flag. For example::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000700
701 >>> parser = argparse.ArgumentParser()
702 >>> parser.add_argument('--foo', action='store_const', const=42)
703 >>> parser.parse_args('--foo'.split())
704 Namespace(foo=42)
705
706* ``'store_true'`` and ``'store_false'`` - These store the values ``True`` and
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000707 ``False`` respectively. These are special cases of ``'store_const'``. For
708 example::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000709
710 >>> parser = argparse.ArgumentParser()
711 >>> parser.add_argument('--foo', action='store_true')
712 >>> parser.add_argument('--bar', action='store_false')
713 >>> parser.parse_args('--foo --bar'.split())
714 Namespace(bar=False, foo=True)
715
716* ``'append'`` - This stores a list, and appends each argument value to the
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000717 list. This is useful to allow an option to be specified multiple times.
718 Example usage::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000719
720 >>> parser = argparse.ArgumentParser()
721 >>> parser.add_argument('--foo', action='append')
722 >>> parser.parse_args('--foo 1 --foo 2'.split())
723 Namespace(foo=['1', '2'])
724
725* ``'append_const'`` - This stores a list, and appends the value specified by
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000726 the const_ keyword argument to the list. (Note that the const_ keyword
727 argument defaults to ``None``.) The ``'append_const'`` action is typically
728 useful when multiple arguments need to store constants to the same list. For
729 example::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000730
731 >>> parser = argparse.ArgumentParser()
732 >>> parser.add_argument('--str', dest='types', action='append_const', const=str)
733 >>> parser.add_argument('--int', dest='types', action='append_const', const=int)
734 >>> parser.parse_args('--str --int'.split())
Florent Xicluna74e64952011-10-28 11:21:19 +0200735 Namespace(types=[<class 'str'>, <class 'int'>])
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000736
Sandro Tosi98492a52012-01-04 23:25:04 +0100737* ``'count'`` - This counts the number of times a keyword argument occurs. For
738 example, this is useful for increasing verbosity levels::
739
740 >>> parser = argparse.ArgumentParser()
741 >>> parser.add_argument('--verbose', '-v', action='count')
742 >>> parser.parse_args('-vvv'.split())
743 Namespace(verbose=3)
744
745* ``'help'`` - This prints a complete help message for all the options in the
746 current parser and then exits. By default a help action is automatically
747 added to the parser. See :class:`ArgumentParser` for details of how the
748 output is created.
749
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000750* ``'version'`` - This expects a ``version=`` keyword argument in the
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300751 :meth:`~ArgumentParser.add_argument` call, and prints version information
Éric Araujoc3ef0372012-02-20 01:44:55 +0100752 and exits when invoked::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000753
754 >>> import argparse
755 >>> parser = argparse.ArgumentParser(prog='PROG')
Steven Bethard59710962010-05-24 03:21:08 +0000756 >>> parser.add_argument('--version', action='version', version='%(prog)s 2.0')
757 >>> parser.parse_args(['--version'])
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000758 PROG 2.0
759
760You can also specify an arbitrary action by passing an object that implements
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000761the Action API. The easiest way to do this is to extend
762:class:`argparse.Action`, supplying an appropriate ``__call__`` method. The
763``__call__`` method should accept four parameters:
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000764
765* ``parser`` - The ArgumentParser object which contains this action.
766
Éric Araujo63b18a42011-07-29 17:59:17 +0200767* ``namespace`` - The :class:`Namespace` object that will be returned by
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300768 :meth:`~ArgumentParser.parse_args`. Most actions add an attribute to this
769 object.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000770
Éric Araujod9d7bca2011-08-10 04:19:03 +0200771* ``values`` - The associated command-line arguments, with any type conversions
772 applied. (Type conversions are specified with the type_ keyword argument to
Sandro Tosiee903c52012-08-12 10:49:26 +0200773 :meth:`~ArgumentParser.add_argument`.)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000774
775* ``option_string`` - The option string that was used to invoke this action.
776 The ``option_string`` argument is optional, and will be absent if the action
777 is associated with a positional argument.
778
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000779An example of a custom action::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000780
781 >>> class FooAction(argparse.Action):
782 ... def __call__(self, parser, namespace, values, option_string=None):
Georg Brandl571a9532010-07-26 17:00:20 +0000783 ... print('%r %r %r' % (namespace, values, option_string))
784 ... setattr(namespace, self.dest, values)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000785 ...
786 >>> parser = argparse.ArgumentParser()
787 >>> parser.add_argument('--foo', action=FooAction)
788 >>> parser.add_argument('bar', action=FooAction)
789 >>> args = parser.parse_args('1 --foo 2'.split())
790 Namespace(bar=None, foo=None) '1' None
791 Namespace(bar='1', foo=None) '2' '--foo'
792 >>> args
793 Namespace(bar='1', foo='2')
794
795
796nargs
797^^^^^
798
799ArgumentParser objects usually associate a single command-line argument with a
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000800single action to be taken. The ``nargs`` keyword argument associates a
Ezio Melotti00f53af2011-04-21 22:56:51 +0300801different number of command-line arguments with a single action. The supported
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000802values are:
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000803
Éric Araujoc3ef0372012-02-20 01:44:55 +0100804* ``N`` (an integer). ``N`` arguments from the command line will be gathered
805 together into a list. For example::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000806
Georg Brandl682d7e02010-10-06 10:26:05 +0000807 >>> parser = argparse.ArgumentParser()
808 >>> parser.add_argument('--foo', nargs=2)
809 >>> parser.add_argument('bar', nargs=1)
810 >>> parser.parse_args('c --foo a b'.split())
811 Namespace(bar=['c'], foo=['a', 'b'])
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000812
Georg Brandl682d7e02010-10-06 10:26:05 +0000813 Note that ``nargs=1`` produces a list of one item. This is different from
814 the default, in which the item is produced by itself.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000815
Éric Araujofde92422011-08-19 01:30:26 +0200816* ``'?'``. One argument will be consumed from the command line if possible, and
817 produced as a single item. If no command-line argument is present, the value from
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000818 default_ will be produced. Note that for optional arguments, there is an
819 additional case - the option string is present but not followed by a
Éric Araujofde92422011-08-19 01:30:26 +0200820 command-line argument. In this case the value from const_ will be produced. Some
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000821 examples to illustrate this::
822
823 >>> parser = argparse.ArgumentParser()
824 >>> parser.add_argument('--foo', nargs='?', const='c', default='d')
825 >>> parser.add_argument('bar', nargs='?', default='d')
826 >>> parser.parse_args('XX --foo YY'.split())
827 Namespace(bar='XX', foo='YY')
828 >>> parser.parse_args('XX --foo'.split())
829 Namespace(bar='XX', foo='c')
830 >>> parser.parse_args(''.split())
831 Namespace(bar='d', foo='d')
832
833 One of the more common uses of ``nargs='?'`` is to allow optional input and
834 output files::
835
836 >>> parser = argparse.ArgumentParser()
Georg Brandle0bf91d2010-10-17 10:34:28 +0000837 >>> parser.add_argument('infile', nargs='?', type=argparse.FileType('r'),
838 ... default=sys.stdin)
839 >>> parser.add_argument('outfile', nargs='?', type=argparse.FileType('w'),
840 ... default=sys.stdout)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000841 >>> parser.parse_args(['input.txt', 'output.txt'])
Georg Brandl04536b02011-01-09 09:31:01 +0000842 Namespace(infile=<_io.TextIOWrapper name='input.txt' encoding='UTF-8'>,
843 outfile=<_io.TextIOWrapper name='output.txt' encoding='UTF-8'>)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000844 >>> parser.parse_args([])
Georg Brandl04536b02011-01-09 09:31:01 +0000845 Namespace(infile=<_io.TextIOWrapper name='<stdin>' encoding='UTF-8'>,
846 outfile=<_io.TextIOWrapper name='<stdout>' encoding='UTF-8'>)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000847
Éric Araujod9d7bca2011-08-10 04:19:03 +0200848* ``'*'``. All command-line arguments present are gathered into a list. Note that
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000849 it generally doesn't make much sense to have more than one positional argument
850 with ``nargs='*'``, but multiple optional arguments with ``nargs='*'`` is
851 possible. For example::
852
853 >>> parser = argparse.ArgumentParser()
854 >>> parser.add_argument('--foo', nargs='*')
855 >>> parser.add_argument('--bar', nargs='*')
856 >>> parser.add_argument('baz', nargs='*')
857 >>> parser.parse_args('a b --foo x y --bar 1 2'.split())
858 Namespace(bar=['1', '2'], baz=['a', 'b'], foo=['x', 'y'])
859
860* ``'+'``. Just like ``'*'``, all command-line args present are gathered into a
861 list. Additionally, an error message will be generated if there wasn't at
Éric Araujofde92422011-08-19 01:30:26 +0200862 least one command-line argument present. For example::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000863
864 >>> parser = argparse.ArgumentParser(prog='PROG')
865 >>> parser.add_argument('foo', nargs='+')
866 >>> parser.parse_args('a b'.split())
867 Namespace(foo=['a', 'b'])
868 >>> parser.parse_args(''.split())
869 usage: PROG [-h] foo [foo ...]
870 PROG: error: too few arguments
871
Sandro Tosida8e11a2012-01-19 22:23:00 +0100872* ``argparse.REMAINDER``. All the remaining command-line arguments are gathered
873 into a list. This is commonly useful for command line utilities that dispatch
Éric Araujoc3ef0372012-02-20 01:44:55 +0100874 to other command line utilities::
Sandro Tosi16bd0b42012-01-19 21:59:55 +0100875
876 >>> parser = argparse.ArgumentParser(prog='PROG')
877 >>> parser.add_argument('--foo')
878 >>> parser.add_argument('command')
879 >>> parser.add_argument('args', nargs=argparse.REMAINDER)
Sandro Tosi04676862012-02-19 19:54:00 +0100880 >>> print(parser.parse_args('--foo B cmd --arg1 XX ZZ'.split()))
Sandro Tosida8e11a2012-01-19 22:23:00 +0100881 Namespace(args=['--arg1', 'XX', 'ZZ'], command='cmd', foo='B')
Sandro Tosi16bd0b42012-01-19 21:59:55 +0100882
Éric Araujod9d7bca2011-08-10 04:19:03 +0200883If the ``nargs`` keyword argument is not provided, the number of arguments consumed
Éric Araujofde92422011-08-19 01:30:26 +0200884is determined by the action_. Generally this means a single command-line argument
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000885will be consumed and a single item (not a list) will be produced.
886
887
888const
889^^^^^
890
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300891The ``const`` argument of :meth:`~ArgumentParser.add_argument` is used to hold
892constant values that are not read from the command line but are required for
893the various :class:`ArgumentParser` actions. The two most common uses of it are:
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000894
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300895* When :meth:`~ArgumentParser.add_argument` is called with
896 ``action='store_const'`` or ``action='append_const'``. These actions add the
Éric Araujoc3ef0372012-02-20 01:44:55 +0100897 ``const`` value to one of the attributes of the object returned by
898 :meth:`~ArgumentParser.parse_args`. See the action_ description for examples.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000899
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300900* When :meth:`~ArgumentParser.add_argument` is called with option strings
901 (like ``-f`` or ``--foo``) and ``nargs='?'``. This creates an optional
Éric Araujod9d7bca2011-08-10 04:19:03 +0200902 argument that can be followed by zero or one command-line arguments.
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300903 When parsing the command line, if the option string is encountered with no
Éric Araujofde92422011-08-19 01:30:26 +0200904 command-line argument following it, the value of ``const`` will be assumed instead.
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300905 See the nargs_ description for examples.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000906
907The ``const`` keyword argument defaults to ``None``.
908
909
910default
911^^^^^^^
912
913All optional arguments and some positional arguments may be omitted at the
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300914command line. The ``default`` keyword argument of
915:meth:`~ArgumentParser.add_argument`, whose value defaults to ``None``,
Éric Araujofde92422011-08-19 01:30:26 +0200916specifies what value should be used if the command-line argument is not present.
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300917For optional arguments, the ``default`` value is used when the option string
918was not present at the command line::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000919
920 >>> parser = argparse.ArgumentParser()
921 >>> parser.add_argument('--foo', default=42)
922 >>> parser.parse_args('--foo 2'.split())
923 Namespace(foo='2')
924 >>> parser.parse_args(''.split())
925 Namespace(foo=42)
926
Barry Warsaw1dedd0a2012-09-25 10:37:58 -0400927If the ``default`` value is a string, the parser parses the value as if it
928were a command-line argument. In particular, the parser applies any type_
929conversion argument, if provided, before setting the attribute on the
930:class:`Namespace` return value. Otherwise, the parser uses the value as is::
931
932 >>> parser = argparse.ArgumentParser()
933 >>> parser.add_argument('--length', default='10', type=int)
934 >>> parser.add_argument('--width', default=10.5, type=int)
935 >>> parser.parse_args()
936 Namespace(length=10, width=10.5)
937
Éric Araujo543edbd2011-08-19 01:45:12 +0200938For positional arguments with nargs_ equal to ``?`` or ``*``, the ``default`` value
Éric Araujofde92422011-08-19 01:30:26 +0200939is used when no command-line argument was present::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000940
941 >>> parser = argparse.ArgumentParser()
942 >>> parser.add_argument('foo', nargs='?', default=42)
943 >>> parser.parse_args('a'.split())
944 Namespace(foo='a')
945 >>> parser.parse_args(''.split())
946 Namespace(foo=42)
947
948
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000949Providing ``default=argparse.SUPPRESS`` causes no attribute to be added if the
950command-line argument was not present.::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000951
952 >>> parser = argparse.ArgumentParser()
953 >>> parser.add_argument('--foo', default=argparse.SUPPRESS)
954 >>> parser.parse_args([])
955 Namespace()
956 >>> parser.parse_args(['--foo', '1'])
957 Namespace(foo='1')
958
959
960type
961^^^^
962
Éric Araujod9d7bca2011-08-10 04:19:03 +0200963By default, :class:`ArgumentParser` objects read command-line arguments in as simple
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300964strings. However, quite often the command-line string should instead be
965interpreted as another type, like a :class:`float` or :class:`int`. The
966``type`` keyword argument of :meth:`~ArgumentParser.add_argument` allows any
Éric Araujod9d7bca2011-08-10 04:19:03 +0200967necessary type-checking and type conversions to be performed. Common built-in
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300968types and functions can be used directly as the value of the ``type`` argument::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000969
970 >>> parser = argparse.ArgumentParser()
971 >>> parser.add_argument('foo', type=int)
Georg Brandl04536b02011-01-09 09:31:01 +0000972 >>> parser.add_argument('bar', type=open)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000973 >>> parser.parse_args('2 temp.txt'.split())
Georg Brandl04536b02011-01-09 09:31:01 +0000974 Namespace(bar=<_io.TextIOWrapper name='temp.txt' encoding='UTF-8'>, foo=2)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000975
Barry Warsaw1dedd0a2012-09-25 10:37:58 -0400976See the section on the default_ keyword argument for information on when the
977``type`` argument is applied to default arguments.
978
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000979To ease the use of various types of files, the argparse module provides the
Petri Lehtinen74d6c252012-12-15 22:39:32 +0200980factory FileType which takes the ``mode=``, ``bufsize=``, ``encoding=`` and
981``errors=`` arguments of the :func:`open` function. For example,
982``FileType('w')`` can be used to create a writable file::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000983
984 >>> parser = argparse.ArgumentParser()
985 >>> parser.add_argument('bar', type=argparse.FileType('w'))
986 >>> parser.parse_args(['out.txt'])
Georg Brandl04536b02011-01-09 09:31:01 +0000987 Namespace(bar=<_io.TextIOWrapper name='out.txt' encoding='UTF-8'>)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000988
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000989``type=`` can take any callable that takes a single string argument and returns
Éric Araujod9d7bca2011-08-10 04:19:03 +0200990the converted value::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000991
992 >>> def perfect_square(string):
993 ... value = int(string)
994 ... sqrt = math.sqrt(value)
995 ... if sqrt != int(sqrt):
996 ... msg = "%r is not a perfect square" % string
997 ... raise argparse.ArgumentTypeError(msg)
998 ... return value
999 ...
1000 >>> parser = argparse.ArgumentParser(prog='PROG')
1001 >>> parser.add_argument('foo', type=perfect_square)
1002 >>> parser.parse_args('9'.split())
1003 Namespace(foo=9)
1004 >>> parser.parse_args('7'.split())
1005 usage: PROG [-h] foo
1006 PROG: error: argument foo: '7' is not a perfect square
1007
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001008The choices_ keyword argument may be more convenient for type checkers that
1009simply check against a range of values::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001010
1011 >>> parser = argparse.ArgumentParser(prog='PROG')
Fred Drake44623062011-03-03 05:27:17 +00001012 >>> parser.add_argument('foo', type=int, choices=range(5, 10))
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001013 >>> parser.parse_args('7'.split())
1014 Namespace(foo=7)
1015 >>> parser.parse_args('11'.split())
1016 usage: PROG [-h] {5,6,7,8,9}
1017 PROG: error: argument foo: invalid choice: 11 (choose from 5, 6, 7, 8, 9)
1018
1019See the choices_ section for more details.
1020
1021
1022choices
1023^^^^^^^
1024
Éric Araujod9d7bca2011-08-10 04:19:03 +02001025Some command-line arguments should be selected from a restricted set of values.
Chris Jerdonek174ef672013-01-11 19:26:44 -08001026These can be handled by passing a container object as the *choices* keyword
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001027argument to :meth:`~ArgumentParser.add_argument`. When the command line is
Chris Jerdonek174ef672013-01-11 19:26:44 -08001028parsed, argument values will be checked, and an error message will be displayed
1029if the argument was not one of the acceptable values::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001030
Chris Jerdonek174ef672013-01-11 19:26:44 -08001031 >>> parser = argparse.ArgumentParser(prog='game.py')
1032 >>> parser.add_argument('move', choices=['rock', 'paper', 'scissors'])
1033 >>> parser.parse_args(['rock'])
1034 Namespace(move='rock')
1035 >>> parser.parse_args(['fire'])
1036 usage: game.py [-h] {rock,paper,scissors}
1037 game.py: error: argument move: invalid choice: 'fire' (choose from 'rock',
1038 'paper', 'scissors')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001039
Chris Jerdonek174ef672013-01-11 19:26:44 -08001040Note that inclusion in the *choices* container is checked after any type_
1041conversions have been performed, so the type of the objects in the *choices*
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001042container should match the type_ specified::
1043
Chris Jerdonek174ef672013-01-11 19:26:44 -08001044 >>> parser = argparse.ArgumentParser(prog='doors.py')
1045 >>> parser.add_argument('door', type=int, choices=range(1, 4))
1046 >>> print(parser.parse_args(['3']))
1047 Namespace(door=3)
1048 >>> parser.parse_args(['4'])
1049 usage: doors.py [-h] {1,2,3}
1050 doors.py: error: argument door: invalid choice: 4 (choose from 1, 2, 3)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001051
Chris Jerdonek174ef672013-01-11 19:26:44 -08001052Any object that supports the ``in`` operator can be passed as the *choices*
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001053value, so :class:`dict` objects, :class:`set` objects, custom containers,
1054etc. are all supported.
1055
1056
1057required
1058^^^^^^^^
1059
Ezio Melotti0ee9c1b2011-04-21 16:12:17 +03001060In general, the :mod:`argparse` module assumes that flags like ``-f`` and ``--bar``
Georg Brandl69518bc2011-04-16 16:44:54 +02001061indicate *optional* arguments, which can always be omitted at the command line.
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001062To make an option *required*, ``True`` can be specified for the ``required=``
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001063keyword argument to :meth:`~ArgumentParser.add_argument`::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001064
1065 >>> parser = argparse.ArgumentParser()
1066 >>> parser.add_argument('--foo', required=True)
1067 >>> parser.parse_args(['--foo', 'BAR'])
1068 Namespace(foo='BAR')
1069 >>> parser.parse_args([])
1070 usage: argparse.py [-h] [--foo FOO]
1071 argparse.py: error: option --foo is required
1072
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001073As the example shows, if an option is marked as ``required``,
1074:meth:`~ArgumentParser.parse_args` will report an error if that option is not
1075present at the command line.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001076
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001077.. note::
1078
1079 Required options are generally considered bad form because users expect
1080 *options* to be *optional*, and thus they should be avoided when possible.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001081
1082
1083help
1084^^^^
1085
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001086The ``help`` value is a string containing a brief description of the argument.
1087When a user requests help (usually by using ``-h`` or ``--help`` at the
Georg Brandl69518bc2011-04-16 16:44:54 +02001088command line), these ``help`` descriptions will be displayed with each
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001089argument::
1090
1091 >>> parser = argparse.ArgumentParser(prog='frobble')
1092 >>> parser.add_argument('--foo', action='store_true',
1093 ... help='foo the bars before frobbling')
1094 >>> parser.add_argument('bar', nargs='+',
1095 ... help='one of the bars to be frobbled')
1096 >>> parser.parse_args('-h'.split())
1097 usage: frobble [-h] [--foo] bar [bar ...]
1098
1099 positional arguments:
1100 bar one of the bars to be frobbled
1101
1102 optional arguments:
1103 -h, --help show this help message and exit
1104 --foo foo the bars before frobbling
1105
1106The ``help`` strings can include various format specifiers to avoid repetition
1107of things like the program name or the argument default_. The available
1108specifiers include the program name, ``%(prog)s`` and most keyword arguments to
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001109:meth:`~ArgumentParser.add_argument`, e.g. ``%(default)s``, ``%(type)s``, etc.::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001110
1111 >>> parser = argparse.ArgumentParser(prog='frobble')
1112 >>> parser.add_argument('bar', nargs='?', type=int, default=42,
1113 ... help='the bar to %(prog)s (default: %(default)s)')
1114 >>> parser.print_help()
1115 usage: frobble [-h] [bar]
1116
1117 positional arguments:
1118 bar the bar to frobble (default: 42)
1119
1120 optional arguments:
1121 -h, --help show this help message and exit
1122
Senthil Kumaranf21804a2012-06-26 14:17:19 +08001123As the help string supports %-formatting, if you want a literal ``%`` to appear
1124in the help string, you must escape it as ``%%``.
1125
Sandro Tosiea320ab2012-01-03 18:37:03 +01001126:mod:`argparse` supports silencing the help entry for certain options, by
1127setting the ``help`` value to ``argparse.SUPPRESS``::
1128
1129 >>> parser = argparse.ArgumentParser(prog='frobble')
1130 >>> parser.add_argument('--foo', help=argparse.SUPPRESS)
1131 >>> parser.print_help()
1132 usage: frobble [-h]
1133
1134 optional arguments:
1135 -h, --help show this help message and exit
1136
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001137
1138metavar
1139^^^^^^^
1140
Sandro Tosi32587fb2013-01-11 10:49:00 +01001141When :class:`ArgumentParser` generates help messages, it needs some way to refer
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001142to each expected argument. By default, ArgumentParser objects use the dest_
1143value as the "name" of each object. By default, for positional argument
1144actions, the dest_ value is used directly, and for optional argument actions,
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001145the dest_ value is uppercased. So, a single positional argument with
Eli Benderskya7795db2011-11-11 10:57:01 +02001146``dest='bar'`` will be referred to as ``bar``. A single
Éric Araujofde92422011-08-19 01:30:26 +02001147optional argument ``--foo`` that should be followed by a single command-line argument
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001148will be referred to as ``FOO``. An example::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001149
1150 >>> parser = argparse.ArgumentParser()
1151 >>> parser.add_argument('--foo')
1152 >>> parser.add_argument('bar')
1153 >>> parser.parse_args('X --foo Y'.split())
1154 Namespace(bar='X', foo='Y')
1155 >>> parser.print_help()
1156 usage: [-h] [--foo FOO] bar
1157
1158 positional arguments:
1159 bar
1160
1161 optional arguments:
1162 -h, --help show this help message and exit
1163 --foo FOO
1164
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001165An alternative name can be specified with ``metavar``::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001166
1167 >>> parser = argparse.ArgumentParser()
1168 >>> parser.add_argument('--foo', metavar='YYY')
1169 >>> parser.add_argument('bar', metavar='XXX')
1170 >>> parser.parse_args('X --foo Y'.split())
1171 Namespace(bar='X', foo='Y')
1172 >>> parser.print_help()
1173 usage: [-h] [--foo YYY] XXX
1174
1175 positional arguments:
1176 XXX
1177
1178 optional arguments:
1179 -h, --help show this help message and exit
1180 --foo YYY
1181
1182Note that ``metavar`` only changes the *displayed* name - the name of the
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001183attribute on the :meth:`~ArgumentParser.parse_args` object is still determined
1184by the dest_ value.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001185
1186Different values of ``nargs`` may cause the metavar to be used multiple times.
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001187Providing a tuple to ``metavar`` specifies a different display for each of the
1188arguments::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001189
1190 >>> parser = argparse.ArgumentParser(prog='PROG')
1191 >>> parser.add_argument('-x', nargs=2)
1192 >>> parser.add_argument('--foo', nargs=2, metavar=('bar', 'baz'))
1193 >>> parser.print_help()
1194 usage: PROG [-h] [-x X X] [--foo bar baz]
1195
1196 optional arguments:
1197 -h, --help show this help message and exit
1198 -x X X
1199 --foo bar baz
1200
1201
1202dest
1203^^^^
1204
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001205Most :class:`ArgumentParser` actions add some value as an attribute of the
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001206object returned by :meth:`~ArgumentParser.parse_args`. The name of this
1207attribute is determined by the ``dest`` keyword argument of
1208:meth:`~ArgumentParser.add_argument`. For positional argument actions,
1209``dest`` is normally supplied as the first argument to
1210:meth:`~ArgumentParser.add_argument`::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001211
1212 >>> parser = argparse.ArgumentParser()
1213 >>> parser.add_argument('bar')
1214 >>> parser.parse_args('XXX'.split())
1215 Namespace(bar='XXX')
1216
1217For optional argument actions, the value of ``dest`` is normally inferred from
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001218the option strings. :class:`ArgumentParser` generates the value of ``dest`` by
Éric Araujo543edbd2011-08-19 01:45:12 +02001219taking the first long option string and stripping away the initial ``--``
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001220string. If no long option strings were supplied, ``dest`` will be derived from
Éric Araujo543edbd2011-08-19 01:45:12 +02001221the first short option string by stripping the initial ``-`` character. Any
1222internal ``-`` characters will be converted to ``_`` characters to make sure
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001223the string is a valid attribute name. The examples below illustrate this
1224behavior::
1225
1226 >>> parser = argparse.ArgumentParser()
1227 >>> parser.add_argument('-f', '--foo-bar', '--foo')
1228 >>> parser.add_argument('-x', '-y')
1229 >>> parser.parse_args('-f 1 -x 2'.split())
1230 Namespace(foo_bar='1', x='2')
1231 >>> parser.parse_args('--foo 1 -y 2'.split())
1232 Namespace(foo_bar='1', x='2')
1233
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001234``dest`` allows a custom attribute name to be provided::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001235
1236 >>> parser = argparse.ArgumentParser()
1237 >>> parser.add_argument('--foo', dest='bar')
1238 >>> parser.parse_args('--foo XXX'.split())
1239 Namespace(bar='XXX')
1240
1241
1242The parse_args() method
1243-----------------------
1244
Georg Brandle0bf91d2010-10-17 10:34:28 +00001245.. method:: ArgumentParser.parse_args(args=None, namespace=None)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001246
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001247 Convert argument strings to objects and assign them as attributes of the
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001248 namespace. Return the populated namespace.
1249
1250 Previous calls to :meth:`add_argument` determine exactly what objects are
1251 created and how they are assigned. See the documentation for
1252 :meth:`add_argument` for details.
1253
Éric Araujofde92422011-08-19 01:30:26 +02001254 By default, the argument strings are taken from :data:`sys.argv`, and a new empty
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001255 :class:`Namespace` object is created for the attributes.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001256
Georg Brandle0bf91d2010-10-17 10:34:28 +00001257
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001258Option value syntax
1259^^^^^^^^^^^^^^^^^^^
1260
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001261The :meth:`~ArgumentParser.parse_args` method supports several ways of
1262specifying the value of an option (if it takes one). In the simplest case, the
1263option and its value are passed as two separate arguments::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001264
1265 >>> parser = argparse.ArgumentParser(prog='PROG')
1266 >>> parser.add_argument('-x')
1267 >>> parser.add_argument('--foo')
1268 >>> parser.parse_args('-x X'.split())
1269 Namespace(foo=None, x='X')
1270 >>> parser.parse_args('--foo FOO'.split())
1271 Namespace(foo='FOO', x=None)
1272
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001273For long options (options with names longer than a single character), the option
Georg Brandl69518bc2011-04-16 16:44:54 +02001274and value can also be passed as a single command-line argument, using ``=`` to
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001275separate them::
1276
1277 >>> parser.parse_args('--foo=FOO'.split())
1278 Namespace(foo='FOO', x=None)
1279
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001280For short options (options only one character long), the option and its value
1281can be concatenated::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001282
1283 >>> parser.parse_args('-xX'.split())
1284 Namespace(foo=None, x='X')
1285
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001286Several short options can be joined together, using only a single ``-`` prefix,
1287as long as only the last option (or none of them) requires a value::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001288
1289 >>> parser = argparse.ArgumentParser(prog='PROG')
1290 >>> parser.add_argument('-x', action='store_true')
1291 >>> parser.add_argument('-y', action='store_true')
1292 >>> parser.add_argument('-z')
1293 >>> parser.parse_args('-xyzZ'.split())
1294 Namespace(x=True, y=True, z='Z')
1295
1296
1297Invalid arguments
1298^^^^^^^^^^^^^^^^^
1299
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001300While parsing the command line, :meth:`~ArgumentParser.parse_args` checks for a
1301variety of errors, including ambiguous options, invalid types, invalid options,
1302wrong number of positional arguments, etc. When it encounters such an error,
1303it exits and prints the error along with a usage message::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001304
1305 >>> parser = argparse.ArgumentParser(prog='PROG')
1306 >>> parser.add_argument('--foo', type=int)
1307 >>> parser.add_argument('bar', nargs='?')
1308
1309 >>> # invalid type
1310 >>> parser.parse_args(['--foo', 'spam'])
1311 usage: PROG [-h] [--foo FOO] [bar]
1312 PROG: error: argument --foo: invalid int value: 'spam'
1313
1314 >>> # invalid option
1315 >>> parser.parse_args(['--bar'])
1316 usage: PROG [-h] [--foo FOO] [bar]
1317 PROG: error: no such option: --bar
1318
1319 >>> # wrong number of arguments
1320 >>> parser.parse_args(['spam', 'badger'])
1321 usage: PROG [-h] [--foo FOO] [bar]
1322 PROG: error: extra arguments found: badger
1323
1324
Éric Araujo543edbd2011-08-19 01:45:12 +02001325Arguments containing ``-``
1326^^^^^^^^^^^^^^^^^^^^^^^^^^
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001327
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001328The :meth:`~ArgumentParser.parse_args` method attempts to give errors whenever
1329the user has clearly made a mistake, but some situations are inherently
Éric Araujo543edbd2011-08-19 01:45:12 +02001330ambiguous. For example, the command-line argument ``-1`` could either be an
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001331attempt to specify an option or an attempt to provide a positional argument.
1332The :meth:`~ArgumentParser.parse_args` method is cautious here: positional
Éric Araujo543edbd2011-08-19 01:45:12 +02001333arguments may only begin with ``-`` if they look like negative numbers and
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001334there are no options in the parser that look like negative numbers::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001335
1336 >>> parser = argparse.ArgumentParser(prog='PROG')
1337 >>> parser.add_argument('-x')
1338 >>> parser.add_argument('foo', nargs='?')
1339
1340 >>> # no negative number options, so -1 is a positional argument
1341 >>> parser.parse_args(['-x', '-1'])
1342 Namespace(foo=None, x='-1')
1343
1344 >>> # no negative number options, so -1 and -5 are positional arguments
1345 >>> parser.parse_args(['-x', '-1', '-5'])
1346 Namespace(foo='-5', x='-1')
1347
1348 >>> parser = argparse.ArgumentParser(prog='PROG')
1349 >>> parser.add_argument('-1', dest='one')
1350 >>> parser.add_argument('foo', nargs='?')
1351
1352 >>> # negative number options present, so -1 is an option
1353 >>> parser.parse_args(['-1', 'X'])
1354 Namespace(foo=None, one='X')
1355
1356 >>> # negative number options present, so -2 is an option
1357 >>> parser.parse_args(['-2'])
1358 usage: PROG [-h] [-1 ONE] [foo]
1359 PROG: error: no such option: -2
1360
1361 >>> # negative number options present, so both -1s are options
1362 >>> parser.parse_args(['-1', '-1'])
1363 usage: PROG [-h] [-1 ONE] [foo]
1364 PROG: error: argument -1: expected one argument
1365
Éric Araujo543edbd2011-08-19 01:45:12 +02001366If you have positional arguments that must begin with ``-`` and don't look
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001367like negative numbers, you can insert the pseudo-argument ``'--'`` which tells
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001368:meth:`~ArgumentParser.parse_args` that everything after that is a positional
1369argument::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001370
1371 >>> parser.parse_args(['--', '-f'])
1372 Namespace(foo='-f', one=None)
1373
1374
1375Argument abbreviations
1376^^^^^^^^^^^^^^^^^^^^^^
1377
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001378The :meth:`~ArgumentParser.parse_args` method allows long options to be
1379abbreviated if the abbreviation is unambiguous::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001380
1381 >>> parser = argparse.ArgumentParser(prog='PROG')
1382 >>> parser.add_argument('-bacon')
1383 >>> parser.add_argument('-badger')
1384 >>> parser.parse_args('-bac MMM'.split())
1385 Namespace(bacon='MMM', badger=None)
1386 >>> parser.parse_args('-bad WOOD'.split())
1387 Namespace(bacon=None, badger='WOOD')
1388 >>> parser.parse_args('-ba BA'.split())
1389 usage: PROG [-h] [-bacon BACON] [-badger BADGER]
1390 PROG: error: ambiguous option: -ba could match -badger, -bacon
1391
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001392An error is produced for arguments that could produce more than one options.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001393
1394
1395Beyond ``sys.argv``
1396^^^^^^^^^^^^^^^^^^^
1397
Éric Araujod9d7bca2011-08-10 04:19:03 +02001398Sometimes it may be useful to have an ArgumentParser parse arguments other than those
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001399of :data:`sys.argv`. This can be accomplished by passing a list of strings to
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001400:meth:`~ArgumentParser.parse_args`. This is useful for testing at the
1401interactive prompt::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001402
1403 >>> parser = argparse.ArgumentParser()
1404 >>> parser.add_argument(
Fred Drake44623062011-03-03 05:27:17 +00001405 ... 'integers', metavar='int', type=int, choices=range(10),
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001406 ... nargs='+', help='an integer in the range 0..9')
1407 >>> parser.add_argument(
1408 ... '--sum', dest='accumulate', action='store_const', const=sum,
1409 ... default=max, help='sum the integers (default: find the max)')
1410 >>> parser.parse_args(['1', '2', '3', '4'])
1411 Namespace(accumulate=<built-in function max>, integers=[1, 2, 3, 4])
1412 >>> parser.parse_args('1 2 3 4 --sum'.split())
1413 Namespace(accumulate=<built-in function sum>, integers=[1, 2, 3, 4])
1414
1415
Steven Bethardd8f2d502011-03-26 19:50:06 +01001416The Namespace object
1417^^^^^^^^^^^^^^^^^^^^
1418
Éric Araujo63b18a42011-07-29 17:59:17 +02001419.. class:: Namespace
1420
1421 Simple class used by default by :meth:`~ArgumentParser.parse_args` to create
1422 an object holding attributes and return it.
1423
1424This class is deliberately simple, just an :class:`object` subclass with a
1425readable string representation. If you prefer to have dict-like view of the
1426attributes, you can use the standard Python idiom, :func:`vars`::
Steven Bethardd8f2d502011-03-26 19:50:06 +01001427
1428 >>> parser = argparse.ArgumentParser()
1429 >>> parser.add_argument('--foo')
1430 >>> args = parser.parse_args(['--foo', 'BAR'])
1431 >>> vars(args)
1432 {'foo': 'BAR'}
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001433
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001434It may also be useful to have an :class:`ArgumentParser` assign attributes to an
Steven Bethardd8f2d502011-03-26 19:50:06 +01001435already existing object, rather than a new :class:`Namespace` object. This can
1436be achieved by specifying the ``namespace=`` keyword argument::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001437
Éric Araujo28053fb2010-11-22 03:09:19 +00001438 >>> class C:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001439 ... pass
1440 ...
1441 >>> c = C()
1442 >>> parser = argparse.ArgumentParser()
1443 >>> parser.add_argument('--foo')
1444 >>> parser.parse_args(args=['--foo', 'BAR'], namespace=c)
1445 >>> c.foo
1446 'BAR'
1447
1448
1449Other utilities
1450---------------
1451
1452Sub-commands
1453^^^^^^^^^^^^
1454
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001455.. method:: ArgumentParser.add_subparsers()
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001456
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001457 Many programs split up their functionality into a number of sub-commands,
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001458 for example, the ``svn`` program can invoke sub-commands like ``svn
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001459 checkout``, ``svn update``, and ``svn commit``. Splitting up functionality
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001460 this way can be a particularly good idea when a program performs several
1461 different functions which require different kinds of command-line arguments.
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001462 :class:`ArgumentParser` supports the creation of such sub-commands with the
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001463 :meth:`add_subparsers` method. The :meth:`add_subparsers` method is normally
Ezio Melotti52336f02012-12-28 01:59:24 +02001464 called with no arguments and returns a special action object. This object
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001465 has a single method, :meth:`~ArgumentParser.add_parser`, which takes a
1466 command name and any :class:`ArgumentParser` constructor arguments, and
1467 returns an :class:`ArgumentParser` object that can be modified as usual.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001468
1469 Some example usage::
1470
1471 >>> # create the top-level parser
1472 >>> parser = argparse.ArgumentParser(prog='PROG')
1473 >>> parser.add_argument('--foo', action='store_true', help='foo help')
1474 >>> subparsers = parser.add_subparsers(help='sub-command help')
1475 >>>
1476 >>> # create the parser for the "a" command
1477 >>> parser_a = subparsers.add_parser('a', help='a help')
1478 >>> parser_a.add_argument('bar', type=int, help='bar help')
1479 >>>
1480 >>> # create the parser for the "b" command
1481 >>> parser_b = subparsers.add_parser('b', help='b help')
1482 >>> parser_b.add_argument('--baz', choices='XYZ', help='baz help')
1483 >>>
Éric Araujofde92422011-08-19 01:30:26 +02001484 >>> # parse some argument lists
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001485 >>> parser.parse_args(['a', '12'])
1486 Namespace(bar=12, foo=False)
1487 >>> parser.parse_args(['--foo', 'b', '--baz', 'Z'])
1488 Namespace(baz='Z', foo=True)
1489
1490 Note that the object returned by :meth:`parse_args` will only contain
1491 attributes for the main parser and the subparser that was selected by the
1492 command line (and not any other subparsers). So in the example above, when
Éric Araujo543edbd2011-08-19 01:45:12 +02001493 the ``a`` command is specified, only the ``foo`` and ``bar`` attributes are
1494 present, and when the ``b`` command is specified, only the ``foo`` and
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001495 ``baz`` attributes are present.
1496
1497 Similarly, when a help message is requested from a subparser, only the help
1498 for that particular parser will be printed. The help message will not
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001499 include parent parser or sibling parser messages. (A help message for each
1500 subparser command, however, can be given by supplying the ``help=`` argument
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001501 to :meth:`add_parser` as above.)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001502
1503 ::
1504
1505 >>> parser.parse_args(['--help'])
1506 usage: PROG [-h] [--foo] {a,b} ...
1507
1508 positional arguments:
1509 {a,b} sub-command help
Ezio Melotti7128e072013-01-12 10:39:45 +02001510 a a help
1511 b b help
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001512
1513 optional arguments:
1514 -h, --help show this help message and exit
1515 --foo foo help
1516
1517 >>> parser.parse_args(['a', '--help'])
1518 usage: PROG a [-h] bar
1519
1520 positional arguments:
1521 bar bar help
1522
1523 optional arguments:
1524 -h, --help show this help message and exit
1525
1526 >>> parser.parse_args(['b', '--help'])
1527 usage: PROG b [-h] [--baz {X,Y,Z}]
1528
1529 optional arguments:
1530 -h, --help show this help message and exit
1531 --baz {X,Y,Z} baz help
1532
1533 The :meth:`add_subparsers` method also supports ``title`` and ``description``
1534 keyword arguments. When either is present, the subparser's commands will
1535 appear in their own group in the help output. For example::
1536
1537 >>> parser = argparse.ArgumentParser()
1538 >>> subparsers = parser.add_subparsers(title='subcommands',
1539 ... description='valid subcommands',
1540 ... help='additional help')
1541 >>> subparsers.add_parser('foo')
1542 >>> subparsers.add_parser('bar')
1543 >>> parser.parse_args(['-h'])
1544 usage: [-h] {foo,bar} ...
1545
1546 optional arguments:
1547 -h, --help show this help message and exit
1548
1549 subcommands:
1550 valid subcommands
1551
1552 {foo,bar} additional help
1553
Steven Bethardfd311a72010-12-18 11:19:23 +00001554 Furthermore, ``add_parser`` supports an additional ``aliases`` argument,
1555 which allows multiple strings to refer to the same subparser. This example,
1556 like ``svn``, aliases ``co`` as a shorthand for ``checkout``::
1557
1558 >>> parser = argparse.ArgumentParser()
1559 >>> subparsers = parser.add_subparsers()
1560 >>> checkout = subparsers.add_parser('checkout', aliases=['co'])
1561 >>> checkout.add_argument('foo')
1562 >>> parser.parse_args(['co', 'bar'])
1563 Namespace(foo='bar')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001564
1565 One particularly effective way of handling sub-commands is to combine the use
1566 of the :meth:`add_subparsers` method with calls to :meth:`set_defaults` so
1567 that each subparser knows which Python function it should execute. For
1568 example::
1569
1570 >>> # sub-command functions
1571 >>> def foo(args):
Benjamin Petersonb2deb112010-03-03 02:09:18 +00001572 ... print(args.x * args.y)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001573 ...
1574 >>> def bar(args):
Benjamin Petersonb2deb112010-03-03 02:09:18 +00001575 ... print('((%s))' % args.z)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001576 ...
1577 >>> # create the top-level parser
1578 >>> parser = argparse.ArgumentParser()
1579 >>> subparsers = parser.add_subparsers()
1580 >>>
1581 >>> # create the parser for the "foo" command
1582 >>> parser_foo = subparsers.add_parser('foo')
1583 >>> parser_foo.add_argument('-x', type=int, default=1)
1584 >>> parser_foo.add_argument('y', type=float)
1585 >>> parser_foo.set_defaults(func=foo)
1586 >>>
1587 >>> # create the parser for the "bar" command
1588 >>> parser_bar = subparsers.add_parser('bar')
1589 >>> parser_bar.add_argument('z')
1590 >>> parser_bar.set_defaults(func=bar)
1591 >>>
1592 >>> # parse the args and call whatever function was selected
1593 >>> args = parser.parse_args('foo 1 -x 2'.split())
1594 >>> args.func(args)
1595 2.0
1596 >>>
1597 >>> # parse the args and call whatever function was selected
1598 >>> args = parser.parse_args('bar XYZYX'.split())
1599 >>> args.func(args)
1600 ((XYZYX))
1601
Steven Bethardfd311a72010-12-18 11:19:23 +00001602 This way, you can let :meth:`parse_args` do the job of calling the
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001603 appropriate function after argument parsing is complete. Associating
1604 functions with actions like this is typically the easiest way to handle the
1605 different actions for each of your subparsers. However, if it is necessary
1606 to check the name of the subparser that was invoked, the ``dest`` keyword
1607 argument to the :meth:`add_subparsers` call will work::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001608
1609 >>> parser = argparse.ArgumentParser()
1610 >>> subparsers = parser.add_subparsers(dest='subparser_name')
1611 >>> subparser1 = subparsers.add_parser('1')
1612 >>> subparser1.add_argument('-x')
1613 >>> subparser2 = subparsers.add_parser('2')
1614 >>> subparser2.add_argument('y')
1615 >>> parser.parse_args(['2', 'frobble'])
1616 Namespace(subparser_name='2', y='frobble')
1617
1618
1619FileType objects
1620^^^^^^^^^^^^^^^^
1621
Petri Lehtinen74d6c252012-12-15 22:39:32 +02001622.. class:: FileType(mode='r', bufsize=-1, encoding=None, errors=None)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001623
1624 The :class:`FileType` factory creates objects that can be passed to the type
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001625 argument of :meth:`ArgumentParser.add_argument`. Arguments that have
Petri Lehtinen74d6c252012-12-15 22:39:32 +02001626 :class:`FileType` objects as their type will open command-line arguments as
1627 files with the requested modes, buffer sizes, encodings and error handling
1628 (see the :func:`open` function for more details)::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001629
Éric Araujoc3ef0372012-02-20 01:44:55 +01001630 >>> parser = argparse.ArgumentParser()
Petri Lehtinen74d6c252012-12-15 22:39:32 +02001631 >>> parser.add_argument('--raw', type=argparse.FileType('wb', 0))
1632 >>> parser.add_argument('out', type=argparse.FileType('w', encoding='UTF-8'))
1633 >>> parser.parse_args(['--raw', 'raw.dat', 'file.txt'])
1634 Namespace(out=<_io.TextIOWrapper name='file.txt' mode='w' encoding='UTF-8'>, raw=<_io.FileIO name='raw.dat' mode='wb'>)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001635
1636 FileType objects understand the pseudo-argument ``'-'`` and automatically
1637 convert this into ``sys.stdin`` for readable :class:`FileType` objects and
Éric Araujoc3ef0372012-02-20 01:44:55 +01001638 ``sys.stdout`` for writable :class:`FileType` objects::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001639
Éric Araujoc3ef0372012-02-20 01:44:55 +01001640 >>> parser = argparse.ArgumentParser()
1641 >>> parser.add_argument('infile', type=argparse.FileType('r'))
1642 >>> parser.parse_args(['-'])
1643 Namespace(infile=<_io.TextIOWrapper name='<stdin>' encoding='UTF-8'>)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001644
1645
1646Argument groups
1647^^^^^^^^^^^^^^^
1648
Georg Brandle0bf91d2010-10-17 10:34:28 +00001649.. method:: ArgumentParser.add_argument_group(title=None, description=None)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001650
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001651 By default, :class:`ArgumentParser` groups command-line arguments into
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001652 "positional arguments" and "optional arguments" when displaying help
1653 messages. When there is a better conceptual grouping of arguments than this
1654 default one, appropriate groups can be created using the
1655 :meth:`add_argument_group` method::
1656
1657 >>> parser = argparse.ArgumentParser(prog='PROG', add_help=False)
1658 >>> group = parser.add_argument_group('group')
1659 >>> group.add_argument('--foo', help='foo help')
1660 >>> group.add_argument('bar', help='bar help')
1661 >>> parser.print_help()
1662 usage: PROG [--foo FOO] bar
1663
1664 group:
1665 bar bar help
1666 --foo FOO foo help
1667
1668 The :meth:`add_argument_group` method returns an argument group object which
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001669 has an :meth:`~ArgumentParser.add_argument` method just like a regular
1670 :class:`ArgumentParser`. When an argument is added to the group, the parser
1671 treats it just like a normal argument, but displays the argument in a
1672 separate group for help messages. The :meth:`add_argument_group` method
Georg Brandle0bf91d2010-10-17 10:34:28 +00001673 accepts *title* and *description* arguments which can be used to
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001674 customize this display::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001675
1676 >>> parser = argparse.ArgumentParser(prog='PROG', add_help=False)
1677 >>> group1 = parser.add_argument_group('group1', 'group1 description')
1678 >>> group1.add_argument('foo', help='foo help')
1679 >>> group2 = parser.add_argument_group('group2', 'group2 description')
1680 >>> group2.add_argument('--bar', help='bar help')
1681 >>> parser.print_help()
1682 usage: PROG [--bar BAR] foo
1683
1684 group1:
1685 group1 description
1686
1687 foo foo help
1688
1689 group2:
1690 group2 description
1691
1692 --bar BAR bar help
1693
Sandro Tosi99e7d072012-03-26 19:36:23 +02001694 Note that any arguments not in your user-defined groups will end up back
1695 in the usual "positional arguments" and "optional arguments" sections.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001696
1697
1698Mutual exclusion
1699^^^^^^^^^^^^^^^^
1700
Georg Brandle0bf91d2010-10-17 10:34:28 +00001701.. method:: add_mutually_exclusive_group(required=False)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001702
Ezio Melotti0ee9c1b2011-04-21 16:12:17 +03001703 Create a mutually exclusive group. :mod:`argparse` will make sure that only
1704 one of the arguments in the mutually exclusive group was present on the
1705 command line::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001706
1707 >>> parser = argparse.ArgumentParser(prog='PROG')
1708 >>> group = parser.add_mutually_exclusive_group()
1709 >>> group.add_argument('--foo', action='store_true')
1710 >>> group.add_argument('--bar', action='store_false')
1711 >>> parser.parse_args(['--foo'])
1712 Namespace(bar=True, foo=True)
1713 >>> parser.parse_args(['--bar'])
1714 Namespace(bar=False, foo=False)
1715 >>> parser.parse_args(['--foo', '--bar'])
1716 usage: PROG [-h] [--foo | --bar]
1717 PROG: error: argument --bar: not allowed with argument --foo
1718
Georg Brandle0bf91d2010-10-17 10:34:28 +00001719 The :meth:`add_mutually_exclusive_group` method also accepts a *required*
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001720 argument, to indicate that at least one of the mutually exclusive arguments
1721 is required::
1722
1723 >>> parser = argparse.ArgumentParser(prog='PROG')
1724 >>> group = parser.add_mutually_exclusive_group(required=True)
1725 >>> group.add_argument('--foo', action='store_true')
1726 >>> group.add_argument('--bar', action='store_false')
1727 >>> parser.parse_args([])
1728 usage: PROG [-h] (--foo | --bar)
1729 PROG: error: one of the arguments --foo --bar is required
1730
1731 Note that currently mutually exclusive argument groups do not support the
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001732 *title* and *description* arguments of
1733 :meth:`~ArgumentParser.add_argument_group`.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001734
1735
1736Parser defaults
1737^^^^^^^^^^^^^^^
1738
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001739.. method:: ArgumentParser.set_defaults(**kwargs)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001740
1741 Most of the time, the attributes of the object returned by :meth:`parse_args`
Éric Araujod9d7bca2011-08-10 04:19:03 +02001742 will be fully determined by inspecting the command-line arguments and the argument
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001743 actions. :meth:`set_defaults` allows some additional
Georg Brandl69518bc2011-04-16 16:44:54 +02001744 attributes that are determined without any inspection of the command line to
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001745 be added::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001746
1747 >>> parser = argparse.ArgumentParser()
1748 >>> parser.add_argument('foo', type=int)
1749 >>> parser.set_defaults(bar=42, baz='badger')
1750 >>> parser.parse_args(['736'])
1751 Namespace(bar=42, baz='badger', foo=736)
1752
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001753 Note that parser-level defaults always override argument-level defaults::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001754
1755 >>> parser = argparse.ArgumentParser()
1756 >>> parser.add_argument('--foo', default='bar')
1757 >>> parser.set_defaults(foo='spam')
1758 >>> parser.parse_args([])
1759 Namespace(foo='spam')
1760
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001761 Parser-level defaults can be particularly useful when working with multiple
1762 parsers. See the :meth:`~ArgumentParser.add_subparsers` method for an
1763 example of this type.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001764
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001765.. method:: ArgumentParser.get_default(dest)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001766
1767 Get the default value for a namespace attribute, as set by either
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001768 :meth:`~ArgumentParser.add_argument` or by
1769 :meth:`~ArgumentParser.set_defaults`::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001770
1771 >>> parser = argparse.ArgumentParser()
1772 >>> parser.add_argument('--foo', default='badger')
1773 >>> parser.get_default('foo')
1774 'badger'
1775
1776
1777Printing help
1778^^^^^^^^^^^^^
1779
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001780In most typical applications, :meth:`~ArgumentParser.parse_args` will take
1781care of formatting and printing any usage or error messages. However, several
1782formatting methods are available:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001783
Georg Brandle0bf91d2010-10-17 10:34:28 +00001784.. method:: ArgumentParser.print_usage(file=None)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001785
1786 Print a brief description of how the :class:`ArgumentParser` should be
R. David Murray32e17712010-12-18 16:39:06 +00001787 invoked on the command line. If *file* is ``None``, :data:`sys.stdout` is
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001788 assumed.
1789
Georg Brandle0bf91d2010-10-17 10:34:28 +00001790.. method:: ArgumentParser.print_help(file=None)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001791
1792 Print a help message, including the program usage and information about the
Georg Brandle0bf91d2010-10-17 10:34:28 +00001793 arguments registered with the :class:`ArgumentParser`. If *file* is
R. David Murray32e17712010-12-18 16:39:06 +00001794 ``None``, :data:`sys.stdout` is assumed.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001795
1796There are also variants of these methods that simply return a string instead of
1797printing it:
1798
Georg Brandle0bf91d2010-10-17 10:34:28 +00001799.. method:: ArgumentParser.format_usage()
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001800
1801 Return a string containing a brief description of how the
1802 :class:`ArgumentParser` should be invoked on the command line.
1803
Georg Brandle0bf91d2010-10-17 10:34:28 +00001804.. method:: ArgumentParser.format_help()
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001805
1806 Return a string containing a help message, including the program usage and
1807 information about the arguments registered with the :class:`ArgumentParser`.
1808
1809
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001810Partial parsing
1811^^^^^^^^^^^^^^^
1812
Georg Brandle0bf91d2010-10-17 10:34:28 +00001813.. method:: ArgumentParser.parse_known_args(args=None, namespace=None)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001814
Georg Brandl69518bc2011-04-16 16:44:54 +02001815Sometimes a script may only parse a few of the command-line arguments, passing
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001816the remaining arguments on to another script or program. In these cases, the
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001817:meth:`~ArgumentParser.parse_known_args` method can be useful. It works much like
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001818:meth:`~ArgumentParser.parse_args` except that it does not produce an error when
1819extra arguments are present. Instead, it returns a two item tuple containing
1820the populated namespace and the list of remaining argument strings.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001821
1822::
1823
1824 >>> parser = argparse.ArgumentParser()
1825 >>> parser.add_argument('--foo', action='store_true')
1826 >>> parser.add_argument('bar')
1827 >>> parser.parse_known_args(['--foo', '--badger', 'BAR', 'spam'])
1828 (Namespace(bar='BAR', foo=True), ['--badger', 'spam'])
1829
1830
1831Customizing file parsing
1832^^^^^^^^^^^^^^^^^^^^^^^^
1833
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001834.. method:: ArgumentParser.convert_arg_line_to_args(arg_line)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001835
Georg Brandle0bf91d2010-10-17 10:34:28 +00001836 Arguments that are read from a file (see the *fromfile_prefix_chars*
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001837 keyword argument to the :class:`ArgumentParser` constructor) are read one
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001838 argument per line. :meth:`convert_arg_line_to_args` can be overriden for
1839 fancier reading.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001840
Georg Brandle0bf91d2010-10-17 10:34:28 +00001841 This method takes a single argument *arg_line* which is a string read from
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001842 the argument file. It returns a list of arguments parsed from this string.
1843 The method is called once per line read from the argument file, in order.
1844
1845 A useful override of this method is one that treats each space-separated word
1846 as an argument::
1847
1848 def convert_arg_line_to_args(self, arg_line):
1849 for arg in arg_line.split():
1850 if not arg.strip():
1851 continue
1852 yield arg
1853
1854
Georg Brandl93754922010-10-17 10:28:04 +00001855Exiting methods
1856^^^^^^^^^^^^^^^
1857
1858.. method:: ArgumentParser.exit(status=0, message=None)
1859
1860 This method terminates the program, exiting with the specified *status*
1861 and, if given, it prints a *message* before that.
1862
1863.. method:: ArgumentParser.error(message)
1864
1865 This method prints a usage message including the *message* to the
Senthil Kumaran86a1a892011-08-03 07:42:18 +08001866 standard error and terminates the program with a status code of 2.
Georg Brandl93754922010-10-17 10:28:04 +00001867
Raymond Hettinger677e10a2010-12-07 06:45:30 +00001868.. _upgrading-optparse-code:
Georg Brandl93754922010-10-17 10:28:04 +00001869
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001870Upgrading optparse code
1871-----------------------
1872
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001873Originally, the :mod:`argparse` module had attempted to maintain compatibility
Ezio Melotti0ee9c1b2011-04-21 16:12:17 +03001874with :mod:`optparse`. However, :mod:`optparse` was difficult to extend
1875transparently, particularly with the changes required to support the new
1876``nargs=`` specifiers and better usage messages. When most everything in
1877:mod:`optparse` had either been copy-pasted over or monkey-patched, it no
1878longer seemed practical to try to maintain the backwards compatibility.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001879
Ezio Melotti0ee9c1b2011-04-21 16:12:17 +03001880A partial upgrade path from :mod:`optparse` to :mod:`argparse`:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001881
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001882* Replace all :meth:`optparse.OptionParser.add_option` calls with
1883 :meth:`ArgumentParser.add_argument` calls.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001884
R David Murray5e0c5712012-03-30 18:07:42 -04001885* Replace ``(options, args) = parser.parse_args()`` with ``args =
Georg Brandlc9007082011-01-09 09:04:08 +00001886 parser.parse_args()`` and add additional :meth:`ArgumentParser.add_argument`
R David Murray5e0c5712012-03-30 18:07:42 -04001887 calls for the positional arguments. Keep in mind that what was previously
1888 called ``options``, now in :mod:`argparse` context is called ``args``.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001889
1890* Replace callback actions and the ``callback_*`` keyword arguments with
1891 ``type`` or ``action`` arguments.
1892
1893* Replace string names for ``type`` keyword arguments with the corresponding
1894 type objects (e.g. int, float, complex, etc).
1895
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001896* Replace :class:`optparse.Values` with :class:`Namespace` and
1897 :exc:`optparse.OptionError` and :exc:`optparse.OptionValueError` with
1898 :exc:`ArgumentError`.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001899
1900* Replace strings with implicit arguments such as ``%default`` or ``%prog`` with
Ezio Melotticca4ef82011-04-21 15:26:46 +03001901 the standard Python syntax to use dictionaries to format strings, that is,
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001902 ``%(default)s`` and ``%(prog)s``.
Steven Bethard59710962010-05-24 03:21:08 +00001903
1904* Replace the OptionParser constructor ``version`` argument with a call to
1905 ``parser.add_argument('--version', action='version', version='<the version>')``