blob: 6181ee2c7a69b6619be3f0984f01473514a0a4c8 [file] [log] [blame]
Georg Brandl69518bc2011-04-16 16:44:54 +02001:mod:`argparse` --- Parser for command-line options, arguments and sub-commands
Georg Brandle0bf91d2010-10-17 10:34:28 +00002===============================================================================
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003
4.. module:: argparse
Éric Araujod9d7bca2011-08-10 04:19:03 +02005 :synopsis: Command-line option and argument parsing library.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00006.. moduleauthor:: Steven Bethard <steven.bethard@gmail.com>
Benjamin Peterson698a18a2010-03-02 22:34:37 +00007.. sectionauthor:: Steven Bethard <steven.bethard@gmail.com>
8
Raymond Hettingera1993682011-01-27 01:20:32 +00009.. versionadded:: 3.2
10
Éric Araujo19f9b712011-08-19 00:49:18 +020011**Source code:** :source:`Lib/argparse.py`
12
Raymond Hettingera1993682011-01-27 01:20:32 +000013--------------
Benjamin Peterson698a18a2010-03-02 22:34:37 +000014
Ezio Melotti6cc7a412012-05-06 16:15:35 +030015.. sidebar:: Tutorial
16
17 This page contains the API reference information. For a more gentle
18 introduction to Python command-line parsing, have a look at the
19 :ref:`argparse tutorial <argparse-tutorial>`.
20
Ezio Melotti2409d772011-04-16 23:13:50 +030021The :mod:`argparse` module makes it easy to write user-friendly command-line
Benjamin Peterson98047eb2010-03-03 02:07:08 +000022interfaces. The program defines what arguments it requires, and :mod:`argparse`
Benjamin Peterson698a18a2010-03-02 22:34:37 +000023will figure out how to parse those out of :data:`sys.argv`. The :mod:`argparse`
Benjamin Peterson98047eb2010-03-03 02:07:08 +000024module also automatically generates help and usage messages and issues errors
25when users give the program invalid arguments.
Benjamin Peterson698a18a2010-03-02 22:34:37 +000026
Georg Brandle0bf91d2010-10-17 10:34:28 +000027
Benjamin Peterson698a18a2010-03-02 22:34:37 +000028Example
29-------
30
Benjamin Peterson98047eb2010-03-03 02:07:08 +000031The following code is a Python program that takes a list of integers and
32produces either the sum or the max::
Benjamin Peterson698a18a2010-03-02 22:34:37 +000033
34 import argparse
35
36 parser = argparse.ArgumentParser(description='Process some integers.')
37 parser.add_argument('integers', metavar='N', type=int, nargs='+',
38 help='an integer for the accumulator')
39 parser.add_argument('--sum', dest='accumulate', action='store_const',
40 const=sum, default=max,
41 help='sum the integers (default: find the max)')
42
43 args = parser.parse_args()
Benjamin Petersonb2deb112010-03-03 02:09:18 +000044 print(args.accumulate(args.integers))
Benjamin Peterson698a18a2010-03-02 22:34:37 +000045
46Assuming the Python code above is saved into a file called ``prog.py``, it can
47be run at the command line and provides useful help messages::
48
Georg Brandl29fc4bf2013-10-06 19:33:56 +020049 $ python prog.py -h
Benjamin Peterson698a18a2010-03-02 22:34:37 +000050 usage: prog.py [-h] [--sum] N [N ...]
51
52 Process some integers.
53
54 positional arguments:
55 N an integer for the accumulator
56
57 optional arguments:
58 -h, --help show this help message and exit
59 --sum sum the integers (default: find the max)
60
61When run with the appropriate arguments, it prints either the sum or the max of
62the command-line integers::
63
Georg Brandl29fc4bf2013-10-06 19:33:56 +020064 $ python prog.py 1 2 3 4
Benjamin Peterson698a18a2010-03-02 22:34:37 +000065 4
66
Georg Brandl29fc4bf2013-10-06 19:33:56 +020067 $ python prog.py 1 2 3 4 --sum
Benjamin Peterson698a18a2010-03-02 22:34:37 +000068 10
69
70If invalid arguments are passed in, it will issue an error::
71
Georg Brandl29fc4bf2013-10-06 19:33:56 +020072 $ python prog.py a b c
Benjamin Peterson698a18a2010-03-02 22:34:37 +000073 usage: prog.py [-h] [--sum] N [N ...]
74 prog.py: error: argument N: invalid int value: 'a'
75
76The following sections walk you through this example.
77
Georg Brandle0bf91d2010-10-17 10:34:28 +000078
Benjamin Peterson698a18a2010-03-02 22:34:37 +000079Creating a parser
80^^^^^^^^^^^^^^^^^
81
Benjamin Peterson2614cda2010-03-21 22:36:19 +000082The first step in using the :mod:`argparse` is creating an
Benjamin Peterson98047eb2010-03-03 02:07:08 +000083:class:`ArgumentParser` object::
Benjamin Peterson698a18a2010-03-02 22:34:37 +000084
85 >>> parser = argparse.ArgumentParser(description='Process some integers.')
86
87The :class:`ArgumentParser` object will hold all the information necessary to
Ezio Melotticca4ef82011-04-21 15:26:46 +030088parse the command line into Python data types.
Benjamin Peterson698a18a2010-03-02 22:34:37 +000089
90
91Adding arguments
92^^^^^^^^^^^^^^^^
93
Benjamin Peterson98047eb2010-03-03 02:07:08 +000094Filling an :class:`ArgumentParser` with information about program arguments is
95done by making calls to the :meth:`~ArgumentParser.add_argument` method.
96Generally, these calls tell the :class:`ArgumentParser` how to take the strings
97on the command line and turn them into objects. This information is stored and
98used when :meth:`~ArgumentParser.parse_args` is called. For example::
Benjamin Peterson698a18a2010-03-02 22:34:37 +000099
100 >>> parser.add_argument('integers', metavar='N', type=int, nargs='+',
101 ... help='an integer for the accumulator')
102 >>> parser.add_argument('--sum', dest='accumulate', action='store_const',
103 ... const=sum, default=max,
104 ... help='sum the integers (default: find the max)')
105
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300106Later, calling :meth:`~ArgumentParser.parse_args` will return an object with
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000107two attributes, ``integers`` and ``accumulate``. The ``integers`` attribute
108will be a list of one or more ints, and the ``accumulate`` attribute will be
109either the :func:`sum` function, if ``--sum`` was specified at the command line,
110or the :func:`max` function if it was not.
111
Georg Brandle0bf91d2010-10-17 10:34:28 +0000112
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000113Parsing arguments
114^^^^^^^^^^^^^^^^^
115
Éric Araujod9d7bca2011-08-10 04:19:03 +0200116:class:`ArgumentParser` parses arguments through the
Georg Brandl69518bc2011-04-16 16:44:54 +0200117:meth:`~ArgumentParser.parse_args` method. This will inspect the command line,
Éric Araujofde92422011-08-19 01:30:26 +0200118convert each argument to the appropriate type and then invoke the appropriate action.
Éric Araujo63b18a42011-07-29 17:59:17 +0200119In most cases, this means a simple :class:`Namespace` object will be built up from
Georg Brandl69518bc2011-04-16 16:44:54 +0200120attributes parsed out of the command line::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000121
122 >>> parser.parse_args(['--sum', '7', '-1', '42'])
123 Namespace(accumulate=<built-in function sum>, integers=[7, -1, 42])
124
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000125In a script, :meth:`~ArgumentParser.parse_args` will typically be called with no
126arguments, and the :class:`ArgumentParser` will automatically determine the
Éric Araujod9d7bca2011-08-10 04:19:03 +0200127command-line arguments from :data:`sys.argv`.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000128
129
130ArgumentParser objects
131----------------------
132
Ezio Melottie0add762012-09-14 06:32:35 +0300133.. class:: ArgumentParser(prog=None, usage=None, description=None, \
134 epilog=None, parents=[], \
135 formatter_class=argparse.HelpFormatter, \
136 prefix_chars='-', fromfile_prefix_chars=None, \
137 argument_default=None, conflict_handler='error', \
Berker Peksag8089cd62015-02-14 01:39:17 +0200138 add_help=True, allow_abbrev=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
Berker Peksag8089cd62015-02-14 01:39:17 +0200172 * allow_abbrev_ - Allows long options to be abbreviated if the
173 abbreviation is unambiguous. (default: ``True``)
174
175 .. versionchanged:: 3.5
176 *allow_abbrev* parameter was added.
177
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000178The following sections describe how each of these are used.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000179
180
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300181prog
182^^^^
183
184By default, :class:`ArgumentParser` objects uses ``sys.argv[0]`` to determine
185how to display the name of the program in help messages. This default is almost
186always desirable because it will make the help messages match how the program was
187invoked on the command line. For example, consider a file named
188``myprogram.py`` with the following code::
189
190 import argparse
191 parser = argparse.ArgumentParser()
192 parser.add_argument('--foo', help='foo help')
193 args = parser.parse_args()
194
195The help for this program will display ``myprogram.py`` as the program name
196(regardless of where the program was invoked from)::
197
198 $ python myprogram.py --help
199 usage: myprogram.py [-h] [--foo FOO]
200
201 optional arguments:
202 -h, --help show this help message and exit
203 --foo FOO foo help
204 $ cd ..
205 $ python subdir\myprogram.py --help
206 usage: myprogram.py [-h] [--foo FOO]
207
208 optional arguments:
209 -h, --help show this help message and exit
210 --foo FOO foo help
211
212To change this default behavior, another value can be supplied using the
213``prog=`` argument to :class:`ArgumentParser`::
214
215 >>> parser = argparse.ArgumentParser(prog='myprogram')
216 >>> parser.print_help()
217 usage: myprogram [-h]
218
219 optional arguments:
220 -h, --help show this help message and exit
221
222Note that the program name, whether determined from ``sys.argv[0]`` or from the
223``prog=`` argument, is available to help messages using the ``%(prog)s`` format
224specifier.
225
226::
227
228 >>> parser = argparse.ArgumentParser(prog='myprogram')
229 >>> parser.add_argument('--foo', help='foo of the %(prog)s program')
230 >>> parser.print_help()
231 usage: myprogram [-h] [--foo FOO]
232
233 optional arguments:
234 -h, --help show this help message and exit
235 --foo FOO foo of the myprogram program
236
237
238usage
239^^^^^
240
241By default, :class:`ArgumentParser` calculates the usage message from the
242arguments it contains::
243
244 >>> parser = argparse.ArgumentParser(prog='PROG')
245 >>> parser.add_argument('--foo', nargs='?', help='foo help')
246 >>> parser.add_argument('bar', nargs='+', help='bar help')
247 >>> parser.print_help()
248 usage: PROG [-h] [--foo [FOO]] bar [bar ...]
249
250 positional arguments:
251 bar bar help
252
253 optional arguments:
254 -h, --help show this help message and exit
255 --foo [FOO] foo help
256
257The default message can be overridden with the ``usage=`` keyword argument::
258
259 >>> parser = argparse.ArgumentParser(prog='PROG', usage='%(prog)s [options]')
260 >>> parser.add_argument('--foo', nargs='?', help='foo help')
261 >>> parser.add_argument('bar', nargs='+', help='bar help')
262 >>> parser.print_help()
263 usage: PROG [options]
264
265 positional arguments:
266 bar bar help
267
268 optional arguments:
269 -h, --help show this help message and exit
270 --foo [FOO] foo help
271
272The ``%(prog)s`` format specifier is available to fill in the program name in
273your usage messages.
274
275
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000276description
277^^^^^^^^^^^
278
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000279Most calls to the :class:`ArgumentParser` constructor will use the
280``description=`` keyword argument. This argument gives a brief description of
281what the program does and how it works. In help messages, the description is
282displayed between the command-line usage string and the help messages for the
283various arguments::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000284
285 >>> parser = argparse.ArgumentParser(description='A foo that bars')
286 >>> parser.print_help()
287 usage: argparse.py [-h]
288
289 A foo that bars
290
291 optional arguments:
292 -h, --help show this help message and exit
293
294By default, the description will be line-wrapped so that it fits within the
295given space. To change this behavior, see the formatter_class_ argument.
296
297
298epilog
299^^^^^^
300
301Some programs like to display additional description of the program after the
302description of the arguments. Such text can be specified using the ``epilog=``
303argument to :class:`ArgumentParser`::
304
305 >>> parser = argparse.ArgumentParser(
306 ... description='A foo that bars',
307 ... epilog="And that's how you'd foo a bar")
308 >>> parser.print_help()
309 usage: argparse.py [-h]
310
311 A foo that bars
312
313 optional arguments:
314 -h, --help show this help message and exit
315
316 And that's how you'd foo a bar
317
318As with the description_ argument, the ``epilog=`` text is by default
319line-wrapped, but this behavior can be adjusted with the formatter_class_
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000320argument to :class:`ArgumentParser`.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000321
322
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000323parents
324^^^^^^^
325
326Sometimes, several parsers share a common set of arguments. Rather than
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000327repeating the definitions of these arguments, a single parser with all the
328shared arguments and passed to ``parents=`` argument to :class:`ArgumentParser`
329can be used. The ``parents=`` argument takes a list of :class:`ArgumentParser`
330objects, collects all the positional and optional actions from them, and adds
331these actions to the :class:`ArgumentParser` object being constructed::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000332
333 >>> parent_parser = argparse.ArgumentParser(add_help=False)
334 >>> parent_parser.add_argument('--parent', type=int)
335
336 >>> foo_parser = argparse.ArgumentParser(parents=[parent_parser])
337 >>> foo_parser.add_argument('foo')
338 >>> foo_parser.parse_args(['--parent', '2', 'XXX'])
339 Namespace(foo='XXX', parent=2)
340
341 >>> bar_parser = argparse.ArgumentParser(parents=[parent_parser])
342 >>> bar_parser.add_argument('--bar')
343 >>> bar_parser.parse_args(['--bar', 'YYY'])
344 Namespace(bar='YYY', parent=None)
345
346Note that most parent parsers will specify ``add_help=False``. Otherwise, the
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000347:class:`ArgumentParser` will see two ``-h/--help`` options (one in the parent
348and one in the child) and raise an error.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000349
Steven Bethardd186f992011-03-26 21:49:00 +0100350.. note::
351 You must fully initialize the parsers before passing them via ``parents=``.
352 If you change the parent parsers after the child parser, those changes will
353 not be reflected in the child.
354
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000355
356formatter_class
357^^^^^^^^^^^^^^^
358
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000359:class:`ArgumentParser` objects allow the help formatting to be customized by
Ezio Melotti707d1e62011-04-22 01:57:47 +0300360specifying an alternate formatting class. Currently, there are four such
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300361classes:
362
363.. class:: RawDescriptionHelpFormatter
364 RawTextHelpFormatter
365 ArgumentDefaultsHelpFormatter
Ezio Melotti707d1e62011-04-22 01:57:47 +0300366 MetavarTypeHelpFormatter
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000367
Steven Bethard0331e902011-03-26 14:48:04 +0100368:class:`RawDescriptionHelpFormatter` and :class:`RawTextHelpFormatter` give
369more control over how textual descriptions are displayed.
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000370By default, :class:`ArgumentParser` objects line-wrap the description_ and
371epilog_ texts in command-line help messages::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000372
373 >>> parser = argparse.ArgumentParser(
374 ... prog='PROG',
375 ... description='''this description
376 ... was indented weird
377 ... but that is okay''',
378 ... epilog='''
379 ... likewise for this epilog whose whitespace will
380 ... be cleaned up and whose words will be wrapped
381 ... across a couple lines''')
382 >>> parser.print_help()
383 usage: PROG [-h]
384
385 this description was indented weird but that is okay
386
387 optional arguments:
388 -h, --help show this help message and exit
389
390 likewise for this epilog whose whitespace will be cleaned up and whose words
391 will be wrapped across a couple lines
392
Steven Bethard0331e902011-03-26 14:48:04 +0100393Passing :class:`RawDescriptionHelpFormatter` as ``formatter_class=``
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000394indicates that description_ and epilog_ are already correctly formatted and
395should not be line-wrapped::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000396
397 >>> parser = argparse.ArgumentParser(
398 ... prog='PROG',
399 ... formatter_class=argparse.RawDescriptionHelpFormatter,
400 ... description=textwrap.dedent('''\
401 ... Please do not mess up this text!
402 ... --------------------------------
403 ... I have indented it
404 ... exactly the way
405 ... I want it
406 ... '''))
407 >>> parser.print_help()
408 usage: PROG [-h]
409
410 Please do not mess up this text!
411 --------------------------------
412 I have indented it
413 exactly the way
414 I want it
415
416 optional arguments:
417 -h, --help show this help message and exit
418
Steven Bethard0331e902011-03-26 14:48:04 +0100419:class:`RawTextHelpFormatter` maintains whitespace for all sorts of help text,
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000420including argument descriptions.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000421
Steven Bethard0331e902011-03-26 14:48:04 +0100422:class:`ArgumentDefaultsHelpFormatter` automatically adds information about
423default values to each of the argument help messages::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000424
425 >>> parser = argparse.ArgumentParser(
426 ... prog='PROG',
427 ... formatter_class=argparse.ArgumentDefaultsHelpFormatter)
428 >>> parser.add_argument('--foo', type=int, default=42, help='FOO!')
429 >>> parser.add_argument('bar', nargs='*', default=[1, 2, 3], help='BAR!')
430 >>> parser.print_help()
431 usage: PROG [-h] [--foo FOO] [bar [bar ...]]
432
433 positional arguments:
434 bar BAR! (default: [1, 2, 3])
435
436 optional arguments:
437 -h, --help show this help message and exit
438 --foo FOO FOO! (default: 42)
439
Steven Bethard0331e902011-03-26 14:48:04 +0100440:class:`MetavarTypeHelpFormatter` uses the name of the type_ argument for each
Ezio Melottif1064492011-10-19 11:06:26 +0300441argument as the display name for its values (rather than using the dest_
Steven Bethard0331e902011-03-26 14:48:04 +0100442as the regular formatter does)::
443
444 >>> parser = argparse.ArgumentParser(
445 ... prog='PROG',
446 ... formatter_class=argparse.MetavarTypeHelpFormatter)
447 >>> parser.add_argument('--foo', type=int)
448 >>> parser.add_argument('bar', type=float)
449 >>> parser.print_help()
450 usage: PROG [-h] [--foo int] float
451
452 positional arguments:
453 float
454
455 optional arguments:
456 -h, --help show this help message and exit
457 --foo int
458
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000459
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300460prefix_chars
461^^^^^^^^^^^^
462
463Most command-line options will use ``-`` as the prefix, e.g. ``-f/--foo``.
464Parsers that need to support different or additional prefix
465characters, e.g. for options
466like ``+f`` or ``/foo``, may specify them using the ``prefix_chars=`` argument
467to the ArgumentParser constructor::
468
469 >>> parser = argparse.ArgumentParser(prog='PROG', prefix_chars='-+')
470 >>> parser.add_argument('+f')
471 >>> parser.add_argument('++bar')
472 >>> parser.parse_args('+f X ++bar Y'.split())
473 Namespace(bar='Y', f='X')
474
475The ``prefix_chars=`` argument defaults to ``'-'``. Supplying a set of
476characters that does not include ``-`` will cause ``-f/--foo`` options to be
477disallowed.
478
479
480fromfile_prefix_chars
481^^^^^^^^^^^^^^^^^^^^^
482
483Sometimes, for example when dealing with a particularly long argument lists, it
484may make sense to keep the list of arguments in a file rather than typing it out
485at the command line. If the ``fromfile_prefix_chars=`` argument is given to the
486:class:`ArgumentParser` constructor, then arguments that start with any of the
487specified characters will be treated as files, and will be replaced by the
488arguments they contain. For example::
489
490 >>> with open('args.txt', 'w') as fp:
491 ... fp.write('-f\nbar')
492 >>> parser = argparse.ArgumentParser(fromfile_prefix_chars='@')
493 >>> parser.add_argument('-f')
494 >>> parser.parse_args(['-f', 'foo', '@args.txt'])
495 Namespace(f='bar')
496
497Arguments read from a file must by default be one per line (but see also
498:meth:`~ArgumentParser.convert_arg_line_to_args`) and are treated as if they
499were in the same place as the original file referencing argument on the command
500line. So in the example above, the expression ``['-f', 'foo', '@args.txt']``
501is considered equivalent to the expression ``['-f', 'foo', '-f', 'bar']``.
502
503The ``fromfile_prefix_chars=`` argument defaults to ``None``, meaning that
504arguments will never be treated as file references.
505
506
507argument_default
508^^^^^^^^^^^^^^^^
509
510Generally, argument defaults are specified either by passing a default to
511:meth:`~ArgumentParser.add_argument` or by calling the
512:meth:`~ArgumentParser.set_defaults` methods with a specific set of name-value
513pairs. Sometimes however, it may be useful to specify a single parser-wide
514default for arguments. This can be accomplished by passing the
515``argument_default=`` keyword argument to :class:`ArgumentParser`. For example,
516to globally suppress attribute creation on :meth:`~ArgumentParser.parse_args`
517calls, we supply ``argument_default=SUPPRESS``::
518
519 >>> parser = argparse.ArgumentParser(argument_default=argparse.SUPPRESS)
520 >>> parser.add_argument('--foo')
521 >>> parser.add_argument('bar', nargs='?')
522 >>> parser.parse_args(['--foo', '1', 'BAR'])
523 Namespace(bar='BAR', foo='1')
524 >>> parser.parse_args([])
525 Namespace()
526
Berker Peksag8089cd62015-02-14 01:39:17 +0200527.. _allow_abbrev:
528
529allow_abbrev
530^^^^^^^^^^^^
531
532Normally, when you pass an argument list to the
Martin Panterd2ad5712015-11-02 04:20:33 +0000533:meth:`~ArgumentParser.parse_args` method of an :class:`ArgumentParser`,
Berker Peksag8089cd62015-02-14 01:39:17 +0200534it :ref:`recognizes abbreviations <prefix-matching>` of long options.
535
536This feature can be disabled by setting ``allow_abbrev`` to ``False``::
537
538 >>> parser = argparse.ArgumentParser(prog='PROG', allow_abbrev=False)
539 >>> parser.add_argument('--foobar', action='store_true')
540 >>> parser.add_argument('--foonley', action='store_false')
Berker Peksage7e497b2015-03-12 20:47:41 +0200541 >>> parser.parse_args(['--foon'])
Berker Peksag8089cd62015-02-14 01:39:17 +0200542 usage: PROG [-h] [--foobar] [--foonley]
543 PROG: error: unrecognized arguments: --foon
544
545.. versionadded:: 3.5
546
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300547
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000548conflict_handler
549^^^^^^^^^^^^^^^^
550
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000551:class:`ArgumentParser` objects do not allow two actions with the same option
552string. By default, :class:`ArgumentParser` objects raises an exception if an
553attempt is made to create an argument with an option string that is already in
554use::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000555
556 >>> parser = argparse.ArgumentParser(prog='PROG')
557 >>> parser.add_argument('-f', '--foo', help='old foo help')
558 >>> parser.add_argument('--foo', help='new foo help')
559 Traceback (most recent call last):
560 ..
561 ArgumentError: argument --foo: conflicting option string(s): --foo
562
563Sometimes (e.g. when using parents_) it may be useful to simply override any
564older arguments with the same option string. To get this behavior, the value
565``'resolve'`` can be supplied to the ``conflict_handler=`` argument of
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000566:class:`ArgumentParser`::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000567
568 >>> parser = argparse.ArgumentParser(prog='PROG', conflict_handler='resolve')
569 >>> parser.add_argument('-f', '--foo', help='old foo help')
570 >>> parser.add_argument('--foo', help='new foo help')
571 >>> parser.print_help()
572 usage: PROG [-h] [-f FOO] [--foo FOO]
573
574 optional arguments:
575 -h, --help show this help message and exit
576 -f FOO old foo help
577 --foo FOO new foo help
578
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000579Note that :class:`ArgumentParser` objects only remove an action if all of its
580option strings are overridden. So, in the example above, the old ``-f/--foo``
581action is retained as the ``-f`` action, because only the ``--foo`` option
582string was overridden.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000583
584
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300585add_help
586^^^^^^^^
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000587
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300588By default, ArgumentParser objects add an option which simply displays
589the parser's help message. For example, consider a file named
590``myprogram.py`` containing the following code::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000591
592 import argparse
593 parser = argparse.ArgumentParser()
594 parser.add_argument('--foo', help='foo help')
595 args = parser.parse_args()
596
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300597If ``-h`` or ``--help`` is supplied at the command line, the ArgumentParser
598help will be printed::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000599
600 $ python myprogram.py --help
601 usage: myprogram.py [-h] [--foo FOO]
602
603 optional arguments:
604 -h, --help show this help message and exit
605 --foo FOO foo help
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000606
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300607Occasionally, it may be useful to disable the addition of this help option.
608This can be achieved by passing ``False`` as the ``add_help=`` argument to
609:class:`ArgumentParser`::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000610
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300611 >>> parser = argparse.ArgumentParser(prog='PROG', add_help=False)
612 >>> parser.add_argument('--foo', help='foo help')
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000613 >>> parser.print_help()
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300614 usage: PROG [--foo FOO]
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000615
616 optional arguments:
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300617 --foo FOO foo help
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000618
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300619The help option is typically ``-h/--help``. The exception to this is
620if the ``prefix_chars=`` is specified and does not include ``-``, in
621which case ``-h`` and ``--help`` are not valid options. In
622this case, the first character in ``prefix_chars`` is used to prefix
623the help options::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000624
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300625 >>> parser = argparse.ArgumentParser(prog='PROG', prefix_chars='+/')
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000626 >>> parser.print_help()
Georg Brandld2914ce2013-10-06 09:50:36 +0200627 usage: PROG [+h]
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000628
629 optional arguments:
Georg Brandld2914ce2013-10-06 09:50:36 +0200630 +h, ++help show this help message and exit
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000631
632
633The add_argument() method
634-------------------------
635
Georg Brandlc9007082011-01-09 09:04:08 +0000636.. method:: ArgumentParser.add_argument(name or flags..., [action], [nargs], \
637 [const], [default], [type], [choices], [required], \
638 [help], [metavar], [dest])
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000639
Georg Brandl69518bc2011-04-16 16:44:54 +0200640 Define how a single command-line argument should be parsed. Each parameter
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000641 has its own more detailed description below, but in short they are:
642
643 * `name or flags`_ - Either a name or a list of option strings, e.g. ``foo``
Ezio Melottidca309d2011-04-21 23:09:27 +0300644 or ``-f, --foo``.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000645
646 * action_ - The basic type of action to be taken when this argument is
Georg Brandl69518bc2011-04-16 16:44:54 +0200647 encountered at the command line.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000648
649 * nargs_ - The number of command-line arguments that should be consumed.
650
651 * const_ - A constant value required by some action_ and nargs_ selections.
652
653 * default_ - The value produced if the argument is absent from the
Georg Brandl69518bc2011-04-16 16:44:54 +0200654 command line.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000655
Ezio Melotti2409d772011-04-16 23:13:50 +0300656 * type_ - The type to which the command-line argument should be converted.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000657
658 * choices_ - A container of the allowable values for the argument.
659
660 * required_ - Whether or not the command-line option may be omitted
661 (optionals only).
662
663 * help_ - A brief description of what the argument does.
664
665 * metavar_ - A name for the argument in usage messages.
666
667 * dest_ - The name of the attribute to be added to the object returned by
668 :meth:`parse_args`.
669
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000670The following sections describe how each of these are used.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000671
Georg Brandle0bf91d2010-10-17 10:34:28 +0000672
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000673name or flags
674^^^^^^^^^^^^^
675
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300676The :meth:`~ArgumentParser.add_argument` method must know whether an optional
677argument, like ``-f`` or ``--foo``, or a positional argument, like a list of
678filenames, is expected. The first arguments passed to
679:meth:`~ArgumentParser.add_argument` must therefore be either a series of
680flags, or a simple argument name. For example, an optional argument could
681be created like::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000682
683 >>> parser.add_argument('-f', '--foo')
684
685while a positional argument could be created like::
686
687 >>> parser.add_argument('bar')
688
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300689When :meth:`~ArgumentParser.parse_args` is called, optional arguments will be
690identified by the ``-`` prefix, and the remaining arguments will be assumed to
691be positional::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000692
693 >>> parser = argparse.ArgumentParser(prog='PROG')
694 >>> parser.add_argument('-f', '--foo')
695 >>> parser.add_argument('bar')
696 >>> parser.parse_args(['BAR'])
697 Namespace(bar='BAR', foo=None)
698 >>> parser.parse_args(['BAR', '--foo', 'FOO'])
699 Namespace(bar='BAR', foo='FOO')
700 >>> parser.parse_args(['--foo', 'FOO'])
701 usage: PROG [-h] [-f FOO] bar
702 PROG: error: too few arguments
703
Georg Brandle0bf91d2010-10-17 10:34:28 +0000704
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000705action
706^^^^^^
707
Éric Araujod9d7bca2011-08-10 04:19:03 +0200708:class:`ArgumentParser` objects associate command-line arguments with actions. These
709actions can do just about anything with the command-line arguments associated with
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000710them, though most actions simply add an attribute to the object returned by
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300711:meth:`~ArgumentParser.parse_args`. The ``action`` keyword argument specifies
Jason R. Coombsf28cf7a2011-12-13 23:36:45 -0500712how the command-line arguments should be handled. The supplied actions are:
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000713
714* ``'store'`` - This just stores the argument's value. This is the default
Ezio Melotti2f1db7d2011-04-21 23:06:48 +0300715 action. For example::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000716
717 >>> parser = argparse.ArgumentParser()
718 >>> parser.add_argument('--foo')
719 >>> parser.parse_args('--foo 1'.split())
720 Namespace(foo='1')
721
722* ``'store_const'`` - This stores the value specified by the const_ keyword
Martin Panterb4912b82016-04-09 03:49:48 +0000723 argument. The ``'store_const'`` action is most commonly used with
Ezio Melotti2f1db7d2011-04-21 23:06:48 +0300724 optional arguments that specify some sort of flag. For example::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000725
726 >>> parser = argparse.ArgumentParser()
727 >>> parser.add_argument('--foo', action='store_const', const=42)
728 >>> parser.parse_args('--foo'.split())
729 Namespace(foo=42)
730
Raymond Hettingerf9cddcc2011-11-20 11:05:23 -0800731* ``'store_true'`` and ``'store_false'`` - These are special cases of
732 ``'store_const'`` used for storing the values ``True`` and ``False``
733 respectively. In addition, they create default values of ``False`` and
734 ``True`` respectively. For example::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000735
736 >>> parser = argparse.ArgumentParser()
737 >>> parser.add_argument('--foo', action='store_true')
738 >>> parser.add_argument('--bar', action='store_false')
Raymond Hettingerf9cddcc2011-11-20 11:05:23 -0800739 >>> parser.add_argument('--baz', action='store_false')
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000740 >>> parser.parse_args('--foo --bar'.split())
Raymond Hettingerf9cddcc2011-11-20 11:05:23 -0800741 Namespace(foo=True, bar=False, baz=True)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000742
743* ``'append'`` - This stores a list, and appends each argument value to the
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000744 list. This is useful to allow an option to be specified multiple times.
745 Example usage::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000746
747 >>> parser = argparse.ArgumentParser()
748 >>> parser.add_argument('--foo', action='append')
749 >>> parser.parse_args('--foo 1 --foo 2'.split())
750 Namespace(foo=['1', '2'])
751
752* ``'append_const'`` - This stores a list, and appends the value specified by
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000753 the const_ keyword argument to the list. (Note that the const_ keyword
754 argument defaults to ``None``.) The ``'append_const'`` action is typically
755 useful when multiple arguments need to store constants to the same list. For
756 example::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000757
758 >>> parser = argparse.ArgumentParser()
759 >>> parser.add_argument('--str', dest='types', action='append_const', const=str)
760 >>> parser.add_argument('--int', dest='types', action='append_const', const=int)
761 >>> parser.parse_args('--str --int'.split())
Florent Xicluna74e64952011-10-28 11:21:19 +0200762 Namespace(types=[<class 'str'>, <class 'int'>])
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000763
Sandro Tosi98492a52012-01-04 23:25:04 +0100764* ``'count'`` - This counts the number of times a keyword argument occurs. For
765 example, this is useful for increasing verbosity levels::
766
767 >>> parser = argparse.ArgumentParser()
768 >>> parser.add_argument('--verbose', '-v', action='count')
769 >>> parser.parse_args('-vvv'.split())
770 Namespace(verbose=3)
771
772* ``'help'`` - This prints a complete help message for all the options in the
773 current parser and then exits. By default a help action is automatically
774 added to the parser. See :class:`ArgumentParser` for details of how the
775 output is created.
776
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000777* ``'version'`` - This expects a ``version=`` keyword argument in the
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300778 :meth:`~ArgumentParser.add_argument` call, and prints version information
Éric Araujoc3ef0372012-02-20 01:44:55 +0100779 and exits when invoked::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000780
781 >>> import argparse
782 >>> parser = argparse.ArgumentParser(prog='PROG')
Steven Bethard59710962010-05-24 03:21:08 +0000783 >>> parser.add_argument('--version', action='version', version='%(prog)s 2.0')
784 >>> parser.parse_args(['--version'])
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000785 PROG 2.0
786
Jason R. Coombseb0ef412014-07-20 10:52:46 -0400787You may also specify an arbitrary action by passing an Action subclass or
788other object that implements the same interface. The recommended way to do
Jason R. Coombs79690ac2014-08-03 14:54:11 -0400789this is to extend :class:`Action`, overriding the ``__call__`` method
Jason R. Coombseb0ef412014-07-20 10:52:46 -0400790and optionally the ``__init__`` method.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000791
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000792An example of a custom action::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000793
794 >>> class FooAction(argparse.Action):
Jason R. Coombseb0ef412014-07-20 10:52:46 -0400795 ... def __init__(self, option_strings, dest, nargs=None, **kwargs):
796 ... if nargs is not None:
797 ... raise ValueError("nargs not allowed")
798 ... super(FooAction, self).__init__(option_strings, dest, **kwargs)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000799 ... def __call__(self, parser, namespace, values, option_string=None):
Georg Brandl571a9532010-07-26 17:00:20 +0000800 ... print('%r %r %r' % (namespace, values, option_string))
801 ... setattr(namespace, self.dest, values)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000802 ...
803 >>> parser = argparse.ArgumentParser()
804 >>> parser.add_argument('--foo', action=FooAction)
805 >>> parser.add_argument('bar', action=FooAction)
806 >>> args = parser.parse_args('1 --foo 2'.split())
807 Namespace(bar=None, foo=None) '1' None
808 Namespace(bar='1', foo=None) '2' '--foo'
809 >>> args
810 Namespace(bar='1', foo='2')
811
Jason R. Coombs79690ac2014-08-03 14:54:11 -0400812For more details, see :class:`Action`.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000813
814nargs
815^^^^^
816
817ArgumentParser objects usually associate a single command-line argument with a
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000818single action to be taken. The ``nargs`` keyword argument associates a
Ezio Melotti00f53af2011-04-21 22:56:51 +0300819different number of command-line arguments with a single action. The supported
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000820values are:
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000821
Éric Araujoc3ef0372012-02-20 01:44:55 +0100822* ``N`` (an integer). ``N`` arguments from the command line will be gathered
823 together into a list. For example::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000824
Georg Brandl682d7e02010-10-06 10:26:05 +0000825 >>> parser = argparse.ArgumentParser()
826 >>> parser.add_argument('--foo', nargs=2)
827 >>> parser.add_argument('bar', nargs=1)
828 >>> parser.parse_args('c --foo a b'.split())
829 Namespace(bar=['c'], foo=['a', 'b'])
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000830
Georg Brandl682d7e02010-10-06 10:26:05 +0000831 Note that ``nargs=1`` produces a list of one item. This is different from
832 the default, in which the item is produced by itself.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000833
Éric Araujofde92422011-08-19 01:30:26 +0200834* ``'?'``. One argument will be consumed from the command line if possible, and
835 produced as a single item. If no command-line argument is present, the value from
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000836 default_ will be produced. Note that for optional arguments, there is an
837 additional case - the option string is present but not followed by a
Éric Araujofde92422011-08-19 01:30:26 +0200838 command-line argument. In this case the value from const_ will be produced. Some
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000839 examples to illustrate this::
840
841 >>> parser = argparse.ArgumentParser()
842 >>> parser.add_argument('--foo', nargs='?', const='c', default='d')
843 >>> parser.add_argument('bar', nargs='?', default='d')
844 >>> parser.parse_args('XX --foo YY'.split())
845 Namespace(bar='XX', foo='YY')
846 >>> parser.parse_args('XX --foo'.split())
847 Namespace(bar='XX', foo='c')
848 >>> parser.parse_args(''.split())
849 Namespace(bar='d', foo='d')
850
851 One of the more common uses of ``nargs='?'`` is to allow optional input and
852 output files::
853
854 >>> parser = argparse.ArgumentParser()
Georg Brandle0bf91d2010-10-17 10:34:28 +0000855 >>> parser.add_argument('infile', nargs='?', type=argparse.FileType('r'),
856 ... default=sys.stdin)
857 >>> parser.add_argument('outfile', nargs='?', type=argparse.FileType('w'),
858 ... default=sys.stdout)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000859 >>> parser.parse_args(['input.txt', 'output.txt'])
Georg Brandl04536b02011-01-09 09:31:01 +0000860 Namespace(infile=<_io.TextIOWrapper name='input.txt' encoding='UTF-8'>,
861 outfile=<_io.TextIOWrapper name='output.txt' encoding='UTF-8'>)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000862 >>> parser.parse_args([])
Georg Brandl04536b02011-01-09 09:31:01 +0000863 Namespace(infile=<_io.TextIOWrapper name='<stdin>' encoding='UTF-8'>,
864 outfile=<_io.TextIOWrapper name='<stdout>' encoding='UTF-8'>)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000865
Éric Araujod9d7bca2011-08-10 04:19:03 +0200866* ``'*'``. All command-line arguments present are gathered into a list. Note that
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000867 it generally doesn't make much sense to have more than one positional argument
868 with ``nargs='*'``, but multiple optional arguments with ``nargs='*'`` is
869 possible. For example::
870
871 >>> parser = argparse.ArgumentParser()
872 >>> parser.add_argument('--foo', nargs='*')
873 >>> parser.add_argument('--bar', nargs='*')
874 >>> parser.add_argument('baz', nargs='*')
875 >>> parser.parse_args('a b --foo x y --bar 1 2'.split())
876 Namespace(bar=['1', '2'], baz=['a', 'b'], foo=['x', 'y'])
877
878* ``'+'``. Just like ``'*'``, all command-line args present are gathered into a
879 list. Additionally, an error message will be generated if there wasn't at
Éric Araujofde92422011-08-19 01:30:26 +0200880 least one command-line argument present. For example::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000881
882 >>> parser = argparse.ArgumentParser(prog='PROG')
883 >>> parser.add_argument('foo', nargs='+')
884 >>> parser.parse_args('a b'.split())
885 Namespace(foo=['a', 'b'])
886 >>> parser.parse_args(''.split())
887 usage: PROG [-h] foo [foo ...]
888 PROG: error: too few arguments
889
Sandro Tosida8e11a2012-01-19 22:23:00 +0100890* ``argparse.REMAINDER``. All the remaining command-line arguments are gathered
891 into a list. This is commonly useful for command line utilities that dispatch
Éric Araujoc3ef0372012-02-20 01:44:55 +0100892 to other command line utilities::
Sandro Tosi16bd0b42012-01-19 21:59:55 +0100893
894 >>> parser = argparse.ArgumentParser(prog='PROG')
895 >>> parser.add_argument('--foo')
896 >>> parser.add_argument('command')
897 >>> parser.add_argument('args', nargs=argparse.REMAINDER)
Sandro Tosi04676862012-02-19 19:54:00 +0100898 >>> print(parser.parse_args('--foo B cmd --arg1 XX ZZ'.split()))
Sandro Tosida8e11a2012-01-19 22:23:00 +0100899 Namespace(args=['--arg1', 'XX', 'ZZ'], command='cmd', foo='B')
Sandro Tosi16bd0b42012-01-19 21:59:55 +0100900
Éric Araujod9d7bca2011-08-10 04:19:03 +0200901If the ``nargs`` keyword argument is not provided, the number of arguments consumed
Éric Araujofde92422011-08-19 01:30:26 +0200902is determined by the action_. Generally this means a single command-line argument
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000903will be consumed and a single item (not a list) will be produced.
904
905
906const
907^^^^^
908
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300909The ``const`` argument of :meth:`~ArgumentParser.add_argument` is used to hold
910constant values that are not read from the command line but are required for
911the various :class:`ArgumentParser` actions. The two most common uses of it are:
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000912
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300913* When :meth:`~ArgumentParser.add_argument` is called with
914 ``action='store_const'`` or ``action='append_const'``. These actions add the
Éric Araujoc3ef0372012-02-20 01:44:55 +0100915 ``const`` value to one of the attributes of the object returned by
916 :meth:`~ArgumentParser.parse_args`. See the action_ description for examples.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000917
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300918* When :meth:`~ArgumentParser.add_argument` is called with option strings
919 (like ``-f`` or ``--foo``) and ``nargs='?'``. This creates an optional
Éric Araujod9d7bca2011-08-10 04:19:03 +0200920 argument that can be followed by zero or one command-line arguments.
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300921 When parsing the command line, if the option string is encountered with no
Éric Araujofde92422011-08-19 01:30:26 +0200922 command-line argument following it, the value of ``const`` will be assumed instead.
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300923 See the nargs_ description for examples.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000924
Martin Panterb4912b82016-04-09 03:49:48 +0000925With the ``'store_const'`` and ``'append_const'`` actions, the ``const``
926keyword argument must be given. For other actions, is defaults to ``None``.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000927
928
929default
930^^^^^^^
931
932All optional arguments and some positional arguments may be omitted at the
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300933command line. The ``default`` keyword argument of
934:meth:`~ArgumentParser.add_argument`, whose value defaults to ``None``,
Éric Araujofde92422011-08-19 01:30:26 +0200935specifies what value should be used if the command-line argument is not present.
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300936For optional arguments, the ``default`` value is used when the option string
937was not present at the command line::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000938
939 >>> parser = argparse.ArgumentParser()
940 >>> parser.add_argument('--foo', default=42)
941 >>> parser.parse_args('--foo 2'.split())
942 Namespace(foo='2')
943 >>> parser.parse_args(''.split())
944 Namespace(foo=42)
945
Barry Warsaw1dedd0a2012-09-25 10:37:58 -0400946If the ``default`` value is a string, the parser parses the value as if it
947were a command-line argument. In particular, the parser applies any type_
948conversion argument, if provided, before setting the attribute on the
949:class:`Namespace` return value. Otherwise, the parser uses the value as is::
950
951 >>> parser = argparse.ArgumentParser()
952 >>> parser.add_argument('--length', default='10', type=int)
953 >>> parser.add_argument('--width', default=10.5, type=int)
954 >>> parser.parse_args()
955 Namespace(length=10, width=10.5)
956
Éric Araujo543edbd2011-08-19 01:45:12 +0200957For positional arguments with nargs_ equal to ``?`` or ``*``, the ``default`` value
Éric Araujofde92422011-08-19 01:30:26 +0200958is used when no command-line argument was present::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000959
960 >>> parser = argparse.ArgumentParser()
961 >>> parser.add_argument('foo', nargs='?', default=42)
962 >>> parser.parse_args('a'.split())
963 Namespace(foo='a')
964 >>> parser.parse_args(''.split())
965 Namespace(foo=42)
966
967
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000968Providing ``default=argparse.SUPPRESS`` causes no attribute to be added if the
969command-line argument was not present.::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000970
971 >>> parser = argparse.ArgumentParser()
972 >>> parser.add_argument('--foo', default=argparse.SUPPRESS)
973 >>> parser.parse_args([])
974 Namespace()
975 >>> parser.parse_args(['--foo', '1'])
976 Namespace(foo='1')
977
978
979type
980^^^^
981
Éric Araujod9d7bca2011-08-10 04:19:03 +0200982By default, :class:`ArgumentParser` objects read command-line arguments in as simple
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300983strings. However, quite often the command-line string should instead be
984interpreted as another type, like a :class:`float` or :class:`int`. The
985``type`` keyword argument of :meth:`~ArgumentParser.add_argument` allows any
Éric Araujod9d7bca2011-08-10 04:19:03 +0200986necessary type-checking and type conversions to be performed. Common built-in
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300987types and functions can be used directly as the value of the ``type`` argument::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000988
989 >>> parser = argparse.ArgumentParser()
990 >>> parser.add_argument('foo', type=int)
Georg Brandl04536b02011-01-09 09:31:01 +0000991 >>> parser.add_argument('bar', type=open)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000992 >>> parser.parse_args('2 temp.txt'.split())
Georg Brandl04536b02011-01-09 09:31:01 +0000993 Namespace(bar=<_io.TextIOWrapper name='temp.txt' encoding='UTF-8'>, foo=2)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000994
Barry Warsaw1dedd0a2012-09-25 10:37:58 -0400995See the section on the default_ keyword argument for information on when the
996``type`` argument is applied to default arguments.
997
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000998To ease the use of various types of files, the argparse module provides the
Petri Lehtinen74d6c252012-12-15 22:39:32 +0200999factory FileType which takes the ``mode=``, ``bufsize=``, ``encoding=`` and
1000``errors=`` arguments of the :func:`open` function. For example,
1001``FileType('w')`` can be used to create a writable file::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001002
1003 >>> parser = argparse.ArgumentParser()
1004 >>> parser.add_argument('bar', type=argparse.FileType('w'))
1005 >>> parser.parse_args(['out.txt'])
Georg Brandl04536b02011-01-09 09:31:01 +00001006 Namespace(bar=<_io.TextIOWrapper name='out.txt' encoding='UTF-8'>)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001007
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001008``type=`` can take any callable that takes a single string argument and returns
Éric Araujod9d7bca2011-08-10 04:19:03 +02001009the converted value::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001010
1011 >>> def perfect_square(string):
1012 ... value = int(string)
1013 ... sqrt = math.sqrt(value)
1014 ... if sqrt != int(sqrt):
1015 ... msg = "%r is not a perfect square" % string
1016 ... raise argparse.ArgumentTypeError(msg)
1017 ... return value
1018 ...
1019 >>> parser = argparse.ArgumentParser(prog='PROG')
1020 >>> parser.add_argument('foo', type=perfect_square)
1021 >>> parser.parse_args('9'.split())
1022 Namespace(foo=9)
1023 >>> parser.parse_args('7'.split())
1024 usage: PROG [-h] foo
1025 PROG: error: argument foo: '7' is not a perfect square
1026
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001027The choices_ keyword argument may be more convenient for type checkers that
1028simply check against a range of values::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001029
1030 >>> parser = argparse.ArgumentParser(prog='PROG')
Fred Drake44623062011-03-03 05:27:17 +00001031 >>> parser.add_argument('foo', type=int, choices=range(5, 10))
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001032 >>> parser.parse_args('7'.split())
1033 Namespace(foo=7)
1034 >>> parser.parse_args('11'.split())
1035 usage: PROG [-h] {5,6,7,8,9}
1036 PROG: error: argument foo: invalid choice: 11 (choose from 5, 6, 7, 8, 9)
1037
1038See the choices_ section for more details.
1039
1040
1041choices
1042^^^^^^^
1043
Éric Araujod9d7bca2011-08-10 04:19:03 +02001044Some command-line arguments should be selected from a restricted set of values.
Chris Jerdonek174ef672013-01-11 19:26:44 -08001045These can be handled by passing a container object as the *choices* keyword
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001046argument to :meth:`~ArgumentParser.add_argument`. When the command line is
Chris Jerdonek174ef672013-01-11 19:26:44 -08001047parsed, argument values will be checked, and an error message will be displayed
1048if the argument was not one of the acceptable values::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001049
Chris Jerdonek174ef672013-01-11 19:26:44 -08001050 >>> parser = argparse.ArgumentParser(prog='game.py')
1051 >>> parser.add_argument('move', choices=['rock', 'paper', 'scissors'])
1052 >>> parser.parse_args(['rock'])
1053 Namespace(move='rock')
1054 >>> parser.parse_args(['fire'])
1055 usage: game.py [-h] {rock,paper,scissors}
1056 game.py: error: argument move: invalid choice: 'fire' (choose from 'rock',
1057 'paper', 'scissors')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001058
Chris Jerdonek174ef672013-01-11 19:26:44 -08001059Note that inclusion in the *choices* container is checked after any type_
1060conversions have been performed, so the type of the objects in the *choices*
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001061container should match the type_ specified::
1062
Chris Jerdonek174ef672013-01-11 19:26:44 -08001063 >>> parser = argparse.ArgumentParser(prog='doors.py')
1064 >>> parser.add_argument('door', type=int, choices=range(1, 4))
1065 >>> print(parser.parse_args(['3']))
1066 Namespace(door=3)
1067 >>> parser.parse_args(['4'])
1068 usage: doors.py [-h] {1,2,3}
1069 doors.py: error: argument door: invalid choice: 4 (choose from 1, 2, 3)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001070
Chris Jerdonek174ef672013-01-11 19:26:44 -08001071Any object that supports the ``in`` operator can be passed as the *choices*
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001072value, so :class:`dict` objects, :class:`set` objects, custom containers,
1073etc. are all supported.
1074
1075
1076required
1077^^^^^^^^
1078
Ezio Melotti0ee9c1b2011-04-21 16:12:17 +03001079In general, the :mod:`argparse` module assumes that flags like ``-f`` and ``--bar``
Georg Brandl69518bc2011-04-16 16:44:54 +02001080indicate *optional* arguments, which can always be omitted at the command line.
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001081To make an option *required*, ``True`` can be specified for the ``required=``
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001082keyword argument to :meth:`~ArgumentParser.add_argument`::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001083
1084 >>> parser = argparse.ArgumentParser()
1085 >>> parser.add_argument('--foo', required=True)
1086 >>> parser.parse_args(['--foo', 'BAR'])
1087 Namespace(foo='BAR')
1088 >>> parser.parse_args([])
1089 usage: argparse.py [-h] [--foo FOO]
1090 argparse.py: error: option --foo is required
1091
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001092As the example shows, if an option is marked as ``required``,
1093:meth:`~ArgumentParser.parse_args` will report an error if that option is not
1094present at the command line.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001095
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001096.. note::
1097
1098 Required options are generally considered bad form because users expect
1099 *options* to be *optional*, and thus they should be avoided when possible.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001100
1101
1102help
1103^^^^
1104
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001105The ``help`` value is a string containing a brief description of the argument.
1106When a user requests help (usually by using ``-h`` or ``--help`` at the
Georg Brandl69518bc2011-04-16 16:44:54 +02001107command line), these ``help`` descriptions will be displayed with each
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001108argument::
1109
1110 >>> parser = argparse.ArgumentParser(prog='frobble')
1111 >>> parser.add_argument('--foo', action='store_true',
1112 ... help='foo the bars before frobbling')
1113 >>> parser.add_argument('bar', nargs='+',
1114 ... help='one of the bars to be frobbled')
1115 >>> parser.parse_args('-h'.split())
1116 usage: frobble [-h] [--foo] bar [bar ...]
1117
1118 positional arguments:
1119 bar one of the bars to be frobbled
1120
1121 optional arguments:
1122 -h, --help show this help message and exit
1123 --foo foo the bars before frobbling
1124
1125The ``help`` strings can include various format specifiers to avoid repetition
1126of things like the program name or the argument default_. The available
1127specifiers include the program name, ``%(prog)s`` and most keyword arguments to
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001128:meth:`~ArgumentParser.add_argument`, e.g. ``%(default)s``, ``%(type)s``, etc.::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001129
1130 >>> parser = argparse.ArgumentParser(prog='frobble')
1131 >>> parser.add_argument('bar', nargs='?', type=int, default=42,
1132 ... help='the bar to %(prog)s (default: %(default)s)')
1133 >>> parser.print_help()
1134 usage: frobble [-h] [bar]
1135
1136 positional arguments:
1137 bar the bar to frobble (default: 42)
1138
1139 optional arguments:
1140 -h, --help show this help message and exit
1141
Senthil Kumaranf21804a2012-06-26 14:17:19 +08001142As the help string supports %-formatting, if you want a literal ``%`` to appear
1143in the help string, you must escape it as ``%%``.
1144
Sandro Tosiea320ab2012-01-03 18:37:03 +01001145:mod:`argparse` supports silencing the help entry for certain options, by
1146setting the ``help`` value to ``argparse.SUPPRESS``::
1147
1148 >>> parser = argparse.ArgumentParser(prog='frobble')
1149 >>> parser.add_argument('--foo', help=argparse.SUPPRESS)
1150 >>> parser.print_help()
1151 usage: frobble [-h]
1152
1153 optional arguments:
1154 -h, --help show this help message and exit
1155
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001156
1157metavar
1158^^^^^^^
1159
Sandro Tosi32587fb2013-01-11 10:49:00 +01001160When :class:`ArgumentParser` generates help messages, it needs some way to refer
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001161to each expected argument. By default, ArgumentParser objects use the dest_
1162value as the "name" of each object. By default, for positional argument
1163actions, the dest_ value is used directly, and for optional argument actions,
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001164the dest_ value is uppercased. So, a single positional argument with
Eli Benderskya7795db2011-11-11 10:57:01 +02001165``dest='bar'`` will be referred to as ``bar``. A single
Éric Araujofde92422011-08-19 01:30:26 +02001166optional argument ``--foo`` that should be followed by a single command-line argument
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001167will be referred to as ``FOO``. An example::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001168
1169 >>> parser = argparse.ArgumentParser()
1170 >>> parser.add_argument('--foo')
1171 >>> parser.add_argument('bar')
1172 >>> parser.parse_args('X --foo Y'.split())
1173 Namespace(bar='X', foo='Y')
1174 >>> parser.print_help()
1175 usage: [-h] [--foo FOO] bar
1176
1177 positional arguments:
1178 bar
1179
1180 optional arguments:
1181 -h, --help show this help message and exit
1182 --foo FOO
1183
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001184An alternative name can be specified with ``metavar``::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001185
1186 >>> parser = argparse.ArgumentParser()
1187 >>> parser.add_argument('--foo', metavar='YYY')
1188 >>> parser.add_argument('bar', metavar='XXX')
1189 >>> parser.parse_args('X --foo Y'.split())
1190 Namespace(bar='X', foo='Y')
1191 >>> parser.print_help()
1192 usage: [-h] [--foo YYY] XXX
1193
1194 positional arguments:
1195 XXX
1196
1197 optional arguments:
1198 -h, --help show this help message and exit
1199 --foo YYY
1200
1201Note that ``metavar`` only changes the *displayed* name - the name of the
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001202attribute on the :meth:`~ArgumentParser.parse_args` object is still determined
1203by the dest_ value.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001204
1205Different values of ``nargs`` may cause the metavar to be used multiple times.
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001206Providing a tuple to ``metavar`` specifies a different display for each of the
1207arguments::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001208
1209 >>> parser = argparse.ArgumentParser(prog='PROG')
1210 >>> parser.add_argument('-x', nargs=2)
1211 >>> parser.add_argument('--foo', nargs=2, metavar=('bar', 'baz'))
1212 >>> parser.print_help()
1213 usage: PROG [-h] [-x X X] [--foo bar baz]
1214
1215 optional arguments:
1216 -h, --help show this help message and exit
1217 -x X X
1218 --foo bar baz
1219
1220
1221dest
1222^^^^
1223
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001224Most :class:`ArgumentParser` actions add some value as an attribute of the
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001225object returned by :meth:`~ArgumentParser.parse_args`. The name of this
1226attribute is determined by the ``dest`` keyword argument of
1227:meth:`~ArgumentParser.add_argument`. For positional argument actions,
1228``dest`` is normally supplied as the first argument to
1229:meth:`~ArgumentParser.add_argument`::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001230
1231 >>> parser = argparse.ArgumentParser()
1232 >>> parser.add_argument('bar')
1233 >>> parser.parse_args('XXX'.split())
1234 Namespace(bar='XXX')
1235
1236For optional argument actions, the value of ``dest`` is normally inferred from
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001237the option strings. :class:`ArgumentParser` generates the value of ``dest`` by
Éric Araujo543edbd2011-08-19 01:45:12 +02001238taking the first long option string and stripping away the initial ``--``
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001239string. If no long option strings were supplied, ``dest`` will be derived from
Éric Araujo543edbd2011-08-19 01:45:12 +02001240the first short option string by stripping the initial ``-`` character. Any
1241internal ``-`` characters will be converted to ``_`` characters to make sure
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001242the string is a valid attribute name. The examples below illustrate this
1243behavior::
1244
1245 >>> parser = argparse.ArgumentParser()
1246 >>> parser.add_argument('-f', '--foo-bar', '--foo')
1247 >>> parser.add_argument('-x', '-y')
1248 >>> parser.parse_args('-f 1 -x 2'.split())
1249 Namespace(foo_bar='1', x='2')
1250 >>> parser.parse_args('--foo 1 -y 2'.split())
1251 Namespace(foo_bar='1', x='2')
1252
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001253``dest`` allows a custom attribute name to be provided::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001254
1255 >>> parser = argparse.ArgumentParser()
1256 >>> parser.add_argument('--foo', dest='bar')
1257 >>> parser.parse_args('--foo XXX'.split())
1258 Namespace(bar='XXX')
1259
Jason R. Coombsf28cf7a2011-12-13 23:36:45 -05001260Action classes
1261^^^^^^^^^^^^^^
1262
Jason R. Coombseb0ef412014-07-20 10:52:46 -04001263Action classes implement the Action API, a callable which returns a callable
1264which processes arguments from the command-line. Any object which follows
1265this API may be passed as the ``action`` parameter to
Raymond Hettingerc0de59b2014-08-03 23:44:30 -07001266:meth:`add_argument`.
Jason R. Coombseb0ef412014-07-20 10:52:46 -04001267
Terry Jan Reedyee558262014-08-23 22:21:47 -04001268.. class:: Action(option_strings, dest, nargs=None, const=None, default=None, \
1269 type=None, choices=None, required=False, help=None, \
Jason R. Coombsf28cf7a2011-12-13 23:36:45 -05001270 metavar=None)
1271
1272Action objects are used by an ArgumentParser to represent the information
1273needed to parse a single argument from one or more strings from the
Jason R. Coombseb0ef412014-07-20 10:52:46 -04001274command line. The Action class must accept the two positional arguments
Raymond Hettingerc0de59b2014-08-03 23:44:30 -07001275plus any keyword arguments passed to :meth:`ArgumentParser.add_argument`
Jason R. Coombseb0ef412014-07-20 10:52:46 -04001276except for the ``action`` itself.
Jason R. Coombsf28cf7a2011-12-13 23:36:45 -05001277
Jason R. Coombseb0ef412014-07-20 10:52:46 -04001278Instances of Action (or return value of any callable to the ``action``
1279parameter) should have attributes "dest", "option_strings", "default", "type",
1280"required", "help", etc. defined. The easiest way to ensure these attributes
1281are defined is to call ``Action.__init__``.
Jason R. Coombsf28cf7a2011-12-13 23:36:45 -05001282
Jason R. Coombseb0ef412014-07-20 10:52:46 -04001283Action instances should be callable, so subclasses must override the
1284``__call__`` method, which should accept four parameters:
Jason R. Coombsf28cf7a2011-12-13 23:36:45 -05001285
1286* ``parser`` - The ArgumentParser object which contains this action.
1287
1288* ``namespace`` - The :class:`Namespace` object that will be returned by
1289 :meth:`~ArgumentParser.parse_args`. Most actions add an attribute to this
1290 object using :func:`setattr`.
1291
1292* ``values`` - The associated command-line arguments, with any type conversions
1293 applied. Type conversions are specified with the type_ keyword argument to
1294 :meth:`~ArgumentParser.add_argument`.
1295
1296* ``option_string`` - The option string that was used to invoke this action.
1297 The ``option_string`` argument is optional, and will be absent if the action
1298 is associated with a positional argument.
1299
Jason R. Coombseb0ef412014-07-20 10:52:46 -04001300The ``__call__`` method may perform arbitrary actions, but will typically set
1301attributes on the ``namespace`` based on ``dest`` and ``values``.
1302
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001303
1304The parse_args() method
1305-----------------------
1306
Georg Brandle0bf91d2010-10-17 10:34:28 +00001307.. method:: ArgumentParser.parse_args(args=None, namespace=None)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001308
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001309 Convert argument strings to objects and assign them as attributes of the
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001310 namespace. Return the populated namespace.
1311
1312 Previous calls to :meth:`add_argument` determine exactly what objects are
1313 created and how they are assigned. See the documentation for
1314 :meth:`add_argument` for details.
1315
Éric Araujofde92422011-08-19 01:30:26 +02001316 By default, the argument strings are taken from :data:`sys.argv`, and a new empty
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001317 :class:`Namespace` object is created for the attributes.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001318
Georg Brandle0bf91d2010-10-17 10:34:28 +00001319
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001320Option value syntax
1321^^^^^^^^^^^^^^^^^^^
1322
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001323The :meth:`~ArgumentParser.parse_args` method supports several ways of
1324specifying the value of an option (if it takes one). In the simplest case, the
1325option and its value are passed as two separate arguments::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001326
1327 >>> parser = argparse.ArgumentParser(prog='PROG')
1328 >>> parser.add_argument('-x')
1329 >>> parser.add_argument('--foo')
1330 >>> parser.parse_args('-x X'.split())
1331 Namespace(foo=None, x='X')
1332 >>> parser.parse_args('--foo FOO'.split())
1333 Namespace(foo='FOO', x=None)
1334
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001335For long options (options with names longer than a single character), the option
Georg Brandl69518bc2011-04-16 16:44:54 +02001336and value can also be passed as a single command-line argument, using ``=`` to
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001337separate them::
1338
1339 >>> parser.parse_args('--foo=FOO'.split())
1340 Namespace(foo='FOO', x=None)
1341
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001342For short options (options only one character long), the option and its value
1343can be concatenated::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001344
1345 >>> parser.parse_args('-xX'.split())
1346 Namespace(foo=None, x='X')
1347
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001348Several short options can be joined together, using only a single ``-`` prefix,
1349as long as only the last option (or none of them) requires a value::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001350
1351 >>> parser = argparse.ArgumentParser(prog='PROG')
1352 >>> parser.add_argument('-x', action='store_true')
1353 >>> parser.add_argument('-y', action='store_true')
1354 >>> parser.add_argument('-z')
1355 >>> parser.parse_args('-xyzZ'.split())
1356 Namespace(x=True, y=True, z='Z')
1357
1358
1359Invalid arguments
1360^^^^^^^^^^^^^^^^^
1361
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001362While parsing the command line, :meth:`~ArgumentParser.parse_args` checks for a
1363variety of errors, including ambiguous options, invalid types, invalid options,
1364wrong number of positional arguments, etc. When it encounters such an error,
1365it exits and prints the error along with a usage message::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001366
1367 >>> parser = argparse.ArgumentParser(prog='PROG')
1368 >>> parser.add_argument('--foo', type=int)
1369 >>> parser.add_argument('bar', nargs='?')
1370
1371 >>> # invalid type
1372 >>> parser.parse_args(['--foo', 'spam'])
1373 usage: PROG [-h] [--foo FOO] [bar]
1374 PROG: error: argument --foo: invalid int value: 'spam'
1375
1376 >>> # invalid option
1377 >>> parser.parse_args(['--bar'])
1378 usage: PROG [-h] [--foo FOO] [bar]
1379 PROG: error: no such option: --bar
1380
1381 >>> # wrong number of arguments
1382 >>> parser.parse_args(['spam', 'badger'])
1383 usage: PROG [-h] [--foo FOO] [bar]
1384 PROG: error: extra arguments found: badger
1385
1386
Éric Araujo543edbd2011-08-19 01:45:12 +02001387Arguments containing ``-``
1388^^^^^^^^^^^^^^^^^^^^^^^^^^
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001389
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001390The :meth:`~ArgumentParser.parse_args` method attempts to give errors whenever
1391the user has clearly made a mistake, but some situations are inherently
Éric Araujo543edbd2011-08-19 01:45:12 +02001392ambiguous. For example, the command-line argument ``-1`` could either be an
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001393attempt to specify an option or an attempt to provide a positional argument.
1394The :meth:`~ArgumentParser.parse_args` method is cautious here: positional
Éric Araujo543edbd2011-08-19 01:45:12 +02001395arguments may only begin with ``-`` if they look like negative numbers and
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001396there are no options in the parser that look like negative numbers::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001397
1398 >>> parser = argparse.ArgumentParser(prog='PROG')
1399 >>> parser.add_argument('-x')
1400 >>> parser.add_argument('foo', nargs='?')
1401
1402 >>> # no negative number options, so -1 is a positional argument
1403 >>> parser.parse_args(['-x', '-1'])
1404 Namespace(foo=None, x='-1')
1405
1406 >>> # no negative number options, so -1 and -5 are positional arguments
1407 >>> parser.parse_args(['-x', '-1', '-5'])
1408 Namespace(foo='-5', x='-1')
1409
1410 >>> parser = argparse.ArgumentParser(prog='PROG')
1411 >>> parser.add_argument('-1', dest='one')
1412 >>> parser.add_argument('foo', nargs='?')
1413
1414 >>> # negative number options present, so -1 is an option
1415 >>> parser.parse_args(['-1', 'X'])
1416 Namespace(foo=None, one='X')
1417
1418 >>> # negative number options present, so -2 is an option
1419 >>> parser.parse_args(['-2'])
1420 usage: PROG [-h] [-1 ONE] [foo]
1421 PROG: error: no such option: -2
1422
1423 >>> # negative number options present, so both -1s are options
1424 >>> parser.parse_args(['-1', '-1'])
1425 usage: PROG [-h] [-1 ONE] [foo]
1426 PROG: error: argument -1: expected one argument
1427
Éric Araujo543edbd2011-08-19 01:45:12 +02001428If you have positional arguments that must begin with ``-`` and don't look
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001429like negative numbers, you can insert the pseudo-argument ``'--'`` which tells
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001430:meth:`~ArgumentParser.parse_args` that everything after that is a positional
1431argument::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001432
1433 >>> parser.parse_args(['--', '-f'])
1434 Namespace(foo='-f', one=None)
1435
Eli Benderskyf3114532013-12-02 05:49:54 -08001436.. _prefix-matching:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001437
Eli Benderskyf3114532013-12-02 05:49:54 -08001438Argument abbreviations (prefix matching)
1439^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001440
Berker Peksag8089cd62015-02-14 01:39:17 +02001441The :meth:`~ArgumentParser.parse_args` method :ref:`by default <allow_abbrev>`
1442allows long options to be abbreviated to a prefix, if the abbreviation is
1443unambiguous (the prefix matches a unique option)::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001444
1445 >>> parser = argparse.ArgumentParser(prog='PROG')
1446 >>> parser.add_argument('-bacon')
1447 >>> parser.add_argument('-badger')
1448 >>> parser.parse_args('-bac MMM'.split())
1449 Namespace(bacon='MMM', badger=None)
1450 >>> parser.parse_args('-bad WOOD'.split())
1451 Namespace(bacon=None, badger='WOOD')
1452 >>> parser.parse_args('-ba BA'.split())
1453 usage: PROG [-h] [-bacon BACON] [-badger BADGER]
1454 PROG: error: ambiguous option: -ba could match -badger, -bacon
1455
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001456An error is produced for arguments that could produce more than one options.
Berker Peksag8089cd62015-02-14 01:39:17 +02001457This feature can be disabled by setting :ref:`allow_abbrev` to ``False``.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001458
1459
1460Beyond ``sys.argv``
1461^^^^^^^^^^^^^^^^^^^
1462
Éric Araujod9d7bca2011-08-10 04:19:03 +02001463Sometimes it may be useful to have an ArgumentParser parse arguments other than those
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001464of :data:`sys.argv`. This can be accomplished by passing a list of strings to
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001465:meth:`~ArgumentParser.parse_args`. This is useful for testing at the
1466interactive prompt::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001467
1468 >>> parser = argparse.ArgumentParser()
1469 >>> parser.add_argument(
Fred Drake44623062011-03-03 05:27:17 +00001470 ... 'integers', metavar='int', type=int, choices=range(10),
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001471 ... nargs='+', help='an integer in the range 0..9')
1472 >>> parser.add_argument(
1473 ... '--sum', dest='accumulate', action='store_const', const=sum,
1474 ... default=max, help='sum the integers (default: find the max)')
1475 >>> parser.parse_args(['1', '2', '3', '4'])
1476 Namespace(accumulate=<built-in function max>, integers=[1, 2, 3, 4])
1477 >>> parser.parse_args('1 2 3 4 --sum'.split())
1478 Namespace(accumulate=<built-in function sum>, integers=[1, 2, 3, 4])
1479
1480
Steven Bethardd8f2d502011-03-26 19:50:06 +01001481The Namespace object
1482^^^^^^^^^^^^^^^^^^^^
1483
Éric Araujo63b18a42011-07-29 17:59:17 +02001484.. class:: Namespace
1485
1486 Simple class used by default by :meth:`~ArgumentParser.parse_args` to create
1487 an object holding attributes and return it.
1488
1489This class is deliberately simple, just an :class:`object` subclass with a
1490readable string representation. If you prefer to have dict-like view of the
1491attributes, you can use the standard Python idiom, :func:`vars`::
Steven Bethardd8f2d502011-03-26 19:50:06 +01001492
1493 >>> parser = argparse.ArgumentParser()
1494 >>> parser.add_argument('--foo')
1495 >>> args = parser.parse_args(['--foo', 'BAR'])
1496 >>> vars(args)
1497 {'foo': 'BAR'}
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001498
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001499It may also be useful to have an :class:`ArgumentParser` assign attributes to an
Steven Bethardd8f2d502011-03-26 19:50:06 +01001500already existing object, rather than a new :class:`Namespace` object. This can
1501be achieved by specifying the ``namespace=`` keyword argument::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001502
Éric Araujo28053fb2010-11-22 03:09:19 +00001503 >>> class C:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001504 ... pass
1505 ...
1506 >>> c = C()
1507 >>> parser = argparse.ArgumentParser()
1508 >>> parser.add_argument('--foo')
1509 >>> parser.parse_args(args=['--foo', 'BAR'], namespace=c)
1510 >>> c.foo
1511 'BAR'
1512
1513
1514Other utilities
1515---------------
1516
1517Sub-commands
1518^^^^^^^^^^^^
1519
Georg Brandlfc9a1132013-10-06 18:51:39 +02001520.. method:: ArgumentParser.add_subparsers([title], [description], [prog], \
1521 [parser_class], [action], \
1522 [option_string], [dest], [help], \
1523 [metavar])
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001524
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001525 Many programs split up their functionality into a number of sub-commands,
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001526 for example, the ``svn`` program can invoke sub-commands like ``svn
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001527 checkout``, ``svn update``, and ``svn commit``. Splitting up functionality
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001528 this way can be a particularly good idea when a program performs several
1529 different functions which require different kinds of command-line arguments.
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001530 :class:`ArgumentParser` supports the creation of such sub-commands with the
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001531 :meth:`add_subparsers` method. The :meth:`add_subparsers` method is normally
Ezio Melotti52336f02012-12-28 01:59:24 +02001532 called with no arguments and returns a special action object. This object
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001533 has a single method, :meth:`~ArgumentParser.add_parser`, which takes a
1534 command name and any :class:`ArgumentParser` constructor arguments, and
1535 returns an :class:`ArgumentParser` object that can be modified as usual.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001536
Georg Brandlfc9a1132013-10-06 18:51:39 +02001537 Description of parameters:
1538
1539 * title - title for the sub-parser group in help output; by default
1540 "subcommands" if description is provided, otherwise uses title for
1541 positional arguments
1542
1543 * description - description for the sub-parser group in help output, by
1544 default None
1545
1546 * prog - usage information that will be displayed with sub-command help,
1547 by default the name of the program and any positional arguments before the
1548 subparser argument
1549
1550 * parser_class - class which will be used to create sub-parser instances, by
1551 default the class of the current parser (e.g. ArgumentParser)
1552
Berker Peksag5a494f62015-01-20 06:45:53 +02001553 * action_ - the basic type of action to be taken when this argument is
1554 encountered at the command line
1555
1556 * dest_ - name of the attribute under which sub-command name will be
Georg Brandlfc9a1132013-10-06 18:51:39 +02001557 stored; by default None and no value is stored
1558
Berker Peksag5a494f62015-01-20 06:45:53 +02001559 * help_ - help for sub-parser group in help output, by default None
Georg Brandlfc9a1132013-10-06 18:51:39 +02001560
Berker Peksag5a494f62015-01-20 06:45:53 +02001561 * metavar_ - string presenting available sub-commands in help; by default it
Georg Brandlfc9a1132013-10-06 18:51:39 +02001562 is None and presents sub-commands in form {cmd1, cmd2, ..}
1563
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001564 Some example usage::
1565
1566 >>> # create the top-level parser
1567 >>> parser = argparse.ArgumentParser(prog='PROG')
1568 >>> parser.add_argument('--foo', action='store_true', help='foo help')
1569 >>> subparsers = parser.add_subparsers(help='sub-command help')
1570 >>>
1571 >>> # create the parser for the "a" command
1572 >>> parser_a = subparsers.add_parser('a', help='a help')
1573 >>> parser_a.add_argument('bar', type=int, help='bar help')
1574 >>>
1575 >>> # create the parser for the "b" command
1576 >>> parser_b = subparsers.add_parser('b', help='b help')
1577 >>> parser_b.add_argument('--baz', choices='XYZ', help='baz help')
1578 >>>
Éric Araujofde92422011-08-19 01:30:26 +02001579 >>> # parse some argument lists
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001580 >>> parser.parse_args(['a', '12'])
1581 Namespace(bar=12, foo=False)
1582 >>> parser.parse_args(['--foo', 'b', '--baz', 'Z'])
1583 Namespace(baz='Z', foo=True)
1584
1585 Note that the object returned by :meth:`parse_args` will only contain
1586 attributes for the main parser and the subparser that was selected by the
1587 command line (and not any other subparsers). So in the example above, when
Éric Araujo543edbd2011-08-19 01:45:12 +02001588 the ``a`` command is specified, only the ``foo`` and ``bar`` attributes are
1589 present, and when the ``b`` command is specified, only the ``foo`` and
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001590 ``baz`` attributes are present.
1591
1592 Similarly, when a help message is requested from a subparser, only the help
1593 for that particular parser will be printed. The help message will not
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001594 include parent parser or sibling parser messages. (A help message for each
1595 subparser command, however, can be given by supplying the ``help=`` argument
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001596 to :meth:`add_parser` as above.)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001597
1598 ::
1599
1600 >>> parser.parse_args(['--help'])
1601 usage: PROG [-h] [--foo] {a,b} ...
1602
1603 positional arguments:
1604 {a,b} sub-command help
Ezio Melotti7128e072013-01-12 10:39:45 +02001605 a a help
1606 b b help
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001607
1608 optional arguments:
1609 -h, --help show this help message and exit
1610 --foo foo help
1611
1612 >>> parser.parse_args(['a', '--help'])
1613 usage: PROG a [-h] bar
1614
1615 positional arguments:
1616 bar bar help
1617
1618 optional arguments:
1619 -h, --help show this help message and exit
1620
1621 >>> parser.parse_args(['b', '--help'])
1622 usage: PROG b [-h] [--baz {X,Y,Z}]
1623
1624 optional arguments:
1625 -h, --help show this help message and exit
1626 --baz {X,Y,Z} baz help
1627
1628 The :meth:`add_subparsers` method also supports ``title`` and ``description``
1629 keyword arguments. When either is present, the subparser's commands will
1630 appear in their own group in the help output. For example::
1631
1632 >>> parser = argparse.ArgumentParser()
1633 >>> subparsers = parser.add_subparsers(title='subcommands',
1634 ... description='valid subcommands',
1635 ... help='additional help')
1636 >>> subparsers.add_parser('foo')
1637 >>> subparsers.add_parser('bar')
1638 >>> parser.parse_args(['-h'])
1639 usage: [-h] {foo,bar} ...
1640
1641 optional arguments:
1642 -h, --help show this help message and exit
1643
1644 subcommands:
1645 valid subcommands
1646
1647 {foo,bar} additional help
1648
Steven Bethardfd311a72010-12-18 11:19:23 +00001649 Furthermore, ``add_parser`` supports an additional ``aliases`` argument,
1650 which allows multiple strings to refer to the same subparser. This example,
1651 like ``svn``, aliases ``co`` as a shorthand for ``checkout``::
1652
1653 >>> parser = argparse.ArgumentParser()
1654 >>> subparsers = parser.add_subparsers()
1655 >>> checkout = subparsers.add_parser('checkout', aliases=['co'])
1656 >>> checkout.add_argument('foo')
1657 >>> parser.parse_args(['co', 'bar'])
1658 Namespace(foo='bar')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001659
1660 One particularly effective way of handling sub-commands is to combine the use
1661 of the :meth:`add_subparsers` method with calls to :meth:`set_defaults` so
1662 that each subparser knows which Python function it should execute. For
1663 example::
1664
1665 >>> # sub-command functions
1666 >>> def foo(args):
Benjamin Petersonb2deb112010-03-03 02:09:18 +00001667 ... print(args.x * args.y)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001668 ...
1669 >>> def bar(args):
Benjamin Petersonb2deb112010-03-03 02:09:18 +00001670 ... print('((%s))' % args.z)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001671 ...
1672 >>> # create the top-level parser
1673 >>> parser = argparse.ArgumentParser()
1674 >>> subparsers = parser.add_subparsers()
1675 >>>
1676 >>> # create the parser for the "foo" command
1677 >>> parser_foo = subparsers.add_parser('foo')
1678 >>> parser_foo.add_argument('-x', type=int, default=1)
1679 >>> parser_foo.add_argument('y', type=float)
1680 >>> parser_foo.set_defaults(func=foo)
1681 >>>
1682 >>> # create the parser for the "bar" command
1683 >>> parser_bar = subparsers.add_parser('bar')
1684 >>> parser_bar.add_argument('z')
1685 >>> parser_bar.set_defaults(func=bar)
1686 >>>
1687 >>> # parse the args and call whatever function was selected
1688 >>> args = parser.parse_args('foo 1 -x 2'.split())
1689 >>> args.func(args)
1690 2.0
1691 >>>
1692 >>> # parse the args and call whatever function was selected
1693 >>> args = parser.parse_args('bar XYZYX'.split())
1694 >>> args.func(args)
1695 ((XYZYX))
1696
Steven Bethardfd311a72010-12-18 11:19:23 +00001697 This way, you can let :meth:`parse_args` do the job of calling the
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001698 appropriate function after argument parsing is complete. Associating
1699 functions with actions like this is typically the easiest way to handle the
1700 different actions for each of your subparsers. However, if it is necessary
1701 to check the name of the subparser that was invoked, the ``dest`` keyword
1702 argument to the :meth:`add_subparsers` call will work::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001703
1704 >>> parser = argparse.ArgumentParser()
1705 >>> subparsers = parser.add_subparsers(dest='subparser_name')
1706 >>> subparser1 = subparsers.add_parser('1')
1707 >>> subparser1.add_argument('-x')
1708 >>> subparser2 = subparsers.add_parser('2')
1709 >>> subparser2.add_argument('y')
1710 >>> parser.parse_args(['2', 'frobble'])
1711 Namespace(subparser_name='2', y='frobble')
1712
1713
1714FileType objects
1715^^^^^^^^^^^^^^^^
1716
Petri Lehtinen74d6c252012-12-15 22:39:32 +02001717.. class:: FileType(mode='r', bufsize=-1, encoding=None, errors=None)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001718
1719 The :class:`FileType` factory creates objects that can be passed to the type
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001720 argument of :meth:`ArgumentParser.add_argument`. Arguments that have
Petri Lehtinen74d6c252012-12-15 22:39:32 +02001721 :class:`FileType` objects as their type will open command-line arguments as
1722 files with the requested modes, buffer sizes, encodings and error handling
1723 (see the :func:`open` function for more details)::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001724
Éric Araujoc3ef0372012-02-20 01:44:55 +01001725 >>> parser = argparse.ArgumentParser()
Petri Lehtinen74d6c252012-12-15 22:39:32 +02001726 >>> parser.add_argument('--raw', type=argparse.FileType('wb', 0))
1727 >>> parser.add_argument('out', type=argparse.FileType('w', encoding='UTF-8'))
1728 >>> parser.parse_args(['--raw', 'raw.dat', 'file.txt'])
1729 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 +00001730
1731 FileType objects understand the pseudo-argument ``'-'`` and automatically
1732 convert this into ``sys.stdin`` for readable :class:`FileType` objects and
Éric Araujoc3ef0372012-02-20 01:44:55 +01001733 ``sys.stdout`` for writable :class:`FileType` objects::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001734
Éric Araujoc3ef0372012-02-20 01:44:55 +01001735 >>> parser = argparse.ArgumentParser()
1736 >>> parser.add_argument('infile', type=argparse.FileType('r'))
1737 >>> parser.parse_args(['-'])
1738 Namespace(infile=<_io.TextIOWrapper name='<stdin>' encoding='UTF-8'>)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001739
R David Murrayfced3ec2013-12-31 11:18:01 -05001740 .. versionadded:: 3.4
1741 The *encodings* and *errors* keyword arguments.
1742
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001743
1744Argument groups
1745^^^^^^^^^^^^^^^
1746
Georg Brandle0bf91d2010-10-17 10:34:28 +00001747.. method:: ArgumentParser.add_argument_group(title=None, description=None)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001748
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001749 By default, :class:`ArgumentParser` groups command-line arguments into
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001750 "positional arguments" and "optional arguments" when displaying help
1751 messages. When there is a better conceptual grouping of arguments than this
1752 default one, appropriate groups can be created using the
1753 :meth:`add_argument_group` method::
1754
1755 >>> parser = argparse.ArgumentParser(prog='PROG', add_help=False)
1756 >>> group = parser.add_argument_group('group')
1757 >>> group.add_argument('--foo', help='foo help')
1758 >>> group.add_argument('bar', help='bar help')
1759 >>> parser.print_help()
1760 usage: PROG [--foo FOO] bar
1761
1762 group:
1763 bar bar help
1764 --foo FOO foo help
1765
1766 The :meth:`add_argument_group` method returns an argument group object which
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001767 has an :meth:`~ArgumentParser.add_argument` method just like a regular
1768 :class:`ArgumentParser`. When an argument is added to the group, the parser
1769 treats it just like a normal argument, but displays the argument in a
1770 separate group for help messages. The :meth:`add_argument_group` method
Georg Brandle0bf91d2010-10-17 10:34:28 +00001771 accepts *title* and *description* arguments which can be used to
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001772 customize this display::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001773
1774 >>> parser = argparse.ArgumentParser(prog='PROG', add_help=False)
1775 >>> group1 = parser.add_argument_group('group1', 'group1 description')
1776 >>> group1.add_argument('foo', help='foo help')
1777 >>> group2 = parser.add_argument_group('group2', 'group2 description')
1778 >>> group2.add_argument('--bar', help='bar help')
1779 >>> parser.print_help()
1780 usage: PROG [--bar BAR] foo
1781
1782 group1:
1783 group1 description
1784
1785 foo foo help
1786
1787 group2:
1788 group2 description
1789
1790 --bar BAR bar help
1791
Sandro Tosi99e7d072012-03-26 19:36:23 +02001792 Note that any arguments not in your user-defined groups will end up back
1793 in the usual "positional arguments" and "optional arguments" sections.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001794
1795
1796Mutual exclusion
1797^^^^^^^^^^^^^^^^
1798
Georg Brandled86ff82013-10-06 13:09:59 +02001799.. method:: ArgumentParser.add_mutually_exclusive_group(required=False)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001800
Ezio Melotti0ee9c1b2011-04-21 16:12:17 +03001801 Create a mutually exclusive group. :mod:`argparse` will make sure that only
1802 one of the arguments in the mutually exclusive group was present on the
1803 command line::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001804
1805 >>> parser = argparse.ArgumentParser(prog='PROG')
1806 >>> group = parser.add_mutually_exclusive_group()
1807 >>> group.add_argument('--foo', action='store_true')
1808 >>> group.add_argument('--bar', action='store_false')
1809 >>> parser.parse_args(['--foo'])
1810 Namespace(bar=True, foo=True)
1811 >>> parser.parse_args(['--bar'])
1812 Namespace(bar=False, foo=False)
1813 >>> parser.parse_args(['--foo', '--bar'])
1814 usage: PROG [-h] [--foo | --bar]
1815 PROG: error: argument --bar: not allowed with argument --foo
1816
Georg Brandle0bf91d2010-10-17 10:34:28 +00001817 The :meth:`add_mutually_exclusive_group` method also accepts a *required*
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001818 argument, to indicate that at least one of the mutually exclusive arguments
1819 is required::
1820
1821 >>> parser = argparse.ArgumentParser(prog='PROG')
1822 >>> group = parser.add_mutually_exclusive_group(required=True)
1823 >>> group.add_argument('--foo', action='store_true')
1824 >>> group.add_argument('--bar', action='store_false')
1825 >>> parser.parse_args([])
1826 usage: PROG [-h] (--foo | --bar)
1827 PROG: error: one of the arguments --foo --bar is required
1828
1829 Note that currently mutually exclusive argument groups do not support the
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001830 *title* and *description* arguments of
1831 :meth:`~ArgumentParser.add_argument_group`.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001832
1833
1834Parser defaults
1835^^^^^^^^^^^^^^^
1836
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001837.. method:: ArgumentParser.set_defaults(**kwargs)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001838
1839 Most of the time, the attributes of the object returned by :meth:`parse_args`
Éric Araujod9d7bca2011-08-10 04:19:03 +02001840 will be fully determined by inspecting the command-line arguments and the argument
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001841 actions. :meth:`set_defaults` allows some additional
Georg Brandl69518bc2011-04-16 16:44:54 +02001842 attributes that are determined without any inspection of the command line to
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001843 be added::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001844
1845 >>> parser = argparse.ArgumentParser()
1846 >>> parser.add_argument('foo', type=int)
1847 >>> parser.set_defaults(bar=42, baz='badger')
1848 >>> parser.parse_args(['736'])
1849 Namespace(bar=42, baz='badger', foo=736)
1850
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001851 Note that parser-level defaults always override argument-level defaults::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001852
1853 >>> parser = argparse.ArgumentParser()
1854 >>> parser.add_argument('--foo', default='bar')
1855 >>> parser.set_defaults(foo='spam')
1856 >>> parser.parse_args([])
1857 Namespace(foo='spam')
1858
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001859 Parser-level defaults can be particularly useful when working with multiple
1860 parsers. See the :meth:`~ArgumentParser.add_subparsers` method for an
1861 example of this type.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001862
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001863.. method:: ArgumentParser.get_default(dest)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001864
1865 Get the default value for a namespace attribute, as set by either
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001866 :meth:`~ArgumentParser.add_argument` or by
1867 :meth:`~ArgumentParser.set_defaults`::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001868
1869 >>> parser = argparse.ArgumentParser()
1870 >>> parser.add_argument('--foo', default='badger')
1871 >>> parser.get_default('foo')
1872 'badger'
1873
1874
1875Printing help
1876^^^^^^^^^^^^^
1877
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001878In most typical applications, :meth:`~ArgumentParser.parse_args` will take
1879care of formatting and printing any usage or error messages. However, several
1880formatting methods are available:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001881
Georg Brandle0bf91d2010-10-17 10:34:28 +00001882.. method:: ArgumentParser.print_usage(file=None)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001883
1884 Print a brief description of how the :class:`ArgumentParser` should be
R. David Murray32e17712010-12-18 16:39:06 +00001885 invoked on the command line. If *file* is ``None``, :data:`sys.stdout` is
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001886 assumed.
1887
Georg Brandle0bf91d2010-10-17 10:34:28 +00001888.. method:: ArgumentParser.print_help(file=None)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001889
1890 Print a help message, including the program usage and information about the
Georg Brandle0bf91d2010-10-17 10:34:28 +00001891 arguments registered with the :class:`ArgumentParser`. If *file* is
R. David Murray32e17712010-12-18 16:39:06 +00001892 ``None``, :data:`sys.stdout` is assumed.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001893
1894There are also variants of these methods that simply return a string instead of
1895printing it:
1896
Georg Brandle0bf91d2010-10-17 10:34:28 +00001897.. method:: ArgumentParser.format_usage()
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001898
1899 Return a string containing a brief description of how the
1900 :class:`ArgumentParser` should be invoked on the command line.
1901
Georg Brandle0bf91d2010-10-17 10:34:28 +00001902.. method:: ArgumentParser.format_help()
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001903
1904 Return a string containing a help message, including the program usage and
1905 information about the arguments registered with the :class:`ArgumentParser`.
1906
1907
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001908Partial parsing
1909^^^^^^^^^^^^^^^
1910
Georg Brandle0bf91d2010-10-17 10:34:28 +00001911.. method:: ArgumentParser.parse_known_args(args=None, namespace=None)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001912
Georg Brandl69518bc2011-04-16 16:44:54 +02001913Sometimes a script may only parse a few of the command-line arguments, passing
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001914the remaining arguments on to another script or program. In these cases, the
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001915:meth:`~ArgumentParser.parse_known_args` method can be useful. It works much like
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001916:meth:`~ArgumentParser.parse_args` except that it does not produce an error when
1917extra arguments are present. Instead, it returns a two item tuple containing
1918the populated namespace and the list of remaining argument strings.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001919
1920::
1921
1922 >>> parser = argparse.ArgumentParser()
1923 >>> parser.add_argument('--foo', action='store_true')
1924 >>> parser.add_argument('bar')
1925 >>> parser.parse_known_args(['--foo', '--badger', 'BAR', 'spam'])
1926 (Namespace(bar='BAR', foo=True), ['--badger', 'spam'])
1927
Eli Benderskyf3114532013-12-02 05:49:54 -08001928.. warning::
1929 :ref:`Prefix matching <prefix-matching>` rules apply to
1930 :meth:`parse_known_args`. The parser may consume an option even if it's just
1931 a prefix of one of its known options, instead of leaving it in the remaining
1932 arguments list.
1933
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001934
1935Customizing file parsing
1936^^^^^^^^^^^^^^^^^^^^^^^^
1937
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001938.. method:: ArgumentParser.convert_arg_line_to_args(arg_line)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001939
Georg Brandle0bf91d2010-10-17 10:34:28 +00001940 Arguments that are read from a file (see the *fromfile_prefix_chars*
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001941 keyword argument to the :class:`ArgumentParser` constructor) are read one
Donald Stufft8b852f12014-05-20 12:58:38 -04001942 argument per line. :meth:`convert_arg_line_to_args` can be overridden for
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001943 fancier reading.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001944
Georg Brandle0bf91d2010-10-17 10:34:28 +00001945 This method takes a single argument *arg_line* which is a string read from
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001946 the argument file. It returns a list of arguments parsed from this string.
1947 The method is called once per line read from the argument file, in order.
1948
1949 A useful override of this method is one that treats each space-separated word
1950 as an argument::
1951
1952 def convert_arg_line_to_args(self, arg_line):
Berker Peksag8c99a6d2015-04-26 12:09:54 +03001953 return arg_line.split()
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001954
1955
Georg Brandl93754922010-10-17 10:28:04 +00001956Exiting methods
1957^^^^^^^^^^^^^^^
1958
1959.. method:: ArgumentParser.exit(status=0, message=None)
1960
1961 This method terminates the program, exiting with the specified *status*
1962 and, if given, it prints a *message* before that.
1963
1964.. method:: ArgumentParser.error(message)
1965
1966 This method prints a usage message including the *message* to the
Senthil Kumaran86a1a892011-08-03 07:42:18 +08001967 standard error and terminates the program with a status code of 2.
Georg Brandl93754922010-10-17 10:28:04 +00001968
Raymond Hettinger677e10a2010-12-07 06:45:30 +00001969.. _upgrading-optparse-code:
Georg Brandl93754922010-10-17 10:28:04 +00001970
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001971Upgrading optparse code
1972-----------------------
1973
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001974Originally, the :mod:`argparse` module had attempted to maintain compatibility
Ezio Melotti0ee9c1b2011-04-21 16:12:17 +03001975with :mod:`optparse`. However, :mod:`optparse` was difficult to extend
1976transparently, particularly with the changes required to support the new
1977``nargs=`` specifiers and better usage messages. When most everything in
1978:mod:`optparse` had either been copy-pasted over or monkey-patched, it no
1979longer seemed practical to try to maintain the backwards compatibility.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001980
Berker Peksag6c1f0ad2014-09-26 15:34:26 +03001981The :mod:`argparse` module improves on the standard library :mod:`optparse`
1982module in a number of ways including:
1983
1984* Handling positional arguments.
1985* Supporting sub-commands.
1986* Allowing alternative option prefixes like ``+`` and ``/``.
1987* Handling zero-or-more and one-or-more style arguments.
1988* Producing more informative usage messages.
1989* Providing a much simpler interface for custom ``type`` and ``action``.
1990
Ezio Melotti0ee9c1b2011-04-21 16:12:17 +03001991A partial upgrade path from :mod:`optparse` to :mod:`argparse`:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001992
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001993* Replace all :meth:`optparse.OptionParser.add_option` calls with
1994 :meth:`ArgumentParser.add_argument` calls.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001995
R David Murray5e0c5712012-03-30 18:07:42 -04001996* Replace ``(options, args) = parser.parse_args()`` with ``args =
Georg Brandlc9007082011-01-09 09:04:08 +00001997 parser.parse_args()`` and add additional :meth:`ArgumentParser.add_argument`
R David Murray5e0c5712012-03-30 18:07:42 -04001998 calls for the positional arguments. Keep in mind that what was previously
1999 called ``options``, now in :mod:`argparse` context is called ``args``.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002000
2001* Replace callback actions and the ``callback_*`` keyword arguments with
2002 ``type`` or ``action`` arguments.
2003
2004* Replace string names for ``type`` keyword arguments with the corresponding
2005 type objects (e.g. int, float, complex, etc).
2006
Benjamin Peterson98047eb2010-03-03 02:07:08 +00002007* Replace :class:`optparse.Values` with :class:`Namespace` and
2008 :exc:`optparse.OptionError` and :exc:`optparse.OptionValueError` with
2009 :exc:`ArgumentError`.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002010
2011* Replace strings with implicit arguments such as ``%default`` or ``%prog`` with
Ezio Melotticca4ef82011-04-21 15:26:46 +03002012 the standard Python syntax to use dictionaries to format strings, that is,
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002013 ``%(default)s`` and ``%(prog)s``.
Steven Bethard59710962010-05-24 03:21:08 +00002014
2015* Replace the OptionParser constructor ``version`` argument with a call to
Martin Panterd21e0b52015-10-10 10:36:22 +00002016 ``parser.add_argument('--version', action='version', version='<the version>')``.