blob: 72095a825f2e8b6f22eb35ff607c1d180895c14e [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
533:meth:`~ArgumentParser.parse_args` method of a :class:`ArgumentParser`,
534it :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
Ezio Melotti2f1db7d2011-04-21 23:06:48 +0300723 argument. (Note that the const_ keyword argument defaults to the rather
724 unhelpful ``None``.) The ``'store_const'`` action is most commonly used with
725 optional arguments that specify some sort of flag. For example::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000726
727 >>> parser = argparse.ArgumentParser()
728 >>> parser.add_argument('--foo', action='store_const', const=42)
729 >>> parser.parse_args('--foo'.split())
730 Namespace(foo=42)
731
732* ``'store_true'`` and ``'store_false'`` - These store the values ``True`` and
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000733 ``False`` respectively. These are special cases of ``'store_const'``. For
734 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')
739 >>> parser.parse_args('--foo --bar'.split())
740 Namespace(bar=False, foo=True)
741
742* ``'append'`` - This stores a list, and appends each argument value to the
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000743 list. This is useful to allow an option to be specified multiple times.
744 Example usage::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000745
746 >>> parser = argparse.ArgumentParser()
747 >>> parser.add_argument('--foo', action='append')
748 >>> parser.parse_args('--foo 1 --foo 2'.split())
749 Namespace(foo=['1', '2'])
750
751* ``'append_const'`` - This stores a list, and appends the value specified by
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000752 the const_ keyword argument to the list. (Note that the const_ keyword
753 argument defaults to ``None``.) The ``'append_const'`` action is typically
754 useful when multiple arguments need to store constants to the same list. For
755 example::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000756
757 >>> parser = argparse.ArgumentParser()
758 >>> parser.add_argument('--str', dest='types', action='append_const', const=str)
759 >>> parser.add_argument('--int', dest='types', action='append_const', const=int)
760 >>> parser.parse_args('--str --int'.split())
Florent Xicluna74e64952011-10-28 11:21:19 +0200761 Namespace(types=[<class 'str'>, <class 'int'>])
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000762
Sandro Tosi98492a52012-01-04 23:25:04 +0100763* ``'count'`` - This counts the number of times a keyword argument occurs. For
764 example, this is useful for increasing verbosity levels::
765
766 >>> parser = argparse.ArgumentParser()
767 >>> parser.add_argument('--verbose', '-v', action='count')
768 >>> parser.parse_args('-vvv'.split())
769 Namespace(verbose=3)
770
771* ``'help'`` - This prints a complete help message for all the options in the
772 current parser and then exits. By default a help action is automatically
773 added to the parser. See :class:`ArgumentParser` for details of how the
774 output is created.
775
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000776* ``'version'`` - This expects a ``version=`` keyword argument in the
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300777 :meth:`~ArgumentParser.add_argument` call, and prints version information
Éric Araujoc3ef0372012-02-20 01:44:55 +0100778 and exits when invoked::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000779
780 >>> import argparse
781 >>> parser = argparse.ArgumentParser(prog='PROG')
Steven Bethard59710962010-05-24 03:21:08 +0000782 >>> parser.add_argument('--version', action='version', version='%(prog)s 2.0')
783 >>> parser.parse_args(['--version'])
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000784 PROG 2.0
785
Jason R. Coombseb0ef412014-07-20 10:52:46 -0400786You may also specify an arbitrary action by passing an Action subclass or
787other object that implements the same interface. The recommended way to do
Jason R. Coombs79690ac2014-08-03 14:54:11 -0400788this is to extend :class:`Action`, overriding the ``__call__`` method
Jason R. Coombseb0ef412014-07-20 10:52:46 -0400789and optionally the ``__init__`` method.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000790
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000791An example of a custom action::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000792
793 >>> class FooAction(argparse.Action):
Jason R. Coombseb0ef412014-07-20 10:52:46 -0400794 ... def __init__(self, option_strings, dest, nargs=None, **kwargs):
795 ... if nargs is not None:
796 ... raise ValueError("nargs not allowed")
797 ... super(FooAction, self).__init__(option_strings, dest, **kwargs)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000798 ... def __call__(self, parser, namespace, values, option_string=None):
Georg Brandl571a9532010-07-26 17:00:20 +0000799 ... print('%r %r %r' % (namespace, values, option_string))
800 ... setattr(namespace, self.dest, values)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000801 ...
802 >>> parser = argparse.ArgumentParser()
803 >>> parser.add_argument('--foo', action=FooAction)
804 >>> parser.add_argument('bar', action=FooAction)
805 >>> args = parser.parse_args('1 --foo 2'.split())
806 Namespace(bar=None, foo=None) '1' None
807 Namespace(bar='1', foo=None) '2' '--foo'
808 >>> args
809 Namespace(bar='1', foo='2')
810
Jason R. Coombs79690ac2014-08-03 14:54:11 -0400811For more details, see :class:`Action`.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000812
813nargs
814^^^^^
815
816ArgumentParser objects usually associate a single command-line argument with a
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000817single action to be taken. The ``nargs`` keyword argument associates a
Ezio Melotti00f53af2011-04-21 22:56:51 +0300818different number of command-line arguments with a single action. The supported
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000819values are:
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000820
Éric Araujoc3ef0372012-02-20 01:44:55 +0100821* ``N`` (an integer). ``N`` arguments from the command line will be gathered
822 together into a list. For example::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000823
Georg Brandl682d7e02010-10-06 10:26:05 +0000824 >>> parser = argparse.ArgumentParser()
825 >>> parser.add_argument('--foo', nargs=2)
826 >>> parser.add_argument('bar', nargs=1)
827 >>> parser.parse_args('c --foo a b'.split())
828 Namespace(bar=['c'], foo=['a', 'b'])
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000829
Georg Brandl682d7e02010-10-06 10:26:05 +0000830 Note that ``nargs=1`` produces a list of one item. This is different from
831 the default, in which the item is produced by itself.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000832
Éric Araujofde92422011-08-19 01:30:26 +0200833* ``'?'``. One argument will be consumed from the command line if possible, and
834 produced as a single item. If no command-line argument is present, the value from
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000835 default_ will be produced. Note that for optional arguments, there is an
836 additional case - the option string is present but not followed by a
Éric Araujofde92422011-08-19 01:30:26 +0200837 command-line argument. In this case the value from const_ will be produced. Some
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000838 examples to illustrate this::
839
840 >>> parser = argparse.ArgumentParser()
841 >>> parser.add_argument('--foo', nargs='?', const='c', default='d')
842 >>> parser.add_argument('bar', nargs='?', default='d')
843 >>> parser.parse_args('XX --foo YY'.split())
844 Namespace(bar='XX', foo='YY')
845 >>> parser.parse_args('XX --foo'.split())
846 Namespace(bar='XX', foo='c')
847 >>> parser.parse_args(''.split())
848 Namespace(bar='d', foo='d')
849
850 One of the more common uses of ``nargs='?'`` is to allow optional input and
851 output files::
852
853 >>> parser = argparse.ArgumentParser()
Georg Brandle0bf91d2010-10-17 10:34:28 +0000854 >>> parser.add_argument('infile', nargs='?', type=argparse.FileType('r'),
855 ... default=sys.stdin)
856 >>> parser.add_argument('outfile', nargs='?', type=argparse.FileType('w'),
857 ... default=sys.stdout)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000858 >>> parser.parse_args(['input.txt', 'output.txt'])
Georg Brandl04536b02011-01-09 09:31:01 +0000859 Namespace(infile=<_io.TextIOWrapper name='input.txt' encoding='UTF-8'>,
860 outfile=<_io.TextIOWrapper name='output.txt' encoding='UTF-8'>)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000861 >>> parser.parse_args([])
Georg Brandl04536b02011-01-09 09:31:01 +0000862 Namespace(infile=<_io.TextIOWrapper name='<stdin>' encoding='UTF-8'>,
863 outfile=<_io.TextIOWrapper name='<stdout>' encoding='UTF-8'>)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000864
Éric Araujod9d7bca2011-08-10 04:19:03 +0200865* ``'*'``. All command-line arguments present are gathered into a list. Note that
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000866 it generally doesn't make much sense to have more than one positional argument
867 with ``nargs='*'``, but multiple optional arguments with ``nargs='*'`` is
868 possible. For example::
869
870 >>> parser = argparse.ArgumentParser()
871 >>> parser.add_argument('--foo', nargs='*')
872 >>> parser.add_argument('--bar', nargs='*')
873 >>> parser.add_argument('baz', nargs='*')
874 >>> parser.parse_args('a b --foo x y --bar 1 2'.split())
875 Namespace(bar=['1', '2'], baz=['a', 'b'], foo=['x', 'y'])
876
877* ``'+'``. Just like ``'*'``, all command-line args present are gathered into a
878 list. Additionally, an error message will be generated if there wasn't at
Éric Araujofde92422011-08-19 01:30:26 +0200879 least one command-line argument present. For example::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000880
881 >>> parser = argparse.ArgumentParser(prog='PROG')
882 >>> parser.add_argument('foo', nargs='+')
883 >>> parser.parse_args('a b'.split())
884 Namespace(foo=['a', 'b'])
885 >>> parser.parse_args(''.split())
886 usage: PROG [-h] foo [foo ...]
887 PROG: error: too few arguments
888
Sandro Tosida8e11a2012-01-19 22:23:00 +0100889* ``argparse.REMAINDER``. All the remaining command-line arguments are gathered
890 into a list. This is commonly useful for command line utilities that dispatch
Éric Araujoc3ef0372012-02-20 01:44:55 +0100891 to other command line utilities::
Sandro Tosi16bd0b42012-01-19 21:59:55 +0100892
893 >>> parser = argparse.ArgumentParser(prog='PROG')
894 >>> parser.add_argument('--foo')
895 >>> parser.add_argument('command')
896 >>> parser.add_argument('args', nargs=argparse.REMAINDER)
Sandro Tosi04676862012-02-19 19:54:00 +0100897 >>> print(parser.parse_args('--foo B cmd --arg1 XX ZZ'.split()))
Sandro Tosida8e11a2012-01-19 22:23:00 +0100898 Namespace(args=['--arg1', 'XX', 'ZZ'], command='cmd', foo='B')
Sandro Tosi16bd0b42012-01-19 21:59:55 +0100899
Éric Araujod9d7bca2011-08-10 04:19:03 +0200900If the ``nargs`` keyword argument is not provided, the number of arguments consumed
Éric Araujofde92422011-08-19 01:30:26 +0200901is determined by the action_. Generally this means a single command-line argument
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000902will be consumed and a single item (not a list) will be produced.
903
904
905const
906^^^^^
907
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300908The ``const`` argument of :meth:`~ArgumentParser.add_argument` is used to hold
909constant values that are not read from the command line but are required for
910the various :class:`ArgumentParser` actions. The two most common uses of it are:
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000911
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300912* When :meth:`~ArgumentParser.add_argument` is called with
913 ``action='store_const'`` or ``action='append_const'``. These actions add the
Éric Araujoc3ef0372012-02-20 01:44:55 +0100914 ``const`` value to one of the attributes of the object returned by
915 :meth:`~ArgumentParser.parse_args`. See the action_ description for examples.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000916
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300917* When :meth:`~ArgumentParser.add_argument` is called with option strings
918 (like ``-f`` or ``--foo``) and ``nargs='?'``. This creates an optional
Éric Araujod9d7bca2011-08-10 04:19:03 +0200919 argument that can be followed by zero or one command-line arguments.
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300920 When parsing the command line, if the option string is encountered with no
Éric Araujofde92422011-08-19 01:30:26 +0200921 command-line argument following it, the value of ``const`` will be assumed instead.
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300922 See the nargs_ description for examples.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000923
924The ``const`` keyword argument defaults to ``None``.
925
926
927default
928^^^^^^^
929
930All optional arguments and some positional arguments may be omitted at the
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300931command line. The ``default`` keyword argument of
932:meth:`~ArgumentParser.add_argument`, whose value defaults to ``None``,
Éric Araujofde92422011-08-19 01:30:26 +0200933specifies what value should be used if the command-line argument is not present.
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300934For optional arguments, the ``default`` value is used when the option string
935was not present at the command line::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000936
937 >>> parser = argparse.ArgumentParser()
938 >>> parser.add_argument('--foo', default=42)
939 >>> parser.parse_args('--foo 2'.split())
940 Namespace(foo='2')
941 >>> parser.parse_args(''.split())
942 Namespace(foo=42)
943
Barry Warsaw1dedd0a2012-09-25 10:37:58 -0400944If the ``default`` value is a string, the parser parses the value as if it
945were a command-line argument. In particular, the parser applies any type_
946conversion argument, if provided, before setting the attribute on the
947:class:`Namespace` return value. Otherwise, the parser uses the value as is::
948
949 >>> parser = argparse.ArgumentParser()
950 >>> parser.add_argument('--length', default='10', type=int)
951 >>> parser.add_argument('--width', default=10.5, type=int)
952 >>> parser.parse_args()
953 Namespace(length=10, width=10.5)
954
Éric Araujo543edbd2011-08-19 01:45:12 +0200955For positional arguments with nargs_ equal to ``?`` or ``*``, the ``default`` value
Éric Araujofde92422011-08-19 01:30:26 +0200956is used when no command-line argument was present::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000957
958 >>> parser = argparse.ArgumentParser()
959 >>> parser.add_argument('foo', nargs='?', default=42)
960 >>> parser.parse_args('a'.split())
961 Namespace(foo='a')
962 >>> parser.parse_args(''.split())
963 Namespace(foo=42)
964
965
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000966Providing ``default=argparse.SUPPRESS`` causes no attribute to be added if the
967command-line argument was not present.::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000968
969 >>> parser = argparse.ArgumentParser()
970 >>> parser.add_argument('--foo', default=argparse.SUPPRESS)
971 >>> parser.parse_args([])
972 Namespace()
973 >>> parser.parse_args(['--foo', '1'])
974 Namespace(foo='1')
975
976
977type
978^^^^
979
Éric Araujod9d7bca2011-08-10 04:19:03 +0200980By default, :class:`ArgumentParser` objects read command-line arguments in as simple
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300981strings. However, quite often the command-line string should instead be
982interpreted as another type, like a :class:`float` or :class:`int`. The
983``type`` keyword argument of :meth:`~ArgumentParser.add_argument` allows any
Éric Araujod9d7bca2011-08-10 04:19:03 +0200984necessary type-checking and type conversions to be performed. Common built-in
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300985types and functions can be used directly as the value of the ``type`` argument::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000986
987 >>> parser = argparse.ArgumentParser()
988 >>> parser.add_argument('foo', type=int)
Georg Brandl04536b02011-01-09 09:31:01 +0000989 >>> parser.add_argument('bar', type=open)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000990 >>> parser.parse_args('2 temp.txt'.split())
Georg Brandl04536b02011-01-09 09:31:01 +0000991 Namespace(bar=<_io.TextIOWrapper name='temp.txt' encoding='UTF-8'>, foo=2)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000992
Barry Warsaw1dedd0a2012-09-25 10:37:58 -0400993See the section on the default_ keyword argument for information on when the
994``type`` argument is applied to default arguments.
995
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000996To ease the use of various types of files, the argparse module provides the
Petri Lehtinen74d6c252012-12-15 22:39:32 +0200997factory FileType which takes the ``mode=``, ``bufsize=``, ``encoding=`` and
998``errors=`` arguments of the :func:`open` function. For example,
999``FileType('w')`` can be used to create a writable file::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001000
1001 >>> parser = argparse.ArgumentParser()
1002 >>> parser.add_argument('bar', type=argparse.FileType('w'))
1003 >>> parser.parse_args(['out.txt'])
Georg Brandl04536b02011-01-09 09:31:01 +00001004 Namespace(bar=<_io.TextIOWrapper name='out.txt' encoding='UTF-8'>)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001005
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001006``type=`` can take any callable that takes a single string argument and returns
Éric Araujod9d7bca2011-08-10 04:19:03 +02001007the converted value::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001008
1009 >>> def perfect_square(string):
1010 ... value = int(string)
1011 ... sqrt = math.sqrt(value)
1012 ... if sqrt != int(sqrt):
1013 ... msg = "%r is not a perfect square" % string
1014 ... raise argparse.ArgumentTypeError(msg)
1015 ... return value
1016 ...
1017 >>> parser = argparse.ArgumentParser(prog='PROG')
1018 >>> parser.add_argument('foo', type=perfect_square)
1019 >>> parser.parse_args('9'.split())
1020 Namespace(foo=9)
1021 >>> parser.parse_args('7'.split())
1022 usage: PROG [-h] foo
1023 PROG: error: argument foo: '7' is not a perfect square
1024
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001025The choices_ keyword argument may be more convenient for type checkers that
1026simply check against a range of values::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001027
1028 >>> parser = argparse.ArgumentParser(prog='PROG')
Fred Drake44623062011-03-03 05:27:17 +00001029 >>> parser.add_argument('foo', type=int, choices=range(5, 10))
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001030 >>> parser.parse_args('7'.split())
1031 Namespace(foo=7)
1032 >>> parser.parse_args('11'.split())
1033 usage: PROG [-h] {5,6,7,8,9}
1034 PROG: error: argument foo: invalid choice: 11 (choose from 5, 6, 7, 8, 9)
1035
1036See the choices_ section for more details.
1037
1038
1039choices
1040^^^^^^^
1041
Éric Araujod9d7bca2011-08-10 04:19:03 +02001042Some command-line arguments should be selected from a restricted set of values.
Chris Jerdonek174ef672013-01-11 19:26:44 -08001043These can be handled by passing a container object as the *choices* keyword
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001044argument to :meth:`~ArgumentParser.add_argument`. When the command line is
Chris Jerdonek174ef672013-01-11 19:26:44 -08001045parsed, argument values will be checked, and an error message will be displayed
1046if the argument was not one of the acceptable values::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001047
Chris Jerdonek174ef672013-01-11 19:26:44 -08001048 >>> parser = argparse.ArgumentParser(prog='game.py')
1049 >>> parser.add_argument('move', choices=['rock', 'paper', 'scissors'])
1050 >>> parser.parse_args(['rock'])
1051 Namespace(move='rock')
1052 >>> parser.parse_args(['fire'])
1053 usage: game.py [-h] {rock,paper,scissors}
1054 game.py: error: argument move: invalid choice: 'fire' (choose from 'rock',
1055 'paper', 'scissors')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001056
Chris Jerdonek174ef672013-01-11 19:26:44 -08001057Note that inclusion in the *choices* container is checked after any type_
1058conversions have been performed, so the type of the objects in the *choices*
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001059container should match the type_ specified::
1060
Chris Jerdonek174ef672013-01-11 19:26:44 -08001061 >>> parser = argparse.ArgumentParser(prog='doors.py')
1062 >>> parser.add_argument('door', type=int, choices=range(1, 4))
1063 >>> print(parser.parse_args(['3']))
1064 Namespace(door=3)
1065 >>> parser.parse_args(['4'])
1066 usage: doors.py [-h] {1,2,3}
1067 doors.py: error: argument door: invalid choice: 4 (choose from 1, 2, 3)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001068
Chris Jerdonek174ef672013-01-11 19:26:44 -08001069Any object that supports the ``in`` operator can be passed as the *choices*
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001070value, so :class:`dict` objects, :class:`set` objects, custom containers,
1071etc. are all supported.
1072
1073
1074required
1075^^^^^^^^
1076
Ezio Melotti0ee9c1b2011-04-21 16:12:17 +03001077In general, the :mod:`argparse` module assumes that flags like ``-f`` and ``--bar``
Georg Brandl69518bc2011-04-16 16:44:54 +02001078indicate *optional* arguments, which can always be omitted at the command line.
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001079To make an option *required*, ``True`` can be specified for the ``required=``
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001080keyword argument to :meth:`~ArgumentParser.add_argument`::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001081
1082 >>> parser = argparse.ArgumentParser()
1083 >>> parser.add_argument('--foo', required=True)
1084 >>> parser.parse_args(['--foo', 'BAR'])
1085 Namespace(foo='BAR')
1086 >>> parser.parse_args([])
1087 usage: argparse.py [-h] [--foo FOO]
1088 argparse.py: error: option --foo is required
1089
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001090As the example shows, if an option is marked as ``required``,
1091:meth:`~ArgumentParser.parse_args` will report an error if that option is not
1092present at the command line.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001093
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001094.. note::
1095
1096 Required options are generally considered bad form because users expect
1097 *options* to be *optional*, and thus they should be avoided when possible.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001098
1099
1100help
1101^^^^
1102
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001103The ``help`` value is a string containing a brief description of the argument.
1104When a user requests help (usually by using ``-h`` or ``--help`` at the
Georg Brandl69518bc2011-04-16 16:44:54 +02001105command line), these ``help`` descriptions will be displayed with each
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001106argument::
1107
1108 >>> parser = argparse.ArgumentParser(prog='frobble')
1109 >>> parser.add_argument('--foo', action='store_true',
1110 ... help='foo the bars before frobbling')
1111 >>> parser.add_argument('bar', nargs='+',
1112 ... help='one of the bars to be frobbled')
1113 >>> parser.parse_args('-h'.split())
1114 usage: frobble [-h] [--foo] bar [bar ...]
1115
1116 positional arguments:
1117 bar one of the bars to be frobbled
1118
1119 optional arguments:
1120 -h, --help show this help message and exit
1121 --foo foo the bars before frobbling
1122
1123The ``help`` strings can include various format specifiers to avoid repetition
1124of things like the program name or the argument default_. The available
1125specifiers include the program name, ``%(prog)s`` and most keyword arguments to
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001126:meth:`~ArgumentParser.add_argument`, e.g. ``%(default)s``, ``%(type)s``, etc.::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001127
1128 >>> parser = argparse.ArgumentParser(prog='frobble')
1129 >>> parser.add_argument('bar', nargs='?', type=int, default=42,
1130 ... help='the bar to %(prog)s (default: %(default)s)')
1131 >>> parser.print_help()
1132 usage: frobble [-h] [bar]
1133
1134 positional arguments:
1135 bar the bar to frobble (default: 42)
1136
1137 optional arguments:
1138 -h, --help show this help message and exit
1139
Senthil Kumaranf21804a2012-06-26 14:17:19 +08001140As the help string supports %-formatting, if you want a literal ``%`` to appear
1141in the help string, you must escape it as ``%%``.
1142
Sandro Tosiea320ab2012-01-03 18:37:03 +01001143:mod:`argparse` supports silencing the help entry for certain options, by
1144setting the ``help`` value to ``argparse.SUPPRESS``::
1145
1146 >>> parser = argparse.ArgumentParser(prog='frobble')
1147 >>> parser.add_argument('--foo', help=argparse.SUPPRESS)
1148 >>> parser.print_help()
1149 usage: frobble [-h]
1150
1151 optional arguments:
1152 -h, --help show this help message and exit
1153
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001154
1155metavar
1156^^^^^^^
1157
Sandro Tosi32587fb2013-01-11 10:49:00 +01001158When :class:`ArgumentParser` generates help messages, it needs some way to refer
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001159to each expected argument. By default, ArgumentParser objects use the dest_
1160value as the "name" of each object. By default, for positional argument
1161actions, the dest_ value is used directly, and for optional argument actions,
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001162the dest_ value is uppercased. So, a single positional argument with
Eli Benderskya7795db2011-11-11 10:57:01 +02001163``dest='bar'`` will be referred to as ``bar``. A single
Éric Araujofde92422011-08-19 01:30:26 +02001164optional argument ``--foo`` that should be followed by a single command-line argument
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001165will be referred to as ``FOO``. An example::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001166
1167 >>> parser = argparse.ArgumentParser()
1168 >>> parser.add_argument('--foo')
1169 >>> parser.add_argument('bar')
1170 >>> parser.parse_args('X --foo Y'.split())
1171 Namespace(bar='X', foo='Y')
1172 >>> parser.print_help()
1173 usage: [-h] [--foo FOO] bar
1174
1175 positional arguments:
1176 bar
1177
1178 optional arguments:
1179 -h, --help show this help message and exit
1180 --foo FOO
1181
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001182An alternative name can be specified with ``metavar``::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001183
1184 >>> parser = argparse.ArgumentParser()
1185 >>> parser.add_argument('--foo', metavar='YYY')
1186 >>> parser.add_argument('bar', metavar='XXX')
1187 >>> parser.parse_args('X --foo Y'.split())
1188 Namespace(bar='X', foo='Y')
1189 >>> parser.print_help()
1190 usage: [-h] [--foo YYY] XXX
1191
1192 positional arguments:
1193 XXX
1194
1195 optional arguments:
1196 -h, --help show this help message and exit
1197 --foo YYY
1198
1199Note that ``metavar`` only changes the *displayed* name - the name of the
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001200attribute on the :meth:`~ArgumentParser.parse_args` object is still determined
1201by the dest_ value.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001202
1203Different values of ``nargs`` may cause the metavar to be used multiple times.
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001204Providing a tuple to ``metavar`` specifies a different display for each of the
1205arguments::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001206
1207 >>> parser = argparse.ArgumentParser(prog='PROG')
1208 >>> parser.add_argument('-x', nargs=2)
1209 >>> parser.add_argument('--foo', nargs=2, metavar=('bar', 'baz'))
1210 >>> parser.print_help()
1211 usage: PROG [-h] [-x X X] [--foo bar baz]
1212
1213 optional arguments:
1214 -h, --help show this help message and exit
1215 -x X X
1216 --foo bar baz
1217
1218
1219dest
1220^^^^
1221
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001222Most :class:`ArgumentParser` actions add some value as an attribute of the
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001223object returned by :meth:`~ArgumentParser.parse_args`. The name of this
1224attribute is determined by the ``dest`` keyword argument of
1225:meth:`~ArgumentParser.add_argument`. For positional argument actions,
1226``dest`` is normally supplied as the first argument to
1227:meth:`~ArgumentParser.add_argument`::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001228
1229 >>> parser = argparse.ArgumentParser()
1230 >>> parser.add_argument('bar')
1231 >>> parser.parse_args('XXX'.split())
1232 Namespace(bar='XXX')
1233
1234For optional argument actions, the value of ``dest`` is normally inferred from
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001235the option strings. :class:`ArgumentParser` generates the value of ``dest`` by
Éric Araujo543edbd2011-08-19 01:45:12 +02001236taking the first long option string and stripping away the initial ``--``
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001237string. If no long option strings were supplied, ``dest`` will be derived from
Éric Araujo543edbd2011-08-19 01:45:12 +02001238the first short option string by stripping the initial ``-`` character. Any
1239internal ``-`` characters will be converted to ``_`` characters to make sure
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001240the string is a valid attribute name. The examples below illustrate this
1241behavior::
1242
1243 >>> parser = argparse.ArgumentParser()
1244 >>> parser.add_argument('-f', '--foo-bar', '--foo')
1245 >>> parser.add_argument('-x', '-y')
1246 >>> parser.parse_args('-f 1 -x 2'.split())
1247 Namespace(foo_bar='1', x='2')
1248 >>> parser.parse_args('--foo 1 -y 2'.split())
1249 Namespace(foo_bar='1', x='2')
1250
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001251``dest`` allows a custom attribute name to be provided::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001252
1253 >>> parser = argparse.ArgumentParser()
1254 >>> parser.add_argument('--foo', dest='bar')
1255 >>> parser.parse_args('--foo XXX'.split())
1256 Namespace(bar='XXX')
1257
Jason R. Coombsf28cf7a2011-12-13 23:36:45 -05001258Action classes
1259^^^^^^^^^^^^^^
1260
Jason R. Coombseb0ef412014-07-20 10:52:46 -04001261Action classes implement the Action API, a callable which returns a callable
1262which processes arguments from the command-line. Any object which follows
1263this API may be passed as the ``action`` parameter to
Raymond Hettingerc0de59b2014-08-03 23:44:30 -07001264:meth:`add_argument`.
Jason R. Coombseb0ef412014-07-20 10:52:46 -04001265
Terry Jan Reedyee558262014-08-23 22:21:47 -04001266.. class:: Action(option_strings, dest, nargs=None, const=None, default=None, \
1267 type=None, choices=None, required=False, help=None, \
Jason R. Coombsf28cf7a2011-12-13 23:36:45 -05001268 metavar=None)
1269
1270Action objects are used by an ArgumentParser to represent the information
1271needed to parse a single argument from one or more strings from the
Jason R. Coombseb0ef412014-07-20 10:52:46 -04001272command line. The Action class must accept the two positional arguments
Raymond Hettingerc0de59b2014-08-03 23:44:30 -07001273plus any keyword arguments passed to :meth:`ArgumentParser.add_argument`
Jason R. Coombseb0ef412014-07-20 10:52:46 -04001274except for the ``action`` itself.
Jason R. Coombsf28cf7a2011-12-13 23:36:45 -05001275
Jason R. Coombseb0ef412014-07-20 10:52:46 -04001276Instances of Action (or return value of any callable to the ``action``
1277parameter) should have attributes "dest", "option_strings", "default", "type",
1278"required", "help", etc. defined. The easiest way to ensure these attributes
1279are defined is to call ``Action.__init__``.
Jason R. Coombsf28cf7a2011-12-13 23:36:45 -05001280
Jason R. Coombseb0ef412014-07-20 10:52:46 -04001281Action instances should be callable, so subclasses must override the
1282``__call__`` method, which should accept four parameters:
Jason R. Coombsf28cf7a2011-12-13 23:36:45 -05001283
1284* ``parser`` - The ArgumentParser object which contains this action.
1285
1286* ``namespace`` - The :class:`Namespace` object that will be returned by
1287 :meth:`~ArgumentParser.parse_args`. Most actions add an attribute to this
1288 object using :func:`setattr`.
1289
1290* ``values`` - The associated command-line arguments, with any type conversions
1291 applied. Type conversions are specified with the type_ keyword argument to
1292 :meth:`~ArgumentParser.add_argument`.
1293
1294* ``option_string`` - The option string that was used to invoke this action.
1295 The ``option_string`` argument is optional, and will be absent if the action
1296 is associated with a positional argument.
1297
Jason R. Coombseb0ef412014-07-20 10:52:46 -04001298The ``__call__`` method may perform arbitrary actions, but will typically set
1299attributes on the ``namespace`` based on ``dest`` and ``values``.
1300
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001301
1302The parse_args() method
1303-----------------------
1304
Georg Brandle0bf91d2010-10-17 10:34:28 +00001305.. method:: ArgumentParser.parse_args(args=None, namespace=None)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001306
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001307 Convert argument strings to objects and assign them as attributes of the
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001308 namespace. Return the populated namespace.
1309
1310 Previous calls to :meth:`add_argument` determine exactly what objects are
1311 created and how they are assigned. See the documentation for
1312 :meth:`add_argument` for details.
1313
Éric Araujofde92422011-08-19 01:30:26 +02001314 By default, the argument strings are taken from :data:`sys.argv`, and a new empty
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001315 :class:`Namespace` object is created for the attributes.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001316
Georg Brandle0bf91d2010-10-17 10:34:28 +00001317
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001318Option value syntax
1319^^^^^^^^^^^^^^^^^^^
1320
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001321The :meth:`~ArgumentParser.parse_args` method supports several ways of
1322specifying the value of an option (if it takes one). In the simplest case, the
1323option and its value are passed as two separate arguments::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001324
1325 >>> parser = argparse.ArgumentParser(prog='PROG')
1326 >>> parser.add_argument('-x')
1327 >>> parser.add_argument('--foo')
1328 >>> parser.parse_args('-x X'.split())
1329 Namespace(foo=None, x='X')
1330 >>> parser.parse_args('--foo FOO'.split())
1331 Namespace(foo='FOO', x=None)
1332
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001333For long options (options with names longer than a single character), the option
Georg Brandl69518bc2011-04-16 16:44:54 +02001334and value can also be passed as a single command-line argument, using ``=`` to
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001335separate them::
1336
1337 >>> parser.parse_args('--foo=FOO'.split())
1338 Namespace(foo='FOO', x=None)
1339
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001340For short options (options only one character long), the option and its value
1341can be concatenated::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001342
1343 >>> parser.parse_args('-xX'.split())
1344 Namespace(foo=None, x='X')
1345
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001346Several short options can be joined together, using only a single ``-`` prefix,
1347as long as only the last option (or none of them) requires a value::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001348
1349 >>> parser = argparse.ArgumentParser(prog='PROG')
1350 >>> parser.add_argument('-x', action='store_true')
1351 >>> parser.add_argument('-y', action='store_true')
1352 >>> parser.add_argument('-z')
1353 >>> parser.parse_args('-xyzZ'.split())
1354 Namespace(x=True, y=True, z='Z')
1355
1356
1357Invalid arguments
1358^^^^^^^^^^^^^^^^^
1359
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001360While parsing the command line, :meth:`~ArgumentParser.parse_args` checks for a
1361variety of errors, including ambiguous options, invalid types, invalid options,
1362wrong number of positional arguments, etc. When it encounters such an error,
1363it exits and prints the error along with a usage message::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001364
1365 >>> parser = argparse.ArgumentParser(prog='PROG')
1366 >>> parser.add_argument('--foo', type=int)
1367 >>> parser.add_argument('bar', nargs='?')
1368
1369 >>> # invalid type
1370 >>> parser.parse_args(['--foo', 'spam'])
1371 usage: PROG [-h] [--foo FOO] [bar]
1372 PROG: error: argument --foo: invalid int value: 'spam'
1373
1374 >>> # invalid option
1375 >>> parser.parse_args(['--bar'])
1376 usage: PROG [-h] [--foo FOO] [bar]
1377 PROG: error: no such option: --bar
1378
1379 >>> # wrong number of arguments
1380 >>> parser.parse_args(['spam', 'badger'])
1381 usage: PROG [-h] [--foo FOO] [bar]
1382 PROG: error: extra arguments found: badger
1383
1384
Éric Araujo543edbd2011-08-19 01:45:12 +02001385Arguments containing ``-``
1386^^^^^^^^^^^^^^^^^^^^^^^^^^
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001387
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001388The :meth:`~ArgumentParser.parse_args` method attempts to give errors whenever
1389the user has clearly made a mistake, but some situations are inherently
Éric Araujo543edbd2011-08-19 01:45:12 +02001390ambiguous. For example, the command-line argument ``-1`` could either be an
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001391attempt to specify an option or an attempt to provide a positional argument.
1392The :meth:`~ArgumentParser.parse_args` method is cautious here: positional
Éric Araujo543edbd2011-08-19 01:45:12 +02001393arguments may only begin with ``-`` if they look like negative numbers and
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001394there are no options in the parser that look like negative numbers::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001395
1396 >>> parser = argparse.ArgumentParser(prog='PROG')
1397 >>> parser.add_argument('-x')
1398 >>> parser.add_argument('foo', nargs='?')
1399
1400 >>> # no negative number options, so -1 is a positional argument
1401 >>> parser.parse_args(['-x', '-1'])
1402 Namespace(foo=None, x='-1')
1403
1404 >>> # no negative number options, so -1 and -5 are positional arguments
1405 >>> parser.parse_args(['-x', '-1', '-5'])
1406 Namespace(foo='-5', x='-1')
1407
1408 >>> parser = argparse.ArgumentParser(prog='PROG')
1409 >>> parser.add_argument('-1', dest='one')
1410 >>> parser.add_argument('foo', nargs='?')
1411
1412 >>> # negative number options present, so -1 is an option
1413 >>> parser.parse_args(['-1', 'X'])
1414 Namespace(foo=None, one='X')
1415
1416 >>> # negative number options present, so -2 is an option
1417 >>> parser.parse_args(['-2'])
1418 usage: PROG [-h] [-1 ONE] [foo]
1419 PROG: error: no such option: -2
1420
1421 >>> # negative number options present, so both -1s are options
1422 >>> parser.parse_args(['-1', '-1'])
1423 usage: PROG [-h] [-1 ONE] [foo]
1424 PROG: error: argument -1: expected one argument
1425
Éric Araujo543edbd2011-08-19 01:45:12 +02001426If you have positional arguments that must begin with ``-`` and don't look
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001427like negative numbers, you can insert the pseudo-argument ``'--'`` which tells
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001428:meth:`~ArgumentParser.parse_args` that everything after that is a positional
1429argument::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001430
1431 >>> parser.parse_args(['--', '-f'])
1432 Namespace(foo='-f', one=None)
1433
Eli Benderskyf3114532013-12-02 05:49:54 -08001434.. _prefix-matching:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001435
Eli Benderskyf3114532013-12-02 05:49:54 -08001436Argument abbreviations (prefix matching)
1437^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001438
Berker Peksag8089cd62015-02-14 01:39:17 +02001439The :meth:`~ArgumentParser.parse_args` method :ref:`by default <allow_abbrev>`
1440allows long options to be abbreviated to a prefix, if the abbreviation is
1441unambiguous (the prefix matches a unique option)::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001442
1443 >>> parser = argparse.ArgumentParser(prog='PROG')
1444 >>> parser.add_argument('-bacon')
1445 >>> parser.add_argument('-badger')
1446 >>> parser.parse_args('-bac MMM'.split())
1447 Namespace(bacon='MMM', badger=None)
1448 >>> parser.parse_args('-bad WOOD'.split())
1449 Namespace(bacon=None, badger='WOOD')
1450 >>> parser.parse_args('-ba BA'.split())
1451 usage: PROG [-h] [-bacon BACON] [-badger BADGER]
1452 PROG: error: ambiguous option: -ba could match -badger, -bacon
1453
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001454An error is produced for arguments that could produce more than one options.
Berker Peksag8089cd62015-02-14 01:39:17 +02001455This feature can be disabled by setting :ref:`allow_abbrev` to ``False``.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001456
1457
1458Beyond ``sys.argv``
1459^^^^^^^^^^^^^^^^^^^
1460
Éric Araujod9d7bca2011-08-10 04:19:03 +02001461Sometimes it may be useful to have an ArgumentParser parse arguments other than those
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001462of :data:`sys.argv`. This can be accomplished by passing a list of strings to
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001463:meth:`~ArgumentParser.parse_args`. This is useful for testing at the
1464interactive prompt::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001465
1466 >>> parser = argparse.ArgumentParser()
1467 >>> parser.add_argument(
Fred Drake44623062011-03-03 05:27:17 +00001468 ... 'integers', metavar='int', type=int, choices=range(10),
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001469 ... nargs='+', help='an integer in the range 0..9')
1470 >>> parser.add_argument(
1471 ... '--sum', dest='accumulate', action='store_const', const=sum,
1472 ... default=max, help='sum the integers (default: find the max)')
1473 >>> parser.parse_args(['1', '2', '3', '4'])
1474 Namespace(accumulate=<built-in function max>, integers=[1, 2, 3, 4])
1475 >>> parser.parse_args('1 2 3 4 --sum'.split())
1476 Namespace(accumulate=<built-in function sum>, integers=[1, 2, 3, 4])
1477
1478
Steven Bethardd8f2d502011-03-26 19:50:06 +01001479The Namespace object
1480^^^^^^^^^^^^^^^^^^^^
1481
Éric Araujo63b18a42011-07-29 17:59:17 +02001482.. class:: Namespace
1483
1484 Simple class used by default by :meth:`~ArgumentParser.parse_args` to create
1485 an object holding attributes and return it.
1486
1487This class is deliberately simple, just an :class:`object` subclass with a
1488readable string representation. If you prefer to have dict-like view of the
1489attributes, you can use the standard Python idiom, :func:`vars`::
Steven Bethardd8f2d502011-03-26 19:50:06 +01001490
1491 >>> parser = argparse.ArgumentParser()
1492 >>> parser.add_argument('--foo')
1493 >>> args = parser.parse_args(['--foo', 'BAR'])
1494 >>> vars(args)
1495 {'foo': 'BAR'}
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001496
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001497It may also be useful to have an :class:`ArgumentParser` assign attributes to an
Steven Bethardd8f2d502011-03-26 19:50:06 +01001498already existing object, rather than a new :class:`Namespace` object. This can
1499be achieved by specifying the ``namespace=`` keyword argument::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001500
Éric Araujo28053fb2010-11-22 03:09:19 +00001501 >>> class C:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001502 ... pass
1503 ...
1504 >>> c = C()
1505 >>> parser = argparse.ArgumentParser()
1506 >>> parser.add_argument('--foo')
1507 >>> parser.parse_args(args=['--foo', 'BAR'], namespace=c)
1508 >>> c.foo
1509 'BAR'
1510
1511
1512Other utilities
1513---------------
1514
1515Sub-commands
1516^^^^^^^^^^^^
1517
Georg Brandlfc9a1132013-10-06 18:51:39 +02001518.. method:: ArgumentParser.add_subparsers([title], [description], [prog], \
1519 [parser_class], [action], \
1520 [option_string], [dest], [help], \
1521 [metavar])
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001522
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001523 Many programs split up their functionality into a number of sub-commands,
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001524 for example, the ``svn`` program can invoke sub-commands like ``svn
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001525 checkout``, ``svn update``, and ``svn commit``. Splitting up functionality
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001526 this way can be a particularly good idea when a program performs several
1527 different functions which require different kinds of command-line arguments.
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001528 :class:`ArgumentParser` supports the creation of such sub-commands with the
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001529 :meth:`add_subparsers` method. The :meth:`add_subparsers` method is normally
Ezio Melotti52336f02012-12-28 01:59:24 +02001530 called with no arguments and returns a special action object. This object
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001531 has a single method, :meth:`~ArgumentParser.add_parser`, which takes a
1532 command name and any :class:`ArgumentParser` constructor arguments, and
1533 returns an :class:`ArgumentParser` object that can be modified as usual.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001534
Georg Brandlfc9a1132013-10-06 18:51:39 +02001535 Description of parameters:
1536
1537 * title - title for the sub-parser group in help output; by default
1538 "subcommands" if description is provided, otherwise uses title for
1539 positional arguments
1540
1541 * description - description for the sub-parser group in help output, by
1542 default None
1543
1544 * prog - usage information that will be displayed with sub-command help,
1545 by default the name of the program and any positional arguments before the
1546 subparser argument
1547
1548 * parser_class - class which will be used to create sub-parser instances, by
1549 default the class of the current parser (e.g. ArgumentParser)
1550
Berker Peksag5a494f62015-01-20 06:45:53 +02001551 * action_ - the basic type of action to be taken when this argument is
1552 encountered at the command line
1553
1554 * dest_ - name of the attribute under which sub-command name will be
Georg Brandlfc9a1132013-10-06 18:51:39 +02001555 stored; by default None and no value is stored
1556
Berker Peksag5a494f62015-01-20 06:45:53 +02001557 * help_ - help for sub-parser group in help output, by default None
Georg Brandlfc9a1132013-10-06 18:51:39 +02001558
Berker Peksag5a494f62015-01-20 06:45:53 +02001559 * metavar_ - string presenting available sub-commands in help; by default it
Georg Brandlfc9a1132013-10-06 18:51:39 +02001560 is None and presents sub-commands in form {cmd1, cmd2, ..}
1561
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001562 Some example usage::
1563
1564 >>> # create the top-level parser
1565 >>> parser = argparse.ArgumentParser(prog='PROG')
1566 >>> parser.add_argument('--foo', action='store_true', help='foo help')
1567 >>> subparsers = parser.add_subparsers(help='sub-command help')
1568 >>>
1569 >>> # create the parser for the "a" command
1570 >>> parser_a = subparsers.add_parser('a', help='a help')
1571 >>> parser_a.add_argument('bar', type=int, help='bar help')
1572 >>>
1573 >>> # create the parser for the "b" command
1574 >>> parser_b = subparsers.add_parser('b', help='b help')
1575 >>> parser_b.add_argument('--baz', choices='XYZ', help='baz help')
1576 >>>
Éric Araujofde92422011-08-19 01:30:26 +02001577 >>> # parse some argument lists
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001578 >>> parser.parse_args(['a', '12'])
1579 Namespace(bar=12, foo=False)
1580 >>> parser.parse_args(['--foo', 'b', '--baz', 'Z'])
1581 Namespace(baz='Z', foo=True)
1582
1583 Note that the object returned by :meth:`parse_args` will only contain
1584 attributes for the main parser and the subparser that was selected by the
1585 command line (and not any other subparsers). So in the example above, when
Éric Araujo543edbd2011-08-19 01:45:12 +02001586 the ``a`` command is specified, only the ``foo`` and ``bar`` attributes are
1587 present, and when the ``b`` command is specified, only the ``foo`` and
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001588 ``baz`` attributes are present.
1589
1590 Similarly, when a help message is requested from a subparser, only the help
1591 for that particular parser will be printed. The help message will not
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001592 include parent parser or sibling parser messages. (A help message for each
1593 subparser command, however, can be given by supplying the ``help=`` argument
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001594 to :meth:`add_parser` as above.)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001595
1596 ::
1597
1598 >>> parser.parse_args(['--help'])
1599 usage: PROG [-h] [--foo] {a,b} ...
1600
1601 positional arguments:
1602 {a,b} sub-command help
Ezio Melotti7128e072013-01-12 10:39:45 +02001603 a a help
1604 b b help
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001605
1606 optional arguments:
1607 -h, --help show this help message and exit
1608 --foo foo help
1609
1610 >>> parser.parse_args(['a', '--help'])
1611 usage: PROG a [-h] bar
1612
1613 positional arguments:
1614 bar bar help
1615
1616 optional arguments:
1617 -h, --help show this help message and exit
1618
1619 >>> parser.parse_args(['b', '--help'])
1620 usage: PROG b [-h] [--baz {X,Y,Z}]
1621
1622 optional arguments:
1623 -h, --help show this help message and exit
1624 --baz {X,Y,Z} baz help
1625
1626 The :meth:`add_subparsers` method also supports ``title`` and ``description``
1627 keyword arguments. When either is present, the subparser's commands will
1628 appear in their own group in the help output. For example::
1629
1630 >>> parser = argparse.ArgumentParser()
1631 >>> subparsers = parser.add_subparsers(title='subcommands',
1632 ... description='valid subcommands',
1633 ... help='additional help')
1634 >>> subparsers.add_parser('foo')
1635 >>> subparsers.add_parser('bar')
1636 >>> parser.parse_args(['-h'])
1637 usage: [-h] {foo,bar} ...
1638
1639 optional arguments:
1640 -h, --help show this help message and exit
1641
1642 subcommands:
1643 valid subcommands
1644
1645 {foo,bar} additional help
1646
Steven Bethardfd311a72010-12-18 11:19:23 +00001647 Furthermore, ``add_parser`` supports an additional ``aliases`` argument,
1648 which allows multiple strings to refer to the same subparser. This example,
1649 like ``svn``, aliases ``co`` as a shorthand for ``checkout``::
1650
1651 >>> parser = argparse.ArgumentParser()
1652 >>> subparsers = parser.add_subparsers()
1653 >>> checkout = subparsers.add_parser('checkout', aliases=['co'])
1654 >>> checkout.add_argument('foo')
1655 >>> parser.parse_args(['co', 'bar'])
1656 Namespace(foo='bar')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001657
1658 One particularly effective way of handling sub-commands is to combine the use
1659 of the :meth:`add_subparsers` method with calls to :meth:`set_defaults` so
1660 that each subparser knows which Python function it should execute. For
1661 example::
1662
1663 >>> # sub-command functions
1664 >>> def foo(args):
Benjamin Petersonb2deb112010-03-03 02:09:18 +00001665 ... print(args.x * args.y)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001666 ...
1667 >>> def bar(args):
Benjamin Petersonb2deb112010-03-03 02:09:18 +00001668 ... print('((%s))' % args.z)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001669 ...
1670 >>> # create the top-level parser
1671 >>> parser = argparse.ArgumentParser()
1672 >>> subparsers = parser.add_subparsers()
1673 >>>
1674 >>> # create the parser for the "foo" command
1675 >>> parser_foo = subparsers.add_parser('foo')
1676 >>> parser_foo.add_argument('-x', type=int, default=1)
1677 >>> parser_foo.add_argument('y', type=float)
1678 >>> parser_foo.set_defaults(func=foo)
1679 >>>
1680 >>> # create the parser for the "bar" command
1681 >>> parser_bar = subparsers.add_parser('bar')
1682 >>> parser_bar.add_argument('z')
1683 >>> parser_bar.set_defaults(func=bar)
1684 >>>
1685 >>> # parse the args and call whatever function was selected
1686 >>> args = parser.parse_args('foo 1 -x 2'.split())
1687 >>> args.func(args)
1688 2.0
1689 >>>
1690 >>> # parse the args and call whatever function was selected
1691 >>> args = parser.parse_args('bar XYZYX'.split())
1692 >>> args.func(args)
1693 ((XYZYX))
1694
Steven Bethardfd311a72010-12-18 11:19:23 +00001695 This way, you can let :meth:`parse_args` do the job of calling the
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001696 appropriate function after argument parsing is complete. Associating
1697 functions with actions like this is typically the easiest way to handle the
1698 different actions for each of your subparsers. However, if it is necessary
1699 to check the name of the subparser that was invoked, the ``dest`` keyword
1700 argument to the :meth:`add_subparsers` call will work::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001701
1702 >>> parser = argparse.ArgumentParser()
1703 >>> subparsers = parser.add_subparsers(dest='subparser_name')
1704 >>> subparser1 = subparsers.add_parser('1')
1705 >>> subparser1.add_argument('-x')
1706 >>> subparser2 = subparsers.add_parser('2')
1707 >>> subparser2.add_argument('y')
1708 >>> parser.parse_args(['2', 'frobble'])
1709 Namespace(subparser_name='2', y='frobble')
1710
1711
1712FileType objects
1713^^^^^^^^^^^^^^^^
1714
Petri Lehtinen74d6c252012-12-15 22:39:32 +02001715.. class:: FileType(mode='r', bufsize=-1, encoding=None, errors=None)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001716
1717 The :class:`FileType` factory creates objects that can be passed to the type
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001718 argument of :meth:`ArgumentParser.add_argument`. Arguments that have
Petri Lehtinen74d6c252012-12-15 22:39:32 +02001719 :class:`FileType` objects as their type will open command-line arguments as
1720 files with the requested modes, buffer sizes, encodings and error handling
1721 (see the :func:`open` function for more details)::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001722
Éric Araujoc3ef0372012-02-20 01:44:55 +01001723 >>> parser = argparse.ArgumentParser()
Petri Lehtinen74d6c252012-12-15 22:39:32 +02001724 >>> parser.add_argument('--raw', type=argparse.FileType('wb', 0))
1725 >>> parser.add_argument('out', type=argparse.FileType('w', encoding='UTF-8'))
1726 >>> parser.parse_args(['--raw', 'raw.dat', 'file.txt'])
1727 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 +00001728
1729 FileType objects understand the pseudo-argument ``'-'`` and automatically
1730 convert this into ``sys.stdin`` for readable :class:`FileType` objects and
Éric Araujoc3ef0372012-02-20 01:44:55 +01001731 ``sys.stdout`` for writable :class:`FileType` objects::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001732
Éric Araujoc3ef0372012-02-20 01:44:55 +01001733 >>> parser = argparse.ArgumentParser()
1734 >>> parser.add_argument('infile', type=argparse.FileType('r'))
1735 >>> parser.parse_args(['-'])
1736 Namespace(infile=<_io.TextIOWrapper name='<stdin>' encoding='UTF-8'>)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001737
R David Murrayfced3ec2013-12-31 11:18:01 -05001738 .. versionadded:: 3.4
1739 The *encodings* and *errors* keyword arguments.
1740
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001741
1742Argument groups
1743^^^^^^^^^^^^^^^
1744
Georg Brandle0bf91d2010-10-17 10:34:28 +00001745.. method:: ArgumentParser.add_argument_group(title=None, description=None)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001746
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001747 By default, :class:`ArgumentParser` groups command-line arguments into
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001748 "positional arguments" and "optional arguments" when displaying help
1749 messages. When there is a better conceptual grouping of arguments than this
1750 default one, appropriate groups can be created using the
1751 :meth:`add_argument_group` method::
1752
1753 >>> parser = argparse.ArgumentParser(prog='PROG', add_help=False)
1754 >>> group = parser.add_argument_group('group')
1755 >>> group.add_argument('--foo', help='foo help')
1756 >>> group.add_argument('bar', help='bar help')
1757 >>> parser.print_help()
1758 usage: PROG [--foo FOO] bar
1759
1760 group:
1761 bar bar help
1762 --foo FOO foo help
1763
1764 The :meth:`add_argument_group` method returns an argument group object which
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001765 has an :meth:`~ArgumentParser.add_argument` method just like a regular
1766 :class:`ArgumentParser`. When an argument is added to the group, the parser
1767 treats it just like a normal argument, but displays the argument in a
1768 separate group for help messages. The :meth:`add_argument_group` method
Georg Brandle0bf91d2010-10-17 10:34:28 +00001769 accepts *title* and *description* arguments which can be used to
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001770 customize this display::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001771
1772 >>> parser = argparse.ArgumentParser(prog='PROG', add_help=False)
1773 >>> group1 = parser.add_argument_group('group1', 'group1 description')
1774 >>> group1.add_argument('foo', help='foo help')
1775 >>> group2 = parser.add_argument_group('group2', 'group2 description')
1776 >>> group2.add_argument('--bar', help='bar help')
1777 >>> parser.print_help()
1778 usage: PROG [--bar BAR] foo
1779
1780 group1:
1781 group1 description
1782
1783 foo foo help
1784
1785 group2:
1786 group2 description
1787
1788 --bar BAR bar help
1789
Sandro Tosi99e7d072012-03-26 19:36:23 +02001790 Note that any arguments not in your user-defined groups will end up back
1791 in the usual "positional arguments" and "optional arguments" sections.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001792
1793
1794Mutual exclusion
1795^^^^^^^^^^^^^^^^
1796
Georg Brandled86ff82013-10-06 13:09:59 +02001797.. method:: ArgumentParser.add_mutually_exclusive_group(required=False)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001798
Ezio Melotti0ee9c1b2011-04-21 16:12:17 +03001799 Create a mutually exclusive group. :mod:`argparse` will make sure that only
1800 one of the arguments in the mutually exclusive group was present on the
1801 command line::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001802
1803 >>> parser = argparse.ArgumentParser(prog='PROG')
1804 >>> group = parser.add_mutually_exclusive_group()
1805 >>> group.add_argument('--foo', action='store_true')
1806 >>> group.add_argument('--bar', action='store_false')
1807 >>> parser.parse_args(['--foo'])
1808 Namespace(bar=True, foo=True)
1809 >>> parser.parse_args(['--bar'])
1810 Namespace(bar=False, foo=False)
1811 >>> parser.parse_args(['--foo', '--bar'])
1812 usage: PROG [-h] [--foo | --bar]
1813 PROG: error: argument --bar: not allowed with argument --foo
1814
Georg Brandle0bf91d2010-10-17 10:34:28 +00001815 The :meth:`add_mutually_exclusive_group` method also accepts a *required*
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001816 argument, to indicate that at least one of the mutually exclusive arguments
1817 is required::
1818
1819 >>> parser = argparse.ArgumentParser(prog='PROG')
1820 >>> group = parser.add_mutually_exclusive_group(required=True)
1821 >>> group.add_argument('--foo', action='store_true')
1822 >>> group.add_argument('--bar', action='store_false')
1823 >>> parser.parse_args([])
1824 usage: PROG [-h] (--foo | --bar)
1825 PROG: error: one of the arguments --foo --bar is required
1826
1827 Note that currently mutually exclusive argument groups do not support the
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001828 *title* and *description* arguments of
1829 :meth:`~ArgumentParser.add_argument_group`.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001830
1831
1832Parser defaults
1833^^^^^^^^^^^^^^^
1834
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001835.. method:: ArgumentParser.set_defaults(**kwargs)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001836
1837 Most of the time, the attributes of the object returned by :meth:`parse_args`
Éric Araujod9d7bca2011-08-10 04:19:03 +02001838 will be fully determined by inspecting the command-line arguments and the argument
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001839 actions. :meth:`set_defaults` allows some additional
Georg Brandl69518bc2011-04-16 16:44:54 +02001840 attributes that are determined without any inspection of the command line to
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001841 be added::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001842
1843 >>> parser = argparse.ArgumentParser()
1844 >>> parser.add_argument('foo', type=int)
1845 >>> parser.set_defaults(bar=42, baz='badger')
1846 >>> parser.parse_args(['736'])
1847 Namespace(bar=42, baz='badger', foo=736)
1848
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001849 Note that parser-level defaults always override argument-level defaults::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001850
1851 >>> parser = argparse.ArgumentParser()
1852 >>> parser.add_argument('--foo', default='bar')
1853 >>> parser.set_defaults(foo='spam')
1854 >>> parser.parse_args([])
1855 Namespace(foo='spam')
1856
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001857 Parser-level defaults can be particularly useful when working with multiple
1858 parsers. See the :meth:`~ArgumentParser.add_subparsers` method for an
1859 example of this type.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001860
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001861.. method:: ArgumentParser.get_default(dest)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001862
1863 Get the default value for a namespace attribute, as set by either
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001864 :meth:`~ArgumentParser.add_argument` or by
1865 :meth:`~ArgumentParser.set_defaults`::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001866
1867 >>> parser = argparse.ArgumentParser()
1868 >>> parser.add_argument('--foo', default='badger')
1869 >>> parser.get_default('foo')
1870 'badger'
1871
1872
1873Printing help
1874^^^^^^^^^^^^^
1875
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001876In most typical applications, :meth:`~ArgumentParser.parse_args` will take
1877care of formatting and printing any usage or error messages. However, several
1878formatting methods are available:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001879
Georg Brandle0bf91d2010-10-17 10:34:28 +00001880.. method:: ArgumentParser.print_usage(file=None)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001881
1882 Print a brief description of how the :class:`ArgumentParser` should be
R. David Murray32e17712010-12-18 16:39:06 +00001883 invoked on the command line. If *file* is ``None``, :data:`sys.stdout` is
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001884 assumed.
1885
Georg Brandle0bf91d2010-10-17 10:34:28 +00001886.. method:: ArgumentParser.print_help(file=None)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001887
1888 Print a help message, including the program usage and information about the
Georg Brandle0bf91d2010-10-17 10:34:28 +00001889 arguments registered with the :class:`ArgumentParser`. If *file* is
R. David Murray32e17712010-12-18 16:39:06 +00001890 ``None``, :data:`sys.stdout` is assumed.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001891
1892There are also variants of these methods that simply return a string instead of
1893printing it:
1894
Georg Brandle0bf91d2010-10-17 10:34:28 +00001895.. method:: ArgumentParser.format_usage()
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001896
1897 Return a string containing a brief description of how the
1898 :class:`ArgumentParser` should be invoked on the command line.
1899
Georg Brandle0bf91d2010-10-17 10:34:28 +00001900.. method:: ArgumentParser.format_help()
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001901
1902 Return a string containing a help message, including the program usage and
1903 information about the arguments registered with the :class:`ArgumentParser`.
1904
1905
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001906Partial parsing
1907^^^^^^^^^^^^^^^
1908
Georg Brandle0bf91d2010-10-17 10:34:28 +00001909.. method:: ArgumentParser.parse_known_args(args=None, namespace=None)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001910
Georg Brandl69518bc2011-04-16 16:44:54 +02001911Sometimes a script may only parse a few of the command-line arguments, passing
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001912the remaining arguments on to another script or program. In these cases, the
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001913:meth:`~ArgumentParser.parse_known_args` method can be useful. It works much like
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001914:meth:`~ArgumentParser.parse_args` except that it does not produce an error when
1915extra arguments are present. Instead, it returns a two item tuple containing
1916the populated namespace and the list of remaining argument strings.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001917
1918::
1919
1920 >>> parser = argparse.ArgumentParser()
1921 >>> parser.add_argument('--foo', action='store_true')
1922 >>> parser.add_argument('bar')
1923 >>> parser.parse_known_args(['--foo', '--badger', 'BAR', 'spam'])
1924 (Namespace(bar='BAR', foo=True), ['--badger', 'spam'])
1925
Eli Benderskyf3114532013-12-02 05:49:54 -08001926.. warning::
1927 :ref:`Prefix matching <prefix-matching>` rules apply to
1928 :meth:`parse_known_args`. The parser may consume an option even if it's just
1929 a prefix of one of its known options, instead of leaving it in the remaining
1930 arguments list.
1931
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001932
1933Customizing file parsing
1934^^^^^^^^^^^^^^^^^^^^^^^^
1935
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001936.. method:: ArgumentParser.convert_arg_line_to_args(arg_line)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001937
Georg Brandle0bf91d2010-10-17 10:34:28 +00001938 Arguments that are read from a file (see the *fromfile_prefix_chars*
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001939 keyword argument to the :class:`ArgumentParser` constructor) are read one
Donald Stufft8b852f12014-05-20 12:58:38 -04001940 argument per line. :meth:`convert_arg_line_to_args` can be overridden for
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001941 fancier reading.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001942
Georg Brandle0bf91d2010-10-17 10:34:28 +00001943 This method takes a single argument *arg_line* which is a string read from
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001944 the argument file. It returns a list of arguments parsed from this string.
1945 The method is called once per line read from the argument file, in order.
1946
1947 A useful override of this method is one that treats each space-separated word
1948 as an argument::
1949
1950 def convert_arg_line_to_args(self, arg_line):
Berker Peksag8c99a6d2015-04-26 12:09:54 +03001951 return arg_line.split()
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001952
1953
Georg Brandl93754922010-10-17 10:28:04 +00001954Exiting methods
1955^^^^^^^^^^^^^^^
1956
1957.. method:: ArgumentParser.exit(status=0, message=None)
1958
1959 This method terminates the program, exiting with the specified *status*
1960 and, if given, it prints a *message* before that.
1961
1962.. method:: ArgumentParser.error(message)
1963
1964 This method prints a usage message including the *message* to the
Senthil Kumaran86a1a892011-08-03 07:42:18 +08001965 standard error and terminates the program with a status code of 2.
Georg Brandl93754922010-10-17 10:28:04 +00001966
Raymond Hettinger677e10a2010-12-07 06:45:30 +00001967.. _upgrading-optparse-code:
Georg Brandl93754922010-10-17 10:28:04 +00001968
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001969Upgrading optparse code
1970-----------------------
1971
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001972Originally, the :mod:`argparse` module had attempted to maintain compatibility
Ezio Melotti0ee9c1b2011-04-21 16:12:17 +03001973with :mod:`optparse`. However, :mod:`optparse` was difficult to extend
1974transparently, particularly with the changes required to support the new
1975``nargs=`` specifiers and better usage messages. When most everything in
1976:mod:`optparse` had either been copy-pasted over or monkey-patched, it no
1977longer seemed practical to try to maintain the backwards compatibility.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001978
Berker Peksag6c1f0ad2014-09-26 15:34:26 +03001979The :mod:`argparse` module improves on the standard library :mod:`optparse`
1980module in a number of ways including:
1981
1982* Handling positional arguments.
1983* Supporting sub-commands.
1984* Allowing alternative option prefixes like ``+`` and ``/``.
1985* Handling zero-or-more and one-or-more style arguments.
1986* Producing more informative usage messages.
1987* Providing a much simpler interface for custom ``type`` and ``action``.
1988
Ezio Melotti0ee9c1b2011-04-21 16:12:17 +03001989A partial upgrade path from :mod:`optparse` to :mod:`argparse`:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001990
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001991* Replace all :meth:`optparse.OptionParser.add_option` calls with
1992 :meth:`ArgumentParser.add_argument` calls.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001993
R David Murray5e0c5712012-03-30 18:07:42 -04001994* Replace ``(options, args) = parser.parse_args()`` with ``args =
Georg Brandlc9007082011-01-09 09:04:08 +00001995 parser.parse_args()`` and add additional :meth:`ArgumentParser.add_argument`
R David Murray5e0c5712012-03-30 18:07:42 -04001996 calls for the positional arguments. Keep in mind that what was previously
1997 called ``options``, now in :mod:`argparse` context is called ``args``.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001998
1999* Replace callback actions and the ``callback_*`` keyword arguments with
2000 ``type`` or ``action`` arguments.
2001
2002* Replace string names for ``type`` keyword arguments with the corresponding
2003 type objects (e.g. int, float, complex, etc).
2004
Benjamin Peterson98047eb2010-03-03 02:07:08 +00002005* Replace :class:`optparse.Values` with :class:`Namespace` and
2006 :exc:`optparse.OptionError` and :exc:`optparse.OptionValueError` with
2007 :exc:`ArgumentError`.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002008
2009* Replace strings with implicit arguments such as ``%default`` or ``%prog`` with
Ezio Melotticca4ef82011-04-21 15:26:46 +03002010 the standard Python syntax to use dictionaries to format strings, that is,
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002011 ``%(default)s`` and ``%(prog)s``.
Steven Bethard59710962010-05-24 03:21:08 +00002012
2013* Replace the OptionParser constructor ``version`` argument with a call to
2014 ``parser.add_argument('--version', action='version', version='<the version>')``