blob: 4203e8bead3063602770f1897a73cc989ca1359d [file] [log] [blame]
Georg Brandl69518bc2011-04-16 16:44:54 +02001:mod:`argparse` --- Parser for command-line options, arguments and sub-commands
Georg Brandle0bf91d2010-10-17 10:34:28 +00002===============================================================================
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003
4.. module:: argparse
Éric Araujod9d7bca2011-08-10 04:19:03 +02005 :synopsis: Command-line option and argument parsing library.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00006.. moduleauthor:: Steven Bethard <steven.bethard@gmail.com>
Benjamin Peterson698a18a2010-03-02 22:34:37 +00007.. sectionauthor:: Steven Bethard <steven.bethard@gmail.com>
8
Raymond Hettingera1993682011-01-27 01:20:32 +00009.. versionadded:: 3.2
10
Éric Araujo19f9b712011-08-19 00:49:18 +020011**Source code:** :source:`Lib/argparse.py`
12
Raymond Hettingera1993682011-01-27 01:20:32 +000013--------------
Benjamin Peterson698a18a2010-03-02 22:34:37 +000014
Ezio Melotti6cc7a412012-05-06 16:15:35 +030015.. sidebar:: Tutorial
16
17 This page contains the API reference information. For a more gentle
18 introduction to Python command-line parsing, have a look at the
19 :ref:`argparse tutorial <argparse-tutorial>`.
20
Ezio Melotti2409d772011-04-16 23:13:50 +030021The :mod:`argparse` module makes it easy to write user-friendly command-line
Benjamin Peterson98047eb2010-03-03 02:07:08 +000022interfaces. The program defines what arguments it requires, and :mod:`argparse`
Benjamin Peterson698a18a2010-03-02 22:34:37 +000023will figure out how to parse those out of :data:`sys.argv`. The :mod:`argparse`
Benjamin Peterson98047eb2010-03-03 02:07:08 +000024module also automatically generates help and usage messages and issues errors
25when users give the program invalid arguments.
Benjamin Peterson698a18a2010-03-02 22:34:37 +000026
Georg Brandle0bf91d2010-10-17 10:34:28 +000027
Benjamin Peterson698a18a2010-03-02 22:34:37 +000028Example
29-------
30
Benjamin Peterson98047eb2010-03-03 02:07:08 +000031The following code is a Python program that takes a list of integers and
32produces either the sum or the max::
Benjamin Peterson698a18a2010-03-02 22:34:37 +000033
34 import argparse
35
36 parser = argparse.ArgumentParser(description='Process some integers.')
37 parser.add_argument('integers', metavar='N', type=int, nargs='+',
38 help='an integer for the accumulator')
39 parser.add_argument('--sum', dest='accumulate', action='store_const',
40 const=sum, default=max,
41 help='sum the integers (default: find the max)')
42
43 args = parser.parse_args()
Benjamin Petersonb2deb112010-03-03 02:09:18 +000044 print(args.accumulate(args.integers))
Benjamin Peterson698a18a2010-03-02 22:34:37 +000045
46Assuming the Python code above is saved into a file called ``prog.py``, it can
47be run at the command line and provides useful help messages::
48
49 $ prog.py -h
50 usage: prog.py [-h] [--sum] N [N ...]
51
52 Process some integers.
53
54 positional arguments:
55 N an integer for the accumulator
56
57 optional arguments:
58 -h, --help show this help message and exit
59 --sum sum the integers (default: find the max)
60
61When run with the appropriate arguments, it prints either the sum or the max of
62the command-line integers::
63
64 $ prog.py 1 2 3 4
65 4
66
67 $ prog.py 1 2 3 4 --sum
68 10
69
70If invalid arguments are passed in, it will issue an error::
71
72 $ prog.py a b c
73 usage: prog.py [-h] [--sum] N [N ...]
74 prog.py: error: argument N: invalid int value: 'a'
75
76The following sections walk you through this example.
77
Georg Brandle0bf91d2010-10-17 10:34:28 +000078
Benjamin Peterson698a18a2010-03-02 22:34:37 +000079Creating a parser
80^^^^^^^^^^^^^^^^^
81
Benjamin Peterson2614cda2010-03-21 22:36:19 +000082The first step in using the :mod:`argparse` is creating an
Benjamin Peterson98047eb2010-03-03 02:07:08 +000083:class:`ArgumentParser` object::
Benjamin Peterson698a18a2010-03-02 22:34:37 +000084
85 >>> parser = argparse.ArgumentParser(description='Process some integers.')
86
87The :class:`ArgumentParser` object will hold all the information necessary to
Ezio Melotticca4ef82011-04-21 15:26:46 +030088parse the command line into Python data types.
Benjamin Peterson698a18a2010-03-02 22:34:37 +000089
90
91Adding arguments
92^^^^^^^^^^^^^^^^
93
Benjamin Peterson98047eb2010-03-03 02:07:08 +000094Filling an :class:`ArgumentParser` with information about program arguments is
95done by making calls to the :meth:`~ArgumentParser.add_argument` method.
96Generally, these calls tell the :class:`ArgumentParser` how to take the strings
97on the command line and turn them into objects. This information is stored and
98used when :meth:`~ArgumentParser.parse_args` is called. For example::
Benjamin Peterson698a18a2010-03-02 22:34:37 +000099
100 >>> parser.add_argument('integers', metavar='N', type=int, nargs='+',
101 ... help='an integer for the accumulator')
102 >>> parser.add_argument('--sum', dest='accumulate', action='store_const',
103 ... const=sum, default=max,
104 ... help='sum the integers (default: find the max)')
105
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300106Later, calling :meth:`~ArgumentParser.parse_args` will return an object with
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000107two attributes, ``integers`` and ``accumulate``. The ``integers`` attribute
108will be a list of one or more ints, and the ``accumulate`` attribute will be
109either the :func:`sum` function, if ``--sum`` was specified at the command line,
110or the :func:`max` function if it was not.
111
Georg Brandle0bf91d2010-10-17 10:34:28 +0000112
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000113Parsing arguments
114^^^^^^^^^^^^^^^^^
115
Éric Araujod9d7bca2011-08-10 04:19:03 +0200116:class:`ArgumentParser` parses arguments through the
Georg Brandl69518bc2011-04-16 16:44:54 +0200117:meth:`~ArgumentParser.parse_args` method. This will inspect the command line,
Éric Araujofde92422011-08-19 01:30:26 +0200118convert each argument to the appropriate type and then invoke the appropriate action.
Éric Araujo63b18a42011-07-29 17:59:17 +0200119In most cases, this means a simple :class:`Namespace` object will be built up from
Georg Brandl69518bc2011-04-16 16:44:54 +0200120attributes parsed out of the command line::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000121
122 >>> parser.parse_args(['--sum', '7', '-1', '42'])
123 Namespace(accumulate=<built-in function sum>, integers=[7, -1, 42])
124
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000125In a script, :meth:`~ArgumentParser.parse_args` will typically be called with no
126arguments, and the :class:`ArgumentParser` will automatically determine the
Éric Araujod9d7bca2011-08-10 04:19:03 +0200127command-line arguments from :data:`sys.argv`.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000128
129
130ArgumentParser objects
131----------------------
132
Georg Brandlc9007082011-01-09 09:04:08 +0000133.. class:: ArgumentParser([description], [epilog], [prog], [usage], [add_help], \
134 [argument_default], [parents], [prefix_chars], \
135 [conflict_handler], [formatter_class])
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000136
137 Create a new :class:`ArgumentParser` object. Each parameter has its own more
138 detailed description below, but in short they are:
139
140 * description_ - Text to display before the argument help.
141
142 * epilog_ - Text to display after the argument help.
143
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000144 * add_help_ - Add a -h/--help option to the parser. (default: ``True``)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000145
146 * argument_default_ - Set the global default value for arguments.
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000147 (default: ``None``)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000148
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000149 * parents_ - A list of :class:`ArgumentParser` objects whose arguments should
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000150 also be included.
151
152 * prefix_chars_ - The set of characters that prefix optional arguments.
153 (default: '-')
154
155 * fromfile_prefix_chars_ - The set of characters that prefix files from
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000156 which additional arguments should be read. (default: ``None``)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000157
158 * formatter_class_ - A class for customizing the help output.
159
160 * conflict_handler_ - Usually unnecessary, defines strategy for resolving
161 conflicting optionals.
162
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000163 * prog_ - The name of the program (default:
Éric Araujo37b5f9e2011-09-01 03:19:30 +0200164 ``sys.argv[0]``)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000165
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000166 * usage_ - The string describing the program usage (default: generated)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000167
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000168The following sections describe how each of these are used.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000169
170
171description
172^^^^^^^^^^^
173
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000174Most calls to the :class:`ArgumentParser` constructor will use the
175``description=`` keyword argument. This argument gives a brief description of
176what the program does and how it works. In help messages, the description is
177displayed between the command-line usage string and the help messages for the
178various arguments::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000179
180 >>> parser = argparse.ArgumentParser(description='A foo that bars')
181 >>> parser.print_help()
182 usage: argparse.py [-h]
183
184 A foo that bars
185
186 optional arguments:
187 -h, --help show this help message and exit
188
189By default, the description will be line-wrapped so that it fits within the
190given space. To change this behavior, see the formatter_class_ argument.
191
192
193epilog
194^^^^^^
195
196Some programs like to display additional description of the program after the
197description of the arguments. Such text can be specified using the ``epilog=``
198argument to :class:`ArgumentParser`::
199
200 >>> parser = argparse.ArgumentParser(
201 ... description='A foo that bars',
202 ... epilog="And that's how you'd foo a bar")
203 >>> parser.print_help()
204 usage: argparse.py [-h]
205
206 A foo that bars
207
208 optional arguments:
209 -h, --help show this help message and exit
210
211 And that's how you'd foo a bar
212
213As with the description_ argument, the ``epilog=`` text is by default
214line-wrapped, but this behavior can be adjusted with the formatter_class_
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000215argument to :class:`ArgumentParser`.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000216
217
218add_help
219^^^^^^^^
220
R. David Murray88c49fe2010-08-03 17:56:09 +0000221By default, ArgumentParser objects add an option which simply displays
222the parser's help message. For example, consider a file named
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000223``myprogram.py`` containing the following code::
224
225 import argparse
226 parser = argparse.ArgumentParser()
227 parser.add_argument('--foo', help='foo help')
228 args = parser.parse_args()
229
Georg Brandl884843d2011-04-16 17:02:58 +0200230If ``-h`` or ``--help`` is supplied at the command line, the ArgumentParser
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000231help will be printed::
232
233 $ python myprogram.py --help
234 usage: myprogram.py [-h] [--foo FOO]
235
236 optional arguments:
237 -h, --help show this help message and exit
238 --foo FOO foo help
239
240Occasionally, it may be useful to disable the addition of this help option.
241This can be achieved by passing ``False`` as the ``add_help=`` argument to
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000242:class:`ArgumentParser`::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000243
244 >>> parser = argparse.ArgumentParser(prog='PROG', add_help=False)
245 >>> parser.add_argument('--foo', help='foo help')
246 >>> parser.print_help()
247 usage: PROG [--foo FOO]
248
249 optional arguments:
250 --foo FOO foo help
251
R. David Murray88c49fe2010-08-03 17:56:09 +0000252The help option is typically ``-h/--help``. The exception to this is
Éric Araujo543edbd2011-08-19 01:45:12 +0200253if the ``prefix_chars=`` is specified and does not include ``-``, in
R. David Murray88c49fe2010-08-03 17:56:09 +0000254which case ``-h`` and ``--help`` are not valid options. In
255this case, the first character in ``prefix_chars`` is used to prefix
256the help options::
257
258 >>> parser = argparse.ArgumentParser(prog='PROG', prefix_chars='+/')
259 >>> parser.print_help()
260 usage: PROG [+h]
261
262 optional arguments:
263 +h, ++help show this help message and exit
264
265
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000266prefix_chars
267^^^^^^^^^^^^
268
Éric Araujo543edbd2011-08-19 01:45:12 +0200269Most command-line options will use ``-`` as the prefix, e.g. ``-f/--foo``.
R. David Murray88c49fe2010-08-03 17:56:09 +0000270Parsers that need to support different or additional prefix
271characters, e.g. for options
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000272like ``+f`` or ``/foo``, may specify them using the ``prefix_chars=`` argument
273to the ArgumentParser constructor::
274
275 >>> parser = argparse.ArgumentParser(prog='PROG', prefix_chars='-+')
276 >>> parser.add_argument('+f')
277 >>> parser.add_argument('++bar')
278 >>> parser.parse_args('+f X ++bar Y'.split())
279 Namespace(bar='Y', f='X')
280
281The ``prefix_chars=`` argument defaults to ``'-'``. Supplying a set of
Éric Araujo543edbd2011-08-19 01:45:12 +0200282characters that does not include ``-`` will cause ``-f/--foo`` options to be
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000283disallowed.
284
285
286fromfile_prefix_chars
287^^^^^^^^^^^^^^^^^^^^^
288
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000289Sometimes, for example when dealing with a particularly long argument lists, it
290may make sense to keep the list of arguments in a file rather than typing it out
291at the command line. If the ``fromfile_prefix_chars=`` argument is given to the
292:class:`ArgumentParser` constructor, then arguments that start with any of the
293specified characters will be treated as files, and will be replaced by the
294arguments they contain. For example::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000295
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000296 >>> with open('args.txt', 'w') as fp:
297 ... fp.write('-f\nbar')
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000298 >>> parser = argparse.ArgumentParser(fromfile_prefix_chars='@')
299 >>> parser.add_argument('-f')
300 >>> parser.parse_args(['-f', 'foo', '@args.txt'])
301 Namespace(f='bar')
302
303Arguments read from a file must by default be one per line (but see also
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300304:meth:`~ArgumentParser.convert_arg_line_to_args`) and are treated as if they
305were in the same place as the original file referencing argument on the command
306line. So in the example above, the expression ``['-f', 'foo', '@args.txt']``
307is considered equivalent to the expression ``['-f', 'foo', '-f', 'bar']``.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000308
309The ``fromfile_prefix_chars=`` argument defaults to ``None``, meaning that
310arguments will never be treated as file references.
311
Georg Brandle0bf91d2010-10-17 10:34:28 +0000312
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000313argument_default
314^^^^^^^^^^^^^^^^
315
316Generally, argument defaults are specified either by passing a default to
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300317:meth:`~ArgumentParser.add_argument` or by calling the
318:meth:`~ArgumentParser.set_defaults` methods with a specific set of name-value
319pairs. Sometimes however, it may be useful to specify a single parser-wide
320default for arguments. This can be accomplished by passing the
321``argument_default=`` keyword argument to :class:`ArgumentParser`. For example,
322to globally suppress attribute creation on :meth:`~ArgumentParser.parse_args`
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000323calls, we supply ``argument_default=SUPPRESS``::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000324
325 >>> parser = argparse.ArgumentParser(argument_default=argparse.SUPPRESS)
326 >>> parser.add_argument('--foo')
327 >>> parser.add_argument('bar', nargs='?')
328 >>> parser.parse_args(['--foo', '1', 'BAR'])
329 Namespace(bar='BAR', foo='1')
330 >>> parser.parse_args([])
331 Namespace()
332
333
334parents
335^^^^^^^
336
337Sometimes, several parsers share a common set of arguments. Rather than
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000338repeating the definitions of these arguments, a single parser with all the
339shared arguments and passed to ``parents=`` argument to :class:`ArgumentParser`
340can be used. The ``parents=`` argument takes a list of :class:`ArgumentParser`
341objects, collects all the positional and optional actions from them, and adds
342these actions to the :class:`ArgumentParser` object being constructed::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000343
344 >>> parent_parser = argparse.ArgumentParser(add_help=False)
345 >>> parent_parser.add_argument('--parent', type=int)
346
347 >>> foo_parser = argparse.ArgumentParser(parents=[parent_parser])
348 >>> foo_parser.add_argument('foo')
349 >>> foo_parser.parse_args(['--parent', '2', 'XXX'])
350 Namespace(foo='XXX', parent=2)
351
352 >>> bar_parser = argparse.ArgumentParser(parents=[parent_parser])
353 >>> bar_parser.add_argument('--bar')
354 >>> bar_parser.parse_args(['--bar', 'YYY'])
355 Namespace(bar='YYY', parent=None)
356
357Note that most parent parsers will specify ``add_help=False``. Otherwise, the
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000358:class:`ArgumentParser` will see two ``-h/--help`` options (one in the parent
359and one in the child) and raise an error.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000360
Steven Bethardd186f992011-03-26 21:49:00 +0100361.. note::
362 You must fully initialize the parsers before passing them via ``parents=``.
363 If you change the parent parsers after the child parser, those changes will
364 not be reflected in the child.
365
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000366
367formatter_class
368^^^^^^^^^^^^^^^
369
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000370:class:`ArgumentParser` objects allow the help formatting to be customized by
Ezio Melotti707d1e62011-04-22 01:57:47 +0300371specifying an alternate formatting class. Currently, there are four such
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300372classes:
373
374.. class:: RawDescriptionHelpFormatter
375 RawTextHelpFormatter
376 ArgumentDefaultsHelpFormatter
Ezio Melotti707d1e62011-04-22 01:57:47 +0300377 MetavarTypeHelpFormatter
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000378
Steven Bethard0331e902011-03-26 14:48:04 +0100379:class:`RawDescriptionHelpFormatter` and :class:`RawTextHelpFormatter` give
380more control over how textual descriptions are displayed.
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000381By default, :class:`ArgumentParser` objects line-wrap the description_ and
382epilog_ texts in command-line help messages::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000383
384 >>> parser = argparse.ArgumentParser(
385 ... prog='PROG',
386 ... description='''this description
387 ... was indented weird
388 ... but that is okay''',
389 ... epilog='''
390 ... likewise for this epilog whose whitespace will
391 ... be cleaned up and whose words will be wrapped
392 ... across a couple lines''')
393 >>> parser.print_help()
394 usage: PROG [-h]
395
396 this description was indented weird but that is okay
397
398 optional arguments:
399 -h, --help show this help message and exit
400
401 likewise for this epilog whose whitespace will be cleaned up and whose words
402 will be wrapped across a couple lines
403
Steven Bethard0331e902011-03-26 14:48:04 +0100404Passing :class:`RawDescriptionHelpFormatter` as ``formatter_class=``
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000405indicates that description_ and epilog_ are already correctly formatted and
406should not be line-wrapped::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000407
408 >>> parser = argparse.ArgumentParser(
409 ... prog='PROG',
410 ... formatter_class=argparse.RawDescriptionHelpFormatter,
411 ... description=textwrap.dedent('''\
412 ... Please do not mess up this text!
413 ... --------------------------------
414 ... I have indented it
415 ... exactly the way
416 ... I want it
417 ... '''))
418 >>> parser.print_help()
419 usage: PROG [-h]
420
421 Please do not mess up this text!
422 --------------------------------
423 I have indented it
424 exactly the way
425 I want it
426
427 optional arguments:
428 -h, --help show this help message and exit
429
Steven Bethard0331e902011-03-26 14:48:04 +0100430:class:`RawTextHelpFormatter` maintains whitespace for all sorts of help text,
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000431including argument descriptions.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000432
Steven Bethard0331e902011-03-26 14:48:04 +0100433:class:`ArgumentDefaultsHelpFormatter` automatically adds information about
434default values to each of the argument help messages::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000435
436 >>> parser = argparse.ArgumentParser(
437 ... prog='PROG',
438 ... formatter_class=argparse.ArgumentDefaultsHelpFormatter)
439 >>> parser.add_argument('--foo', type=int, default=42, help='FOO!')
440 >>> parser.add_argument('bar', nargs='*', default=[1, 2, 3], help='BAR!')
441 >>> parser.print_help()
442 usage: PROG [-h] [--foo FOO] [bar [bar ...]]
443
444 positional arguments:
445 bar BAR! (default: [1, 2, 3])
446
447 optional arguments:
448 -h, --help show this help message and exit
449 --foo FOO FOO! (default: 42)
450
Steven Bethard0331e902011-03-26 14:48:04 +0100451:class:`MetavarTypeHelpFormatter` uses the name of the type_ argument for each
Ezio Melottif1064492011-10-19 11:06:26 +0300452argument as the display name for its values (rather than using the dest_
Steven Bethard0331e902011-03-26 14:48:04 +0100453as the regular formatter does)::
454
455 >>> parser = argparse.ArgumentParser(
456 ... prog='PROG',
457 ... formatter_class=argparse.MetavarTypeHelpFormatter)
458 >>> parser.add_argument('--foo', type=int)
459 >>> parser.add_argument('bar', type=float)
460 >>> parser.print_help()
461 usage: PROG [-h] [--foo int] float
462
463 positional arguments:
464 float
465
466 optional arguments:
467 -h, --help show this help message and exit
468 --foo int
469
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000470
471conflict_handler
472^^^^^^^^^^^^^^^^
473
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000474:class:`ArgumentParser` objects do not allow two actions with the same option
475string. By default, :class:`ArgumentParser` objects raises an exception if an
476attempt is made to create an argument with an option string that is already in
477use::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000478
479 >>> parser = argparse.ArgumentParser(prog='PROG')
480 >>> parser.add_argument('-f', '--foo', help='old foo help')
481 >>> parser.add_argument('--foo', help='new foo help')
482 Traceback (most recent call last):
483 ..
484 ArgumentError: argument --foo: conflicting option string(s): --foo
485
486Sometimes (e.g. when using parents_) it may be useful to simply override any
487older arguments with the same option string. To get this behavior, the value
488``'resolve'`` can be supplied to the ``conflict_handler=`` argument of
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000489:class:`ArgumentParser`::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000490
491 >>> parser = argparse.ArgumentParser(prog='PROG', conflict_handler='resolve')
492 >>> parser.add_argument('-f', '--foo', help='old foo help')
493 >>> parser.add_argument('--foo', help='new foo help')
494 >>> parser.print_help()
495 usage: PROG [-h] [-f FOO] [--foo FOO]
496
497 optional arguments:
498 -h, --help show this help message and exit
499 -f FOO old foo help
500 --foo FOO new foo help
501
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000502Note that :class:`ArgumentParser` objects only remove an action if all of its
503option strings are overridden. So, in the example above, the old ``-f/--foo``
504action is retained as the ``-f`` action, because only the ``--foo`` option
505string was overridden.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000506
507
508prog
509^^^^
510
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000511By default, :class:`ArgumentParser` objects uses ``sys.argv[0]`` to determine
512how to display the name of the program in help messages. This default is almost
Ezio Melottif82340d2010-05-27 22:38:16 +0000513always desirable because it will make the help messages match how the program was
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000514invoked on the command line. For example, consider a file named
515``myprogram.py`` with the following code::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000516
517 import argparse
518 parser = argparse.ArgumentParser()
519 parser.add_argument('--foo', help='foo help')
520 args = parser.parse_args()
521
522The help for this program will display ``myprogram.py`` as the program name
523(regardless of where the program was invoked from)::
524
525 $ python myprogram.py --help
526 usage: myprogram.py [-h] [--foo FOO]
527
528 optional arguments:
529 -h, --help show this help message and exit
530 --foo FOO foo help
531 $ cd ..
532 $ python subdir\myprogram.py --help
533 usage: myprogram.py [-h] [--foo FOO]
534
535 optional arguments:
536 -h, --help show this help message and exit
537 --foo FOO foo help
538
539To change this default behavior, another value can be supplied using the
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000540``prog=`` argument to :class:`ArgumentParser`::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000541
542 >>> parser = argparse.ArgumentParser(prog='myprogram')
543 >>> parser.print_help()
544 usage: myprogram [-h]
545
546 optional arguments:
547 -h, --help show this help message and exit
548
549Note that the program name, whether determined from ``sys.argv[0]`` or from the
550``prog=`` argument, is available to help messages using the ``%(prog)s`` format
551specifier.
552
553::
554
555 >>> parser = argparse.ArgumentParser(prog='myprogram')
556 >>> parser.add_argument('--foo', help='foo of the %(prog)s program')
557 >>> parser.print_help()
558 usage: myprogram [-h] [--foo FOO]
559
560 optional arguments:
561 -h, --help show this help message and exit
562 --foo FOO foo of the myprogram program
563
564
565usage
566^^^^^
567
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000568By default, :class:`ArgumentParser` calculates the usage message from the
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000569arguments it contains::
570
571 >>> parser = argparse.ArgumentParser(prog='PROG')
572 >>> parser.add_argument('--foo', nargs='?', help='foo help')
573 >>> parser.add_argument('bar', nargs='+', help='bar help')
574 >>> parser.print_help()
575 usage: PROG [-h] [--foo [FOO]] bar [bar ...]
576
577 positional arguments:
578 bar bar help
579
580 optional arguments:
581 -h, --help show this help message and exit
582 --foo [FOO] foo help
583
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000584The default message can be overridden with the ``usage=`` keyword argument::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000585
586 >>> parser = argparse.ArgumentParser(prog='PROG', usage='%(prog)s [options]')
587 >>> parser.add_argument('--foo', nargs='?', help='foo help')
588 >>> parser.add_argument('bar', nargs='+', help='bar help')
589 >>> parser.print_help()
590 usage: PROG [options]
591
592 positional arguments:
593 bar bar help
594
595 optional arguments:
596 -h, --help show this help message and exit
597 --foo [FOO] foo help
598
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000599The ``%(prog)s`` format specifier is available to fill in the program name in
600your usage messages.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000601
602
603The add_argument() method
604-------------------------
605
Georg Brandlc9007082011-01-09 09:04:08 +0000606.. method:: ArgumentParser.add_argument(name or flags..., [action], [nargs], \
607 [const], [default], [type], [choices], [required], \
608 [help], [metavar], [dest])
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000609
Georg Brandl69518bc2011-04-16 16:44:54 +0200610 Define how a single command-line argument should be parsed. Each parameter
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000611 has its own more detailed description below, but in short they are:
612
613 * `name or flags`_ - Either a name or a list of option strings, e.g. ``foo``
Ezio Melottidca309d2011-04-21 23:09:27 +0300614 or ``-f, --foo``.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000615
616 * action_ - The basic type of action to be taken when this argument is
Georg Brandl69518bc2011-04-16 16:44:54 +0200617 encountered at the command line.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000618
619 * nargs_ - The number of command-line arguments that should be consumed.
620
621 * const_ - A constant value required by some action_ and nargs_ selections.
622
623 * default_ - The value produced if the argument is absent from the
Georg Brandl69518bc2011-04-16 16:44:54 +0200624 command line.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000625
Ezio Melotti2409d772011-04-16 23:13:50 +0300626 * type_ - The type to which the command-line argument should be converted.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000627
628 * choices_ - A container of the allowable values for the argument.
629
630 * required_ - Whether or not the command-line option may be omitted
631 (optionals only).
632
633 * help_ - A brief description of what the argument does.
634
635 * metavar_ - A name for the argument in usage messages.
636
637 * dest_ - The name of the attribute to be added to the object returned by
638 :meth:`parse_args`.
639
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000640The following sections describe how each of these are used.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000641
Georg Brandle0bf91d2010-10-17 10:34:28 +0000642
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000643name or flags
644^^^^^^^^^^^^^
645
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300646The :meth:`~ArgumentParser.add_argument` method must know whether an optional
647argument, like ``-f`` or ``--foo``, or a positional argument, like a list of
648filenames, is expected. The first arguments passed to
649:meth:`~ArgumentParser.add_argument` must therefore be either a series of
650flags, or a simple argument name. For example, an optional argument could
651be created like::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000652
653 >>> parser.add_argument('-f', '--foo')
654
655while a positional argument could be created like::
656
657 >>> parser.add_argument('bar')
658
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300659When :meth:`~ArgumentParser.parse_args` is called, optional arguments will be
660identified by the ``-`` prefix, and the remaining arguments will be assumed to
661be positional::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000662
663 >>> parser = argparse.ArgumentParser(prog='PROG')
664 >>> parser.add_argument('-f', '--foo')
665 >>> parser.add_argument('bar')
666 >>> parser.parse_args(['BAR'])
667 Namespace(bar='BAR', foo=None)
668 >>> parser.parse_args(['BAR', '--foo', 'FOO'])
669 Namespace(bar='BAR', foo='FOO')
670 >>> parser.parse_args(['--foo', 'FOO'])
671 usage: PROG [-h] [-f FOO] bar
672 PROG: error: too few arguments
673
Georg Brandle0bf91d2010-10-17 10:34:28 +0000674
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000675action
676^^^^^^
677
Éric Araujod9d7bca2011-08-10 04:19:03 +0200678:class:`ArgumentParser` objects associate command-line arguments with actions. These
679actions can do just about anything with the command-line arguments associated with
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000680them, though most actions simply add an attribute to the object returned by
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300681:meth:`~ArgumentParser.parse_args`. The ``action`` keyword argument specifies
Éric Araujod9d7bca2011-08-10 04:19:03 +0200682how the command-line arguments should be handled. The supported actions are:
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000683
684* ``'store'`` - This just stores the argument's value. This is the default
Ezio Melotti2f1db7d2011-04-21 23:06:48 +0300685 action. For example::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000686
687 >>> parser = argparse.ArgumentParser()
688 >>> parser.add_argument('--foo')
689 >>> parser.parse_args('--foo 1'.split())
690 Namespace(foo='1')
691
692* ``'store_const'`` - This stores the value specified by the const_ keyword
Ezio Melotti2f1db7d2011-04-21 23:06:48 +0300693 argument. (Note that the const_ keyword argument defaults to the rather
694 unhelpful ``None``.) The ``'store_const'`` action is most commonly used with
695 optional arguments that specify some sort of flag. For example::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000696
697 >>> parser = argparse.ArgumentParser()
698 >>> parser.add_argument('--foo', action='store_const', const=42)
699 >>> parser.parse_args('--foo'.split())
700 Namespace(foo=42)
701
702* ``'store_true'`` and ``'store_false'`` - These store the values ``True`` and
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000703 ``False`` respectively. These are special cases of ``'store_const'``. For
704 example::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000705
706 >>> parser = argparse.ArgumentParser()
707 >>> parser.add_argument('--foo', action='store_true')
708 >>> parser.add_argument('--bar', action='store_false')
709 >>> parser.parse_args('--foo --bar'.split())
710 Namespace(bar=False, foo=True)
711
712* ``'append'`` - This stores a list, and appends each argument value to the
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000713 list. This is useful to allow an option to be specified multiple times.
714 Example usage::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000715
716 >>> parser = argparse.ArgumentParser()
717 >>> parser.add_argument('--foo', action='append')
718 >>> parser.parse_args('--foo 1 --foo 2'.split())
719 Namespace(foo=['1', '2'])
720
721* ``'append_const'`` - This stores a list, and appends the value specified by
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000722 the const_ keyword argument to the list. (Note that the const_ keyword
723 argument defaults to ``None``.) The ``'append_const'`` action is typically
724 useful when multiple arguments need to store constants to the same list. For
725 example::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000726
727 >>> parser = argparse.ArgumentParser()
728 >>> parser.add_argument('--str', dest='types', action='append_const', const=str)
729 >>> parser.add_argument('--int', dest='types', action='append_const', const=int)
730 >>> parser.parse_args('--str --int'.split())
Florent Xicluna74e64952011-10-28 11:21:19 +0200731 Namespace(types=[<class 'str'>, <class 'int'>])
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000732
Sandro Tosi98492a52012-01-04 23:25:04 +0100733* ``'count'`` - This counts the number of times a keyword argument occurs. For
734 example, this is useful for increasing verbosity levels::
735
736 >>> parser = argparse.ArgumentParser()
737 >>> parser.add_argument('--verbose', '-v', action='count')
738 >>> parser.parse_args('-vvv'.split())
739 Namespace(verbose=3)
740
741* ``'help'`` - This prints a complete help message for all the options in the
742 current parser and then exits. By default a help action is automatically
743 added to the parser. See :class:`ArgumentParser` for details of how the
744 output is created.
745
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000746* ``'version'`` - This expects a ``version=`` keyword argument in the
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300747 :meth:`~ArgumentParser.add_argument` call, and prints version information
Éric Araujoc3ef0372012-02-20 01:44:55 +0100748 and exits when invoked::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000749
750 >>> import argparse
751 >>> parser = argparse.ArgumentParser(prog='PROG')
Steven Bethard59710962010-05-24 03:21:08 +0000752 >>> parser.add_argument('--version', action='version', version='%(prog)s 2.0')
753 >>> parser.parse_args(['--version'])
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000754 PROG 2.0
755
756You can also specify an arbitrary action by passing an object that implements
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000757the Action API. The easiest way to do this is to extend
758:class:`argparse.Action`, supplying an appropriate ``__call__`` method. The
759``__call__`` method should accept four parameters:
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000760
761* ``parser`` - The ArgumentParser object which contains this action.
762
Éric Araujo63b18a42011-07-29 17:59:17 +0200763* ``namespace`` - The :class:`Namespace` object that will be returned by
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300764 :meth:`~ArgumentParser.parse_args`. Most actions add an attribute to this
765 object.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000766
Éric Araujod9d7bca2011-08-10 04:19:03 +0200767* ``values`` - The associated command-line arguments, with any type conversions
768 applied. (Type conversions are specified with the type_ keyword argument to
Sandro Tosiee903c52012-08-12 10:49:26 +0200769 :meth:`~ArgumentParser.add_argument`.)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000770
771* ``option_string`` - The option string that was used to invoke this action.
772 The ``option_string`` argument is optional, and will be absent if the action
773 is associated with a positional argument.
774
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000775An example of a custom action::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000776
777 >>> class FooAction(argparse.Action):
778 ... def __call__(self, parser, namespace, values, option_string=None):
Georg Brandl571a9532010-07-26 17:00:20 +0000779 ... print('%r %r %r' % (namespace, values, option_string))
780 ... setattr(namespace, self.dest, values)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000781 ...
782 >>> parser = argparse.ArgumentParser()
783 >>> parser.add_argument('--foo', action=FooAction)
784 >>> parser.add_argument('bar', action=FooAction)
785 >>> args = parser.parse_args('1 --foo 2'.split())
786 Namespace(bar=None, foo=None) '1' None
787 Namespace(bar='1', foo=None) '2' '--foo'
788 >>> args
789 Namespace(bar='1', foo='2')
790
791
792nargs
793^^^^^
794
795ArgumentParser objects usually associate a single command-line argument with a
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000796single action to be taken. The ``nargs`` keyword argument associates a
Ezio Melotti00f53af2011-04-21 22:56:51 +0300797different number of command-line arguments with a single action. The supported
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000798values are:
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000799
Éric Araujoc3ef0372012-02-20 01:44:55 +0100800* ``N`` (an integer). ``N`` arguments from the command line will be gathered
801 together into a list. For example::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000802
Georg Brandl682d7e02010-10-06 10:26:05 +0000803 >>> parser = argparse.ArgumentParser()
804 >>> parser.add_argument('--foo', nargs=2)
805 >>> parser.add_argument('bar', nargs=1)
806 >>> parser.parse_args('c --foo a b'.split())
807 Namespace(bar=['c'], foo=['a', 'b'])
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000808
Georg Brandl682d7e02010-10-06 10:26:05 +0000809 Note that ``nargs=1`` produces a list of one item. This is different from
810 the default, in which the item is produced by itself.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000811
Éric Araujofde92422011-08-19 01:30:26 +0200812* ``'?'``. One argument will be consumed from the command line if possible, and
813 produced as a single item. If no command-line argument is present, the value from
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000814 default_ will be produced. Note that for optional arguments, there is an
815 additional case - the option string is present but not followed by a
Éric Araujofde92422011-08-19 01:30:26 +0200816 command-line argument. In this case the value from const_ will be produced. Some
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000817 examples to illustrate this::
818
819 >>> parser = argparse.ArgumentParser()
820 >>> parser.add_argument('--foo', nargs='?', const='c', default='d')
821 >>> parser.add_argument('bar', nargs='?', default='d')
822 >>> parser.parse_args('XX --foo YY'.split())
823 Namespace(bar='XX', foo='YY')
824 >>> parser.parse_args('XX --foo'.split())
825 Namespace(bar='XX', foo='c')
826 >>> parser.parse_args(''.split())
827 Namespace(bar='d', foo='d')
828
829 One of the more common uses of ``nargs='?'`` is to allow optional input and
830 output files::
831
832 >>> parser = argparse.ArgumentParser()
Georg Brandle0bf91d2010-10-17 10:34:28 +0000833 >>> parser.add_argument('infile', nargs='?', type=argparse.FileType('r'),
834 ... default=sys.stdin)
835 >>> parser.add_argument('outfile', nargs='?', type=argparse.FileType('w'),
836 ... default=sys.stdout)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000837 >>> parser.parse_args(['input.txt', 'output.txt'])
Georg Brandl04536b02011-01-09 09:31:01 +0000838 Namespace(infile=<_io.TextIOWrapper name='input.txt' encoding='UTF-8'>,
839 outfile=<_io.TextIOWrapper name='output.txt' encoding='UTF-8'>)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000840 >>> parser.parse_args([])
Georg Brandl04536b02011-01-09 09:31:01 +0000841 Namespace(infile=<_io.TextIOWrapper name='<stdin>' encoding='UTF-8'>,
842 outfile=<_io.TextIOWrapper name='<stdout>' encoding='UTF-8'>)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000843
Éric Araujod9d7bca2011-08-10 04:19:03 +0200844* ``'*'``. All command-line arguments present are gathered into a list. Note that
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000845 it generally doesn't make much sense to have more than one positional argument
846 with ``nargs='*'``, but multiple optional arguments with ``nargs='*'`` is
847 possible. For example::
848
849 >>> parser = argparse.ArgumentParser()
850 >>> parser.add_argument('--foo', nargs='*')
851 >>> parser.add_argument('--bar', nargs='*')
852 >>> parser.add_argument('baz', nargs='*')
853 >>> parser.parse_args('a b --foo x y --bar 1 2'.split())
854 Namespace(bar=['1', '2'], baz=['a', 'b'], foo=['x', 'y'])
855
856* ``'+'``. Just like ``'*'``, all command-line args present are gathered into a
857 list. Additionally, an error message will be generated if there wasn't at
Éric Araujofde92422011-08-19 01:30:26 +0200858 least one command-line argument present. For example::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000859
860 >>> parser = argparse.ArgumentParser(prog='PROG')
861 >>> parser.add_argument('foo', nargs='+')
862 >>> parser.parse_args('a b'.split())
863 Namespace(foo=['a', 'b'])
864 >>> parser.parse_args(''.split())
865 usage: PROG [-h] foo [foo ...]
866 PROG: error: too few arguments
867
Sandro Tosida8e11a2012-01-19 22:23:00 +0100868* ``argparse.REMAINDER``. All the remaining command-line arguments are gathered
869 into a list. This is commonly useful for command line utilities that dispatch
Éric Araujoc3ef0372012-02-20 01:44:55 +0100870 to other command line utilities::
Sandro Tosi16bd0b42012-01-19 21:59:55 +0100871
872 >>> parser = argparse.ArgumentParser(prog='PROG')
873 >>> parser.add_argument('--foo')
874 >>> parser.add_argument('command')
875 >>> parser.add_argument('args', nargs=argparse.REMAINDER)
Sandro Tosi04676862012-02-19 19:54:00 +0100876 >>> print(parser.parse_args('--foo B cmd --arg1 XX ZZ'.split()))
Sandro Tosida8e11a2012-01-19 22:23:00 +0100877 Namespace(args=['--arg1', 'XX', 'ZZ'], command='cmd', foo='B')
Sandro Tosi16bd0b42012-01-19 21:59:55 +0100878
Éric Araujod9d7bca2011-08-10 04:19:03 +0200879If the ``nargs`` keyword argument is not provided, the number of arguments consumed
Éric Araujofde92422011-08-19 01:30:26 +0200880is determined by the action_. Generally this means a single command-line argument
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000881will be consumed and a single item (not a list) will be produced.
882
883
884const
885^^^^^
886
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300887The ``const`` argument of :meth:`~ArgumentParser.add_argument` is used to hold
888constant values that are not read from the command line but are required for
889the various :class:`ArgumentParser` actions. The two most common uses of it are:
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000890
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300891* When :meth:`~ArgumentParser.add_argument` is called with
892 ``action='store_const'`` or ``action='append_const'``. These actions add the
Éric Araujoc3ef0372012-02-20 01:44:55 +0100893 ``const`` value to one of the attributes of the object returned by
894 :meth:`~ArgumentParser.parse_args`. See the action_ description for examples.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000895
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300896* When :meth:`~ArgumentParser.add_argument` is called with option strings
897 (like ``-f`` or ``--foo``) and ``nargs='?'``. This creates an optional
Éric Araujod9d7bca2011-08-10 04:19:03 +0200898 argument that can be followed by zero or one command-line arguments.
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300899 When parsing the command line, if the option string is encountered with no
Éric Araujofde92422011-08-19 01:30:26 +0200900 command-line argument following it, the value of ``const`` will be assumed instead.
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300901 See the nargs_ description for examples.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000902
903The ``const`` keyword argument defaults to ``None``.
904
905
906default
907^^^^^^^
908
909All optional arguments and some positional arguments may be omitted at the
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300910command line. The ``default`` keyword argument of
911:meth:`~ArgumentParser.add_argument`, whose value defaults to ``None``,
Éric Araujofde92422011-08-19 01:30:26 +0200912specifies what value should be used if the command-line argument is not present.
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300913For optional arguments, the ``default`` value is used when the option string
914was not present at the command line::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000915
916 >>> parser = argparse.ArgumentParser()
917 >>> parser.add_argument('--foo', default=42)
918 >>> parser.parse_args('--foo 2'.split())
919 Namespace(foo='2')
920 >>> parser.parse_args(''.split())
921 Namespace(foo=42)
922
Éric Araujo543edbd2011-08-19 01:45:12 +0200923For positional arguments with nargs_ equal to ``?`` or ``*``, the ``default`` value
Éric Araujofde92422011-08-19 01:30:26 +0200924is used when no command-line argument was present::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000925
926 >>> parser = argparse.ArgumentParser()
927 >>> parser.add_argument('foo', nargs='?', default=42)
928 >>> parser.parse_args('a'.split())
929 Namespace(foo='a')
930 >>> parser.parse_args(''.split())
931 Namespace(foo=42)
932
933
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000934Providing ``default=argparse.SUPPRESS`` causes no attribute to be added if the
935command-line argument was not present.::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000936
937 >>> parser = argparse.ArgumentParser()
938 >>> parser.add_argument('--foo', default=argparse.SUPPRESS)
939 >>> parser.parse_args([])
940 Namespace()
941 >>> parser.parse_args(['--foo', '1'])
942 Namespace(foo='1')
943
944
945type
946^^^^
947
Éric Araujod9d7bca2011-08-10 04:19:03 +0200948By default, :class:`ArgumentParser` objects read command-line arguments in as simple
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300949strings. However, quite often the command-line string should instead be
950interpreted as another type, like a :class:`float` or :class:`int`. The
951``type`` keyword argument of :meth:`~ArgumentParser.add_argument` allows any
Éric Araujod9d7bca2011-08-10 04:19:03 +0200952necessary type-checking and type conversions to be performed. Common built-in
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300953types and functions can be used directly as the value of the ``type`` argument::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000954
955 >>> parser = argparse.ArgumentParser()
956 >>> parser.add_argument('foo', type=int)
Georg Brandl04536b02011-01-09 09:31:01 +0000957 >>> parser.add_argument('bar', type=open)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000958 >>> parser.parse_args('2 temp.txt'.split())
Georg Brandl04536b02011-01-09 09:31:01 +0000959 Namespace(bar=<_io.TextIOWrapper name='temp.txt' encoding='UTF-8'>, foo=2)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000960
961To ease the use of various types of files, the argparse module provides the
962factory FileType which takes the ``mode=`` and ``bufsize=`` arguments of the
Georg Brandl04536b02011-01-09 09:31:01 +0000963:func:`open` function. For example, ``FileType('w')`` can be used to create a
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000964writable file::
965
966 >>> parser = argparse.ArgumentParser()
967 >>> parser.add_argument('bar', type=argparse.FileType('w'))
968 >>> parser.parse_args(['out.txt'])
Georg Brandl04536b02011-01-09 09:31:01 +0000969 Namespace(bar=<_io.TextIOWrapper name='out.txt' encoding='UTF-8'>)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000970
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000971``type=`` can take any callable that takes a single string argument and returns
Éric Araujod9d7bca2011-08-10 04:19:03 +0200972the converted value::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000973
974 >>> def perfect_square(string):
975 ... value = int(string)
976 ... sqrt = math.sqrt(value)
977 ... if sqrt != int(sqrt):
978 ... msg = "%r is not a perfect square" % string
979 ... raise argparse.ArgumentTypeError(msg)
980 ... return value
981 ...
982 >>> parser = argparse.ArgumentParser(prog='PROG')
983 >>> parser.add_argument('foo', type=perfect_square)
984 >>> parser.parse_args('9'.split())
985 Namespace(foo=9)
986 >>> parser.parse_args('7'.split())
987 usage: PROG [-h] foo
988 PROG: error: argument foo: '7' is not a perfect square
989
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000990The choices_ keyword argument may be more convenient for type checkers that
991simply check against a range of values::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000992
993 >>> parser = argparse.ArgumentParser(prog='PROG')
Fred Drake44623062011-03-03 05:27:17 +0000994 >>> parser.add_argument('foo', type=int, choices=range(5, 10))
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000995 >>> parser.parse_args('7'.split())
996 Namespace(foo=7)
997 >>> parser.parse_args('11'.split())
998 usage: PROG [-h] {5,6,7,8,9}
999 PROG: error: argument foo: invalid choice: 11 (choose from 5, 6, 7, 8, 9)
1000
1001See the choices_ section for more details.
1002
1003
1004choices
1005^^^^^^^
1006
Éric Araujod9d7bca2011-08-10 04:19:03 +02001007Some command-line arguments should be selected from a restricted set of values.
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001008These can be handled by passing a container object as the ``choices`` keyword
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001009argument to :meth:`~ArgumentParser.add_argument`. When the command line is
Éric Araujofde92422011-08-19 01:30:26 +02001010parsed, argument values will be checked, and an error message will be displayed if
1011the argument was not one of the acceptable values::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001012
1013 >>> parser = argparse.ArgumentParser(prog='PROG')
1014 >>> parser.add_argument('foo', choices='abc')
1015 >>> parser.parse_args('c'.split())
1016 Namespace(foo='c')
1017 >>> parser.parse_args('X'.split())
1018 usage: PROG [-h] {a,b,c}
1019 PROG: error: argument foo: invalid choice: 'X' (choose from 'a', 'b', 'c')
1020
1021Note that inclusion in the ``choices`` container is checked after any type_
1022conversions have been performed, so the type of the objects in the ``choices``
1023container should match the type_ specified::
1024
1025 >>> parser = argparse.ArgumentParser(prog='PROG')
1026 >>> parser.add_argument('foo', type=complex, choices=[1, 1j])
1027 >>> parser.parse_args('1j'.split())
1028 Namespace(foo=1j)
1029 >>> parser.parse_args('-- -4'.split())
1030 usage: PROG [-h] {1,1j}
1031 PROG: error: argument foo: invalid choice: (-4+0j) (choose from 1, 1j)
1032
1033Any object that supports the ``in`` operator can be passed as the ``choices``
1034value, so :class:`dict` objects, :class:`set` objects, custom containers,
1035etc. are all supported.
1036
1037
1038required
1039^^^^^^^^
1040
Ezio Melotti0ee9c1b2011-04-21 16:12:17 +03001041In general, the :mod:`argparse` module assumes that flags like ``-f`` and ``--bar``
Georg Brandl69518bc2011-04-16 16:44:54 +02001042indicate *optional* arguments, which can always be omitted at the command line.
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001043To make an option *required*, ``True`` can be specified for the ``required=``
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001044keyword argument to :meth:`~ArgumentParser.add_argument`::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001045
1046 >>> parser = argparse.ArgumentParser()
1047 >>> parser.add_argument('--foo', required=True)
1048 >>> parser.parse_args(['--foo', 'BAR'])
1049 Namespace(foo='BAR')
1050 >>> parser.parse_args([])
1051 usage: argparse.py [-h] [--foo FOO]
1052 argparse.py: error: option --foo is required
1053
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001054As the example shows, if an option is marked as ``required``,
1055:meth:`~ArgumentParser.parse_args` will report an error if that option is not
1056present at the command line.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001057
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001058.. note::
1059
1060 Required options are generally considered bad form because users expect
1061 *options* to be *optional*, and thus they should be avoided when possible.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001062
1063
1064help
1065^^^^
1066
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001067The ``help`` value is a string containing a brief description of the argument.
1068When a user requests help (usually by using ``-h`` or ``--help`` at the
Georg Brandl69518bc2011-04-16 16:44:54 +02001069command line), these ``help`` descriptions will be displayed with each
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001070argument::
1071
1072 >>> parser = argparse.ArgumentParser(prog='frobble')
1073 >>> parser.add_argument('--foo', action='store_true',
1074 ... help='foo the bars before frobbling')
1075 >>> parser.add_argument('bar', nargs='+',
1076 ... help='one of the bars to be frobbled')
1077 >>> parser.parse_args('-h'.split())
1078 usage: frobble [-h] [--foo] bar [bar ...]
1079
1080 positional arguments:
1081 bar one of the bars to be frobbled
1082
1083 optional arguments:
1084 -h, --help show this help message and exit
1085 --foo foo the bars before frobbling
1086
1087The ``help`` strings can include various format specifiers to avoid repetition
1088of things like the program name or the argument default_. The available
1089specifiers include the program name, ``%(prog)s`` and most keyword arguments to
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001090:meth:`~ArgumentParser.add_argument`, e.g. ``%(default)s``, ``%(type)s``, etc.::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001091
1092 >>> parser = argparse.ArgumentParser(prog='frobble')
1093 >>> parser.add_argument('bar', nargs='?', type=int, default=42,
1094 ... help='the bar to %(prog)s (default: %(default)s)')
1095 >>> parser.print_help()
1096 usage: frobble [-h] [bar]
1097
1098 positional arguments:
1099 bar the bar to frobble (default: 42)
1100
1101 optional arguments:
1102 -h, --help show this help message and exit
1103
Senthil Kumaranf21804a2012-06-26 14:17:19 +08001104As the help string supports %-formatting, if you want a literal ``%`` to appear
1105in the help string, you must escape it as ``%%``.
1106
Sandro Tosiea320ab2012-01-03 18:37:03 +01001107:mod:`argparse` supports silencing the help entry for certain options, by
1108setting the ``help`` value to ``argparse.SUPPRESS``::
1109
1110 >>> parser = argparse.ArgumentParser(prog='frobble')
1111 >>> parser.add_argument('--foo', help=argparse.SUPPRESS)
1112 >>> parser.print_help()
1113 usage: frobble [-h]
1114
1115 optional arguments:
1116 -h, --help show this help message and exit
1117
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001118
1119metavar
1120^^^^^^^
1121
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001122When :class:`ArgumentParser` generates help messages, it need some way to refer
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001123to each expected argument. By default, ArgumentParser objects use the dest_
1124value as the "name" of each object. By default, for positional argument
1125actions, the dest_ value is used directly, and for optional argument actions,
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001126the dest_ value is uppercased. So, a single positional argument with
Eli Benderskya7795db2011-11-11 10:57:01 +02001127``dest='bar'`` will be referred to as ``bar``. A single
Éric Araujofde92422011-08-19 01:30:26 +02001128optional argument ``--foo`` that should be followed by a single command-line argument
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001129will be referred to as ``FOO``. An example::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001130
1131 >>> parser = argparse.ArgumentParser()
1132 >>> parser.add_argument('--foo')
1133 >>> parser.add_argument('bar')
1134 >>> parser.parse_args('X --foo Y'.split())
1135 Namespace(bar='X', foo='Y')
1136 >>> parser.print_help()
1137 usage: [-h] [--foo FOO] bar
1138
1139 positional arguments:
1140 bar
1141
1142 optional arguments:
1143 -h, --help show this help message and exit
1144 --foo FOO
1145
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001146An alternative name can be specified with ``metavar``::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001147
1148 >>> parser = argparse.ArgumentParser()
1149 >>> parser.add_argument('--foo', metavar='YYY')
1150 >>> parser.add_argument('bar', metavar='XXX')
1151 >>> parser.parse_args('X --foo Y'.split())
1152 Namespace(bar='X', foo='Y')
1153 >>> parser.print_help()
1154 usage: [-h] [--foo YYY] XXX
1155
1156 positional arguments:
1157 XXX
1158
1159 optional arguments:
1160 -h, --help show this help message and exit
1161 --foo YYY
1162
1163Note that ``metavar`` only changes the *displayed* name - the name of the
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001164attribute on the :meth:`~ArgumentParser.parse_args` object is still determined
1165by the dest_ value.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001166
1167Different values of ``nargs`` may cause the metavar to be used multiple times.
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001168Providing a tuple to ``metavar`` specifies a different display for each of the
1169arguments::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001170
1171 >>> parser = argparse.ArgumentParser(prog='PROG')
1172 >>> parser.add_argument('-x', nargs=2)
1173 >>> parser.add_argument('--foo', nargs=2, metavar=('bar', 'baz'))
1174 >>> parser.print_help()
1175 usage: PROG [-h] [-x X X] [--foo bar baz]
1176
1177 optional arguments:
1178 -h, --help show this help message and exit
1179 -x X X
1180 --foo bar baz
1181
1182
1183dest
1184^^^^
1185
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001186Most :class:`ArgumentParser` actions add some value as an attribute of the
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001187object returned by :meth:`~ArgumentParser.parse_args`. The name of this
1188attribute is determined by the ``dest`` keyword argument of
1189:meth:`~ArgumentParser.add_argument`. For positional argument actions,
1190``dest`` is normally supplied as the first argument to
1191:meth:`~ArgumentParser.add_argument`::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001192
1193 >>> parser = argparse.ArgumentParser()
1194 >>> parser.add_argument('bar')
1195 >>> parser.parse_args('XXX'.split())
1196 Namespace(bar='XXX')
1197
1198For optional argument actions, the value of ``dest`` is normally inferred from
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001199the option strings. :class:`ArgumentParser` generates the value of ``dest`` by
Éric Araujo543edbd2011-08-19 01:45:12 +02001200taking the first long option string and stripping away the initial ``--``
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001201string. If no long option strings were supplied, ``dest`` will be derived from
Éric Araujo543edbd2011-08-19 01:45:12 +02001202the first short option string by stripping the initial ``-`` character. Any
1203internal ``-`` characters will be converted to ``_`` characters to make sure
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001204the string is a valid attribute name. The examples below illustrate this
1205behavior::
1206
1207 >>> parser = argparse.ArgumentParser()
1208 >>> parser.add_argument('-f', '--foo-bar', '--foo')
1209 >>> parser.add_argument('-x', '-y')
1210 >>> parser.parse_args('-f 1 -x 2'.split())
1211 Namespace(foo_bar='1', x='2')
1212 >>> parser.parse_args('--foo 1 -y 2'.split())
1213 Namespace(foo_bar='1', x='2')
1214
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001215``dest`` allows a custom attribute name to be provided::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001216
1217 >>> parser = argparse.ArgumentParser()
1218 >>> parser.add_argument('--foo', dest='bar')
1219 >>> parser.parse_args('--foo XXX'.split())
1220 Namespace(bar='XXX')
1221
1222
1223The parse_args() method
1224-----------------------
1225
Georg Brandle0bf91d2010-10-17 10:34:28 +00001226.. method:: ArgumentParser.parse_args(args=None, namespace=None)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001227
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001228 Convert argument strings to objects and assign them as attributes of the
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001229 namespace. Return the populated namespace.
1230
1231 Previous calls to :meth:`add_argument` determine exactly what objects are
1232 created and how they are assigned. See the documentation for
1233 :meth:`add_argument` for details.
1234
Éric Araujofde92422011-08-19 01:30:26 +02001235 By default, the argument strings are taken from :data:`sys.argv`, and a new empty
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001236 :class:`Namespace` object is created for the attributes.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001237
Georg Brandle0bf91d2010-10-17 10:34:28 +00001238
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001239Option value syntax
1240^^^^^^^^^^^^^^^^^^^
1241
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001242The :meth:`~ArgumentParser.parse_args` method supports several ways of
1243specifying the value of an option (if it takes one). In the simplest case, the
1244option and its value are passed as two separate arguments::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001245
1246 >>> parser = argparse.ArgumentParser(prog='PROG')
1247 >>> parser.add_argument('-x')
1248 >>> parser.add_argument('--foo')
1249 >>> parser.parse_args('-x X'.split())
1250 Namespace(foo=None, x='X')
1251 >>> parser.parse_args('--foo FOO'.split())
1252 Namespace(foo='FOO', x=None)
1253
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001254For long options (options with names longer than a single character), the option
Georg Brandl69518bc2011-04-16 16:44:54 +02001255and value can also be passed as a single command-line argument, using ``=`` to
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001256separate them::
1257
1258 >>> parser.parse_args('--foo=FOO'.split())
1259 Namespace(foo='FOO', x=None)
1260
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001261For short options (options only one character long), the option and its value
1262can be concatenated::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001263
1264 >>> parser.parse_args('-xX'.split())
1265 Namespace(foo=None, x='X')
1266
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001267Several short options can be joined together, using only a single ``-`` prefix,
1268as long as only the last option (or none of them) requires a value::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001269
1270 >>> parser = argparse.ArgumentParser(prog='PROG')
1271 >>> parser.add_argument('-x', action='store_true')
1272 >>> parser.add_argument('-y', action='store_true')
1273 >>> parser.add_argument('-z')
1274 >>> parser.parse_args('-xyzZ'.split())
1275 Namespace(x=True, y=True, z='Z')
1276
1277
1278Invalid arguments
1279^^^^^^^^^^^^^^^^^
1280
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001281While parsing the command line, :meth:`~ArgumentParser.parse_args` checks for a
1282variety of errors, including ambiguous options, invalid types, invalid options,
1283wrong number of positional arguments, etc. When it encounters such an error,
1284it exits and prints the error along with a usage message::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001285
1286 >>> parser = argparse.ArgumentParser(prog='PROG')
1287 >>> parser.add_argument('--foo', type=int)
1288 >>> parser.add_argument('bar', nargs='?')
1289
1290 >>> # invalid type
1291 >>> parser.parse_args(['--foo', 'spam'])
1292 usage: PROG [-h] [--foo FOO] [bar]
1293 PROG: error: argument --foo: invalid int value: 'spam'
1294
1295 >>> # invalid option
1296 >>> parser.parse_args(['--bar'])
1297 usage: PROG [-h] [--foo FOO] [bar]
1298 PROG: error: no such option: --bar
1299
1300 >>> # wrong number of arguments
1301 >>> parser.parse_args(['spam', 'badger'])
1302 usage: PROG [-h] [--foo FOO] [bar]
1303 PROG: error: extra arguments found: badger
1304
1305
Éric Araujo543edbd2011-08-19 01:45:12 +02001306Arguments containing ``-``
1307^^^^^^^^^^^^^^^^^^^^^^^^^^
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001308
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001309The :meth:`~ArgumentParser.parse_args` method attempts to give errors whenever
1310the user has clearly made a mistake, but some situations are inherently
Éric Araujo543edbd2011-08-19 01:45:12 +02001311ambiguous. For example, the command-line argument ``-1`` could either be an
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001312attempt to specify an option or an attempt to provide a positional argument.
1313The :meth:`~ArgumentParser.parse_args` method is cautious here: positional
Éric Araujo543edbd2011-08-19 01:45:12 +02001314arguments may only begin with ``-`` if they look like negative numbers and
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001315there are no options in the parser that look like negative numbers::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001316
1317 >>> parser = argparse.ArgumentParser(prog='PROG')
1318 >>> parser.add_argument('-x')
1319 >>> parser.add_argument('foo', nargs='?')
1320
1321 >>> # no negative number options, so -1 is a positional argument
1322 >>> parser.parse_args(['-x', '-1'])
1323 Namespace(foo=None, x='-1')
1324
1325 >>> # no negative number options, so -1 and -5 are positional arguments
1326 >>> parser.parse_args(['-x', '-1', '-5'])
1327 Namespace(foo='-5', x='-1')
1328
1329 >>> parser = argparse.ArgumentParser(prog='PROG')
1330 >>> parser.add_argument('-1', dest='one')
1331 >>> parser.add_argument('foo', nargs='?')
1332
1333 >>> # negative number options present, so -1 is an option
1334 >>> parser.parse_args(['-1', 'X'])
1335 Namespace(foo=None, one='X')
1336
1337 >>> # negative number options present, so -2 is an option
1338 >>> parser.parse_args(['-2'])
1339 usage: PROG [-h] [-1 ONE] [foo]
1340 PROG: error: no such option: -2
1341
1342 >>> # negative number options present, so both -1s are options
1343 >>> parser.parse_args(['-1', '-1'])
1344 usage: PROG [-h] [-1 ONE] [foo]
1345 PROG: error: argument -1: expected one argument
1346
Éric Araujo543edbd2011-08-19 01:45:12 +02001347If you have positional arguments that must begin with ``-`` and don't look
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001348like negative numbers, you can insert the pseudo-argument ``'--'`` which tells
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001349:meth:`~ArgumentParser.parse_args` that everything after that is a positional
1350argument::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001351
1352 >>> parser.parse_args(['--', '-f'])
1353 Namespace(foo='-f', one=None)
1354
1355
1356Argument abbreviations
1357^^^^^^^^^^^^^^^^^^^^^^
1358
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001359The :meth:`~ArgumentParser.parse_args` method allows long options to be
1360abbreviated if the abbreviation is unambiguous::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001361
1362 >>> parser = argparse.ArgumentParser(prog='PROG')
1363 >>> parser.add_argument('-bacon')
1364 >>> parser.add_argument('-badger')
1365 >>> parser.parse_args('-bac MMM'.split())
1366 Namespace(bacon='MMM', badger=None)
1367 >>> parser.parse_args('-bad WOOD'.split())
1368 Namespace(bacon=None, badger='WOOD')
1369 >>> parser.parse_args('-ba BA'.split())
1370 usage: PROG [-h] [-bacon BACON] [-badger BADGER]
1371 PROG: error: ambiguous option: -ba could match -badger, -bacon
1372
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001373An error is produced for arguments that could produce more than one options.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001374
1375
1376Beyond ``sys.argv``
1377^^^^^^^^^^^^^^^^^^^
1378
Éric Araujod9d7bca2011-08-10 04:19:03 +02001379Sometimes it may be useful to have an ArgumentParser parse arguments other than those
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001380of :data:`sys.argv`. This can be accomplished by passing a list of strings to
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001381:meth:`~ArgumentParser.parse_args`. This is useful for testing at the
1382interactive prompt::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001383
1384 >>> parser = argparse.ArgumentParser()
1385 >>> parser.add_argument(
Fred Drake44623062011-03-03 05:27:17 +00001386 ... 'integers', metavar='int', type=int, choices=range(10),
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001387 ... nargs='+', help='an integer in the range 0..9')
1388 >>> parser.add_argument(
1389 ... '--sum', dest='accumulate', action='store_const', const=sum,
1390 ... default=max, help='sum the integers (default: find the max)')
1391 >>> parser.parse_args(['1', '2', '3', '4'])
1392 Namespace(accumulate=<built-in function max>, integers=[1, 2, 3, 4])
1393 >>> parser.parse_args('1 2 3 4 --sum'.split())
1394 Namespace(accumulate=<built-in function sum>, integers=[1, 2, 3, 4])
1395
1396
Steven Bethardd8f2d502011-03-26 19:50:06 +01001397The Namespace object
1398^^^^^^^^^^^^^^^^^^^^
1399
Éric Araujo63b18a42011-07-29 17:59:17 +02001400.. class:: Namespace
1401
1402 Simple class used by default by :meth:`~ArgumentParser.parse_args` to create
1403 an object holding attributes and return it.
1404
1405This class is deliberately simple, just an :class:`object` subclass with a
1406readable string representation. If you prefer to have dict-like view of the
1407attributes, you can use the standard Python idiom, :func:`vars`::
Steven Bethardd8f2d502011-03-26 19:50:06 +01001408
1409 >>> parser = argparse.ArgumentParser()
1410 >>> parser.add_argument('--foo')
1411 >>> args = parser.parse_args(['--foo', 'BAR'])
1412 >>> vars(args)
1413 {'foo': 'BAR'}
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001414
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001415It may also be useful to have an :class:`ArgumentParser` assign attributes to an
Steven Bethardd8f2d502011-03-26 19:50:06 +01001416already existing object, rather than a new :class:`Namespace` object. This can
1417be achieved by specifying the ``namespace=`` keyword argument::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001418
Éric Araujo28053fb2010-11-22 03:09:19 +00001419 >>> class C:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001420 ... pass
1421 ...
1422 >>> c = C()
1423 >>> parser = argparse.ArgumentParser()
1424 >>> parser.add_argument('--foo')
1425 >>> parser.parse_args(args=['--foo', 'BAR'], namespace=c)
1426 >>> c.foo
1427 'BAR'
1428
1429
1430Other utilities
1431---------------
1432
1433Sub-commands
1434^^^^^^^^^^^^
1435
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001436.. method:: ArgumentParser.add_subparsers()
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001437
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001438 Many programs split up their functionality into a number of sub-commands,
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001439 for example, the ``svn`` program can invoke sub-commands like ``svn
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001440 checkout``, ``svn update``, and ``svn commit``. Splitting up functionality
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001441 this way can be a particularly good idea when a program performs several
1442 different functions which require different kinds of command-line arguments.
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001443 :class:`ArgumentParser` supports the creation of such sub-commands with the
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001444 :meth:`add_subparsers` method. The :meth:`add_subparsers` method is normally
1445 called with no arguments and returns an special action object. This object
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001446 has a single method, :meth:`~ArgumentParser.add_parser`, which takes a
1447 command name and any :class:`ArgumentParser` constructor arguments, and
1448 returns an :class:`ArgumentParser` object that can be modified as usual.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001449
1450 Some example usage::
1451
1452 >>> # create the top-level parser
1453 >>> parser = argparse.ArgumentParser(prog='PROG')
1454 >>> parser.add_argument('--foo', action='store_true', help='foo help')
1455 >>> subparsers = parser.add_subparsers(help='sub-command help')
1456 >>>
1457 >>> # create the parser for the "a" command
1458 >>> parser_a = subparsers.add_parser('a', help='a help')
1459 >>> parser_a.add_argument('bar', type=int, help='bar help')
1460 >>>
1461 >>> # create the parser for the "b" command
1462 >>> parser_b = subparsers.add_parser('b', help='b help')
1463 >>> parser_b.add_argument('--baz', choices='XYZ', help='baz help')
1464 >>>
Éric Araujofde92422011-08-19 01:30:26 +02001465 >>> # parse some argument lists
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001466 >>> parser.parse_args(['a', '12'])
1467 Namespace(bar=12, foo=False)
1468 >>> parser.parse_args(['--foo', 'b', '--baz', 'Z'])
1469 Namespace(baz='Z', foo=True)
1470
1471 Note that the object returned by :meth:`parse_args` will only contain
1472 attributes for the main parser and the subparser that was selected by the
1473 command line (and not any other subparsers). So in the example above, when
Éric Araujo543edbd2011-08-19 01:45:12 +02001474 the ``a`` command is specified, only the ``foo`` and ``bar`` attributes are
1475 present, and when the ``b`` command is specified, only the ``foo`` and
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001476 ``baz`` attributes are present.
1477
1478 Similarly, when a help message is requested from a subparser, only the help
1479 for that particular parser will be printed. The help message will not
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001480 include parent parser or sibling parser messages. (A help message for each
1481 subparser command, however, can be given by supplying the ``help=`` argument
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001482 to :meth:`add_parser` as above.)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001483
1484 ::
1485
1486 >>> parser.parse_args(['--help'])
1487 usage: PROG [-h] [--foo] {a,b} ...
1488
1489 positional arguments:
1490 {a,b} sub-command help
1491 a a help
1492 b b help
1493
1494 optional arguments:
1495 -h, --help show this help message and exit
1496 --foo foo help
1497
1498 >>> parser.parse_args(['a', '--help'])
1499 usage: PROG a [-h] bar
1500
1501 positional arguments:
1502 bar bar help
1503
1504 optional arguments:
1505 -h, --help show this help message and exit
1506
1507 >>> parser.parse_args(['b', '--help'])
1508 usage: PROG b [-h] [--baz {X,Y,Z}]
1509
1510 optional arguments:
1511 -h, --help show this help message and exit
1512 --baz {X,Y,Z} baz help
1513
1514 The :meth:`add_subparsers` method also supports ``title`` and ``description``
1515 keyword arguments. When either is present, the subparser's commands will
1516 appear in their own group in the help output. For example::
1517
1518 >>> parser = argparse.ArgumentParser()
1519 >>> subparsers = parser.add_subparsers(title='subcommands',
1520 ... description='valid subcommands',
1521 ... help='additional help')
1522 >>> subparsers.add_parser('foo')
1523 >>> subparsers.add_parser('bar')
1524 >>> parser.parse_args(['-h'])
1525 usage: [-h] {foo,bar} ...
1526
1527 optional arguments:
1528 -h, --help show this help message and exit
1529
1530 subcommands:
1531 valid subcommands
1532
1533 {foo,bar} additional help
1534
Steven Bethardfd311a72010-12-18 11:19:23 +00001535 Furthermore, ``add_parser`` supports an additional ``aliases`` argument,
1536 which allows multiple strings to refer to the same subparser. This example,
1537 like ``svn``, aliases ``co`` as a shorthand for ``checkout``::
1538
1539 >>> parser = argparse.ArgumentParser()
1540 >>> subparsers = parser.add_subparsers()
1541 >>> checkout = subparsers.add_parser('checkout', aliases=['co'])
1542 >>> checkout.add_argument('foo')
1543 >>> parser.parse_args(['co', 'bar'])
1544 Namespace(foo='bar')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001545
1546 One particularly effective way of handling sub-commands is to combine the use
1547 of the :meth:`add_subparsers` method with calls to :meth:`set_defaults` so
1548 that each subparser knows which Python function it should execute. For
1549 example::
1550
1551 >>> # sub-command functions
1552 >>> def foo(args):
Benjamin Petersonb2deb112010-03-03 02:09:18 +00001553 ... print(args.x * args.y)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001554 ...
1555 >>> def bar(args):
Benjamin Petersonb2deb112010-03-03 02:09:18 +00001556 ... print('((%s))' % args.z)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001557 ...
1558 >>> # create the top-level parser
1559 >>> parser = argparse.ArgumentParser()
1560 >>> subparsers = parser.add_subparsers()
1561 >>>
1562 >>> # create the parser for the "foo" command
1563 >>> parser_foo = subparsers.add_parser('foo')
1564 >>> parser_foo.add_argument('-x', type=int, default=1)
1565 >>> parser_foo.add_argument('y', type=float)
1566 >>> parser_foo.set_defaults(func=foo)
1567 >>>
1568 >>> # create the parser for the "bar" command
1569 >>> parser_bar = subparsers.add_parser('bar')
1570 >>> parser_bar.add_argument('z')
1571 >>> parser_bar.set_defaults(func=bar)
1572 >>>
1573 >>> # parse the args and call whatever function was selected
1574 >>> args = parser.parse_args('foo 1 -x 2'.split())
1575 >>> args.func(args)
1576 2.0
1577 >>>
1578 >>> # parse the args and call whatever function was selected
1579 >>> args = parser.parse_args('bar XYZYX'.split())
1580 >>> args.func(args)
1581 ((XYZYX))
1582
Steven Bethardfd311a72010-12-18 11:19:23 +00001583 This way, you can let :meth:`parse_args` do the job of calling the
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001584 appropriate function after argument parsing is complete. Associating
1585 functions with actions like this is typically the easiest way to handle the
1586 different actions for each of your subparsers. However, if it is necessary
1587 to check the name of the subparser that was invoked, the ``dest`` keyword
1588 argument to the :meth:`add_subparsers` call will work::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001589
1590 >>> parser = argparse.ArgumentParser()
1591 >>> subparsers = parser.add_subparsers(dest='subparser_name')
1592 >>> subparser1 = subparsers.add_parser('1')
1593 >>> subparser1.add_argument('-x')
1594 >>> subparser2 = subparsers.add_parser('2')
1595 >>> subparser2.add_argument('y')
1596 >>> parser.parse_args(['2', 'frobble'])
1597 Namespace(subparser_name='2', y='frobble')
1598
1599
1600FileType objects
1601^^^^^^^^^^^^^^^^
1602
1603.. class:: FileType(mode='r', bufsize=None)
1604
1605 The :class:`FileType` factory creates objects that can be passed to the type
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001606 argument of :meth:`ArgumentParser.add_argument`. Arguments that have
Éric Araujod9d7bca2011-08-10 04:19:03 +02001607 :class:`FileType` objects as their type will open command-line arguments as files
Éric Araujoc3ef0372012-02-20 01:44:55 +01001608 with the requested modes and buffer sizes::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001609
Éric Araujoc3ef0372012-02-20 01:44:55 +01001610 >>> parser = argparse.ArgumentParser()
1611 >>> parser.add_argument('--output', type=argparse.FileType('wb', 0))
1612 >>> parser.parse_args(['--output', 'out'])
1613 Namespace(output=<_io.BufferedWriter name='out'>)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001614
1615 FileType objects understand the pseudo-argument ``'-'`` and automatically
1616 convert this into ``sys.stdin`` for readable :class:`FileType` objects and
Éric Araujoc3ef0372012-02-20 01:44:55 +01001617 ``sys.stdout`` for writable :class:`FileType` objects::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001618
Éric Araujoc3ef0372012-02-20 01:44:55 +01001619 >>> parser = argparse.ArgumentParser()
1620 >>> parser.add_argument('infile', type=argparse.FileType('r'))
1621 >>> parser.parse_args(['-'])
1622 Namespace(infile=<_io.TextIOWrapper name='<stdin>' encoding='UTF-8'>)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001623
1624
1625Argument groups
1626^^^^^^^^^^^^^^^
1627
Georg Brandle0bf91d2010-10-17 10:34:28 +00001628.. method:: ArgumentParser.add_argument_group(title=None, description=None)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001629
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001630 By default, :class:`ArgumentParser` groups command-line arguments into
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001631 "positional arguments" and "optional arguments" when displaying help
1632 messages. When there is a better conceptual grouping of arguments than this
1633 default one, appropriate groups can be created using the
1634 :meth:`add_argument_group` method::
1635
1636 >>> parser = argparse.ArgumentParser(prog='PROG', add_help=False)
1637 >>> group = parser.add_argument_group('group')
1638 >>> group.add_argument('--foo', help='foo help')
1639 >>> group.add_argument('bar', help='bar help')
1640 >>> parser.print_help()
1641 usage: PROG [--foo FOO] bar
1642
1643 group:
1644 bar bar help
1645 --foo FOO foo help
1646
1647 The :meth:`add_argument_group` method returns an argument group object which
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001648 has an :meth:`~ArgumentParser.add_argument` method just like a regular
1649 :class:`ArgumentParser`. When an argument is added to the group, the parser
1650 treats it just like a normal argument, but displays the argument in a
1651 separate group for help messages. The :meth:`add_argument_group` method
Georg Brandle0bf91d2010-10-17 10:34:28 +00001652 accepts *title* and *description* arguments which can be used to
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001653 customize this display::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001654
1655 >>> parser = argparse.ArgumentParser(prog='PROG', add_help=False)
1656 >>> group1 = parser.add_argument_group('group1', 'group1 description')
1657 >>> group1.add_argument('foo', help='foo help')
1658 >>> group2 = parser.add_argument_group('group2', 'group2 description')
1659 >>> group2.add_argument('--bar', help='bar help')
1660 >>> parser.print_help()
1661 usage: PROG [--bar BAR] foo
1662
1663 group1:
1664 group1 description
1665
1666 foo foo help
1667
1668 group2:
1669 group2 description
1670
1671 --bar BAR bar help
1672
Sandro Tosi99e7d072012-03-26 19:36:23 +02001673 Note that any arguments not in your user-defined groups will end up back
1674 in the usual "positional arguments" and "optional arguments" sections.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001675
1676
1677Mutual exclusion
1678^^^^^^^^^^^^^^^^
1679
Georg Brandle0bf91d2010-10-17 10:34:28 +00001680.. method:: add_mutually_exclusive_group(required=False)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001681
Ezio Melotti0ee9c1b2011-04-21 16:12:17 +03001682 Create a mutually exclusive group. :mod:`argparse` will make sure that only
1683 one of the arguments in the mutually exclusive group was present on the
1684 command line::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001685
1686 >>> parser = argparse.ArgumentParser(prog='PROG')
1687 >>> group = parser.add_mutually_exclusive_group()
1688 >>> group.add_argument('--foo', action='store_true')
1689 >>> group.add_argument('--bar', action='store_false')
1690 >>> parser.parse_args(['--foo'])
1691 Namespace(bar=True, foo=True)
1692 >>> parser.parse_args(['--bar'])
1693 Namespace(bar=False, foo=False)
1694 >>> parser.parse_args(['--foo', '--bar'])
1695 usage: PROG [-h] [--foo | --bar]
1696 PROG: error: argument --bar: not allowed with argument --foo
1697
Georg Brandle0bf91d2010-10-17 10:34:28 +00001698 The :meth:`add_mutually_exclusive_group` method also accepts a *required*
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001699 argument, to indicate that at least one of the mutually exclusive arguments
1700 is required::
1701
1702 >>> parser = argparse.ArgumentParser(prog='PROG')
1703 >>> group = parser.add_mutually_exclusive_group(required=True)
1704 >>> group.add_argument('--foo', action='store_true')
1705 >>> group.add_argument('--bar', action='store_false')
1706 >>> parser.parse_args([])
1707 usage: PROG [-h] (--foo | --bar)
1708 PROG: error: one of the arguments --foo --bar is required
1709
1710 Note that currently mutually exclusive argument groups do not support the
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001711 *title* and *description* arguments of
1712 :meth:`~ArgumentParser.add_argument_group`.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001713
1714
1715Parser defaults
1716^^^^^^^^^^^^^^^
1717
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001718.. method:: ArgumentParser.set_defaults(**kwargs)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001719
1720 Most of the time, the attributes of the object returned by :meth:`parse_args`
Éric Araujod9d7bca2011-08-10 04:19:03 +02001721 will be fully determined by inspecting the command-line arguments and the argument
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001722 actions. :meth:`set_defaults` allows some additional
Georg Brandl69518bc2011-04-16 16:44:54 +02001723 attributes that are determined without any inspection of the command line to
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001724 be added::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001725
1726 >>> parser = argparse.ArgumentParser()
1727 >>> parser.add_argument('foo', type=int)
1728 >>> parser.set_defaults(bar=42, baz='badger')
1729 >>> parser.parse_args(['736'])
1730 Namespace(bar=42, baz='badger', foo=736)
1731
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001732 Note that parser-level defaults always override argument-level defaults::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001733
1734 >>> parser = argparse.ArgumentParser()
1735 >>> parser.add_argument('--foo', default='bar')
1736 >>> parser.set_defaults(foo='spam')
1737 >>> parser.parse_args([])
1738 Namespace(foo='spam')
1739
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001740 Parser-level defaults can be particularly useful when working with multiple
1741 parsers. See the :meth:`~ArgumentParser.add_subparsers` method for an
1742 example of this type.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001743
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001744.. method:: ArgumentParser.get_default(dest)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001745
1746 Get the default value for a namespace attribute, as set by either
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001747 :meth:`~ArgumentParser.add_argument` or by
1748 :meth:`~ArgumentParser.set_defaults`::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001749
1750 >>> parser = argparse.ArgumentParser()
1751 >>> parser.add_argument('--foo', default='badger')
1752 >>> parser.get_default('foo')
1753 'badger'
1754
1755
1756Printing help
1757^^^^^^^^^^^^^
1758
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001759In most typical applications, :meth:`~ArgumentParser.parse_args` will take
1760care of formatting and printing any usage or error messages. However, several
1761formatting methods are available:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001762
Georg Brandle0bf91d2010-10-17 10:34:28 +00001763.. method:: ArgumentParser.print_usage(file=None)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001764
1765 Print a brief description of how the :class:`ArgumentParser` should be
R. David Murray32e17712010-12-18 16:39:06 +00001766 invoked on the command line. If *file* is ``None``, :data:`sys.stdout` is
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001767 assumed.
1768
Georg Brandle0bf91d2010-10-17 10:34:28 +00001769.. method:: ArgumentParser.print_help(file=None)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001770
1771 Print a help message, including the program usage and information about the
Georg Brandle0bf91d2010-10-17 10:34:28 +00001772 arguments registered with the :class:`ArgumentParser`. If *file* is
R. David Murray32e17712010-12-18 16:39:06 +00001773 ``None``, :data:`sys.stdout` is assumed.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001774
1775There are also variants of these methods that simply return a string instead of
1776printing it:
1777
Georg Brandle0bf91d2010-10-17 10:34:28 +00001778.. method:: ArgumentParser.format_usage()
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001779
1780 Return a string containing a brief description of how the
1781 :class:`ArgumentParser` should be invoked on the command line.
1782
Georg Brandle0bf91d2010-10-17 10:34:28 +00001783.. method:: ArgumentParser.format_help()
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001784
1785 Return a string containing a help message, including the program usage and
1786 information about the arguments registered with the :class:`ArgumentParser`.
1787
1788
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001789Partial parsing
1790^^^^^^^^^^^^^^^
1791
Georg Brandle0bf91d2010-10-17 10:34:28 +00001792.. method:: ArgumentParser.parse_known_args(args=None, namespace=None)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001793
Georg Brandl69518bc2011-04-16 16:44:54 +02001794Sometimes a script may only parse a few of the command-line arguments, passing
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001795the remaining arguments on to another script or program. In these cases, the
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001796:meth:`~ArgumentParser.parse_known_args` method can be useful. It works much like
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001797:meth:`~ArgumentParser.parse_args` except that it does not produce an error when
1798extra arguments are present. Instead, it returns a two item tuple containing
1799the populated namespace and the list of remaining argument strings.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001800
1801::
1802
1803 >>> parser = argparse.ArgumentParser()
1804 >>> parser.add_argument('--foo', action='store_true')
1805 >>> parser.add_argument('bar')
1806 >>> parser.parse_known_args(['--foo', '--badger', 'BAR', 'spam'])
1807 (Namespace(bar='BAR', foo=True), ['--badger', 'spam'])
1808
1809
1810Customizing file parsing
1811^^^^^^^^^^^^^^^^^^^^^^^^
1812
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001813.. method:: ArgumentParser.convert_arg_line_to_args(arg_line)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001814
Georg Brandle0bf91d2010-10-17 10:34:28 +00001815 Arguments that are read from a file (see the *fromfile_prefix_chars*
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001816 keyword argument to the :class:`ArgumentParser` constructor) are read one
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001817 argument per line. :meth:`convert_arg_line_to_args` can be overriden for
1818 fancier reading.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001819
Georg Brandle0bf91d2010-10-17 10:34:28 +00001820 This method takes a single argument *arg_line* which is a string read from
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001821 the argument file. It returns a list of arguments parsed from this string.
1822 The method is called once per line read from the argument file, in order.
1823
1824 A useful override of this method is one that treats each space-separated word
1825 as an argument::
1826
1827 def convert_arg_line_to_args(self, arg_line):
1828 for arg in arg_line.split():
1829 if not arg.strip():
1830 continue
1831 yield arg
1832
1833
Georg Brandl93754922010-10-17 10:28:04 +00001834Exiting methods
1835^^^^^^^^^^^^^^^
1836
1837.. method:: ArgumentParser.exit(status=0, message=None)
1838
1839 This method terminates the program, exiting with the specified *status*
1840 and, if given, it prints a *message* before that.
1841
1842.. method:: ArgumentParser.error(message)
1843
1844 This method prints a usage message including the *message* to the
Senthil Kumaran86a1a892011-08-03 07:42:18 +08001845 standard error and terminates the program with a status code of 2.
Georg Brandl93754922010-10-17 10:28:04 +00001846
Raymond Hettinger677e10a2010-12-07 06:45:30 +00001847.. _upgrading-optparse-code:
Georg Brandl93754922010-10-17 10:28:04 +00001848
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001849Upgrading optparse code
1850-----------------------
1851
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001852Originally, the :mod:`argparse` module had attempted to maintain compatibility
Ezio Melotti0ee9c1b2011-04-21 16:12:17 +03001853with :mod:`optparse`. However, :mod:`optparse` was difficult to extend
1854transparently, particularly with the changes required to support the new
1855``nargs=`` specifiers and better usage messages. When most everything in
1856:mod:`optparse` had either been copy-pasted over or monkey-patched, it no
1857longer seemed practical to try to maintain the backwards compatibility.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001858
Ezio Melotti0ee9c1b2011-04-21 16:12:17 +03001859A partial upgrade path from :mod:`optparse` to :mod:`argparse`:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001860
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001861* Replace all :meth:`optparse.OptionParser.add_option` calls with
1862 :meth:`ArgumentParser.add_argument` calls.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001863
R David Murray5e0c5712012-03-30 18:07:42 -04001864* Replace ``(options, args) = parser.parse_args()`` with ``args =
Georg Brandlc9007082011-01-09 09:04:08 +00001865 parser.parse_args()`` and add additional :meth:`ArgumentParser.add_argument`
R David Murray5e0c5712012-03-30 18:07:42 -04001866 calls for the positional arguments. Keep in mind that what was previously
1867 called ``options``, now in :mod:`argparse` context is called ``args``.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001868
1869* Replace callback actions and the ``callback_*`` keyword arguments with
1870 ``type`` or ``action`` arguments.
1871
1872* Replace string names for ``type`` keyword arguments with the corresponding
1873 type objects (e.g. int, float, complex, etc).
1874
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001875* Replace :class:`optparse.Values` with :class:`Namespace` and
1876 :exc:`optparse.OptionError` and :exc:`optparse.OptionValueError` with
1877 :exc:`ArgumentError`.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001878
1879* Replace strings with implicit arguments such as ``%default`` or ``%prog`` with
Ezio Melotticca4ef82011-04-21 15:26:46 +03001880 the standard Python syntax to use dictionaries to format strings, that is,
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001881 ``%(default)s`` and ``%(prog)s``.
Steven Bethard59710962010-05-24 03:21:08 +00001882
1883* Replace the OptionParser constructor ``version`` argument with a call to
1884 ``parser.add_argument('--version', action='version', version='<the version>')``