blob: 1313e4b1de1d2bc7a9425371243d74c9e06b54b3 [file] [log] [blame]
Georg Brandl1d827ff2011-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 Brandl1d827ff2011-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 Brandl1d827ff2011-04-16 16:44:54 +0200120attributes parsed out of the command line::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000121
122 >>> parser.parse_args(['--sum', '7', '-1', '42'])
123 Namespace(accumulate=<built-in function sum>, integers=[7, -1, 42])
124
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000125In a script, :meth:`~ArgumentParser.parse_args` will typically be called with no
126arguments, and the :class:`ArgumentParser` will automatically determine the
Éric Araujod9d7bca2011-08-10 04:19:03 +0200127command-line arguments from :data:`sys.argv`.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000128
129
130ArgumentParser objects
131----------------------
132
Ezio Melottie0add762012-09-14 06:32:35 +0300133.. class:: ArgumentParser(prog=None, usage=None, description=None, \
134 epilog=None, parents=[], \
135 formatter_class=argparse.HelpFormatter, \
136 prefix_chars='-', fromfile_prefix_chars=None, \
137 argument_default=None, conflict_handler='error', \
138 add_help=True)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000139
140 Create a new :class:`ArgumentParser` object. Each parameter has its own more
141 detailed description below, but in short they are:
142
143 * description_ - Text to display before the argument help.
144
145 * epilog_ - Text to display after the argument help.
146
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000147 * add_help_ - Add a -h/--help option to the parser. (default: ``True``)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000148
149 * argument_default_ - Set the global default value for arguments.
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000150 (default: ``None``)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000151
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000152 * parents_ - A list of :class:`ArgumentParser` objects whose arguments should
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000153 also be included.
154
155 * prefix_chars_ - The set of characters that prefix optional arguments.
156 (default: '-')
157
158 * fromfile_prefix_chars_ - The set of characters that prefix files from
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000159 which additional arguments should be read. (default: ``None``)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000160
161 * formatter_class_ - A class for customizing the help output.
162
163 * conflict_handler_ - Usually unnecessary, defines strategy for resolving
164 conflicting optionals.
165
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000166 * prog_ - The name of the program (default:
Éric Araujo37b5f9e2011-09-01 03:19:30 +0200167 ``sys.argv[0]``)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000168
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000169 * usage_ - The string describing the program usage (default: generated)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000170
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000171The following sections describe how each of these are used.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000172
173
174description
175^^^^^^^^^^^
176
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000177Most calls to the :class:`ArgumentParser` constructor will use the
178``description=`` keyword argument. This argument gives a brief description of
179what the program does and how it works. In help messages, the description is
180displayed between the command-line usage string and the help messages for the
181various arguments::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000182
183 >>> parser = argparse.ArgumentParser(description='A foo that bars')
184 >>> parser.print_help()
185 usage: argparse.py [-h]
186
187 A foo that bars
188
189 optional arguments:
190 -h, --help show this help message and exit
191
192By default, the description will be line-wrapped so that it fits within the
193given space. To change this behavior, see the formatter_class_ argument.
194
195
196epilog
197^^^^^^
198
199Some programs like to display additional description of the program after the
200description of the arguments. Such text can be specified using the ``epilog=``
201argument to :class:`ArgumentParser`::
202
203 >>> parser = argparse.ArgumentParser(
204 ... description='A foo that bars',
205 ... epilog="And that's how you'd foo a bar")
206 >>> parser.print_help()
207 usage: argparse.py [-h]
208
209 A foo that bars
210
211 optional arguments:
212 -h, --help show this help message and exit
213
214 And that's how you'd foo a bar
215
216As with the description_ argument, the ``epilog=`` text is by default
217line-wrapped, but this behavior can be adjusted with the formatter_class_
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000218argument to :class:`ArgumentParser`.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000219
220
221add_help
222^^^^^^^^
223
R. David Murray88c49fe2010-08-03 17:56:09 +0000224By default, ArgumentParser objects add an option which simply displays
225the parser's help message. For example, consider a file named
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000226``myprogram.py`` containing the following code::
227
228 import argparse
229 parser = argparse.ArgumentParser()
230 parser.add_argument('--foo', help='foo help')
231 args = parser.parse_args()
232
Georg Brandl1d827ff2011-04-16 16:44:54 +0200233If ``-h`` or ``--help`` is supplied at the command line, the ArgumentParser
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000234help will be printed::
235
236 $ python myprogram.py --help
237 usage: myprogram.py [-h] [--foo FOO]
238
239 optional arguments:
240 -h, --help show this help message and exit
241 --foo FOO foo help
242
243Occasionally, it may be useful to disable the addition of this help option.
244This can be achieved by passing ``False`` as the ``add_help=`` argument to
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000245:class:`ArgumentParser`::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000246
247 >>> parser = argparse.ArgumentParser(prog='PROG', add_help=False)
248 >>> parser.add_argument('--foo', help='foo help')
249 >>> parser.print_help()
250 usage: PROG [--foo FOO]
251
252 optional arguments:
253 --foo FOO foo help
254
R. David Murray88c49fe2010-08-03 17:56:09 +0000255The help option is typically ``-h/--help``. The exception to this is
Éric Araujo543edbd2011-08-19 01:45:12 +0200256if the ``prefix_chars=`` is specified and does not include ``-``, in
R. David Murray88c49fe2010-08-03 17:56:09 +0000257which case ``-h`` and ``--help`` are not valid options. In
258this case, the first character in ``prefix_chars`` is used to prefix
259the help options::
260
261 >>> parser = argparse.ArgumentParser(prog='PROG', prefix_chars='+/')
262 >>> parser.print_help()
263 usage: PROG [+h]
264
265 optional arguments:
266 +h, ++help show this help message and exit
267
268
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000269prefix_chars
270^^^^^^^^^^^^
271
Éric Araujo543edbd2011-08-19 01:45:12 +0200272Most command-line options will use ``-`` as the prefix, e.g. ``-f/--foo``.
R. David Murray88c49fe2010-08-03 17:56:09 +0000273Parsers that need to support different or additional prefix
274characters, e.g. for options
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000275like ``+f`` or ``/foo``, may specify them using the ``prefix_chars=`` argument
276to the ArgumentParser constructor::
277
278 >>> parser = argparse.ArgumentParser(prog='PROG', prefix_chars='-+')
279 >>> parser.add_argument('+f')
280 >>> parser.add_argument('++bar')
281 >>> parser.parse_args('+f X ++bar Y'.split())
282 Namespace(bar='Y', f='X')
283
284The ``prefix_chars=`` argument defaults to ``'-'``. Supplying a set of
Éric Araujo543edbd2011-08-19 01:45:12 +0200285characters that does not include ``-`` will cause ``-f/--foo`` options to be
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000286disallowed.
287
288
289fromfile_prefix_chars
290^^^^^^^^^^^^^^^^^^^^^
291
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000292Sometimes, for example when dealing with a particularly long argument lists, it
293may make sense to keep the list of arguments in a file rather than typing it out
294at the command line. If the ``fromfile_prefix_chars=`` argument is given to the
295:class:`ArgumentParser` constructor, then arguments that start with any of the
296specified characters will be treated as files, and will be replaced by the
297arguments they contain. For example::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000298
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000299 >>> with open('args.txt', 'w') as fp:
300 ... fp.write('-f\nbar')
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000301 >>> parser = argparse.ArgumentParser(fromfile_prefix_chars='@')
302 >>> parser.add_argument('-f')
303 >>> parser.parse_args(['-f', 'foo', '@args.txt'])
304 Namespace(f='bar')
305
306Arguments read from a file must by default be one per line (but see also
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300307:meth:`~ArgumentParser.convert_arg_line_to_args`) and are treated as if they
308were in the same place as the original file referencing argument on the command
309line. So in the example above, the expression ``['-f', 'foo', '@args.txt']``
310is considered equivalent to the expression ``['-f', 'foo', '-f', 'bar']``.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000311
312The ``fromfile_prefix_chars=`` argument defaults to ``None``, meaning that
313arguments will never be treated as file references.
314
Georg Brandle0bf91d2010-10-17 10:34:28 +0000315
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000316argument_default
317^^^^^^^^^^^^^^^^
318
319Generally, argument defaults are specified either by passing a default to
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300320:meth:`~ArgumentParser.add_argument` or by calling the
321:meth:`~ArgumentParser.set_defaults` methods with a specific set of name-value
322pairs. Sometimes however, it may be useful to specify a single parser-wide
323default for arguments. This can be accomplished by passing the
324``argument_default=`` keyword argument to :class:`ArgumentParser`. For example,
325to globally suppress attribute creation on :meth:`~ArgumentParser.parse_args`
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000326calls, we supply ``argument_default=SUPPRESS``::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000327
328 >>> parser = argparse.ArgumentParser(argument_default=argparse.SUPPRESS)
329 >>> parser.add_argument('--foo')
330 >>> parser.add_argument('bar', nargs='?')
331 >>> parser.parse_args(['--foo', '1', 'BAR'])
332 Namespace(bar='BAR', foo='1')
333 >>> parser.parse_args([])
334 Namespace()
335
336
337parents
338^^^^^^^
339
340Sometimes, several parsers share a common set of arguments. Rather than
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000341repeating the definitions of these arguments, a single parser with all the
342shared arguments and passed to ``parents=`` argument to :class:`ArgumentParser`
343can be used. The ``parents=`` argument takes a list of :class:`ArgumentParser`
344objects, collects all the positional and optional actions from them, and adds
345these actions to the :class:`ArgumentParser` object being constructed::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000346
347 >>> parent_parser = argparse.ArgumentParser(add_help=False)
348 >>> parent_parser.add_argument('--parent', type=int)
349
350 >>> foo_parser = argparse.ArgumentParser(parents=[parent_parser])
351 >>> foo_parser.add_argument('foo')
352 >>> foo_parser.parse_args(['--parent', '2', 'XXX'])
353 Namespace(foo='XXX', parent=2)
354
355 >>> bar_parser = argparse.ArgumentParser(parents=[parent_parser])
356 >>> bar_parser.add_argument('--bar')
357 >>> bar_parser.parse_args(['--bar', 'YYY'])
358 Namespace(bar='YYY', parent=None)
359
360Note that most parent parsers will specify ``add_help=False``. Otherwise, the
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000361:class:`ArgumentParser` will see two ``-h/--help`` options (one in the parent
362and one in the child) and raise an error.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000363
Steven Bethardd186f992011-03-26 21:49:00 +0100364.. note::
365 You must fully initialize the parsers before passing them via ``parents=``.
366 If you change the parent parsers after the child parser, those changes will
367 not be reflected in the child.
368
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000369
370formatter_class
371^^^^^^^^^^^^^^^
372
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000373:class:`ArgumentParser` objects allow the help formatting to be customized by
374specifying an alternate formatting class. Currently, there are three such
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300375classes:
376
377.. class:: RawDescriptionHelpFormatter
378 RawTextHelpFormatter
379 ArgumentDefaultsHelpFormatter
380
381The first two allow more control over how textual descriptions are displayed,
382while the last automatically adds information about argument default values.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000383
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000384By default, :class:`ArgumentParser` objects line-wrap the description_ and
385epilog_ texts in command-line help messages::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000386
387 >>> parser = argparse.ArgumentParser(
388 ... prog='PROG',
389 ... description='''this description
390 ... was indented weird
391 ... but that is okay''',
392 ... epilog='''
393 ... likewise for this epilog whose whitespace will
394 ... be cleaned up and whose words will be wrapped
395 ... across a couple lines''')
396 >>> parser.print_help()
397 usage: PROG [-h]
398
399 this description was indented weird but that is okay
400
401 optional arguments:
402 -h, --help show this help message and exit
403
404 likewise for this epilog whose whitespace will be cleaned up and whose words
405 will be wrapped across a couple lines
406
Éric Araujo543edbd2011-08-19 01:45:12 +0200407Passing :class:`RawDescriptionHelpFormatter` as ``formatter_class=``
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000408indicates that description_ and epilog_ are already correctly formatted and
409should not be line-wrapped::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000410
411 >>> parser = argparse.ArgumentParser(
412 ... prog='PROG',
413 ... formatter_class=argparse.RawDescriptionHelpFormatter,
414 ... description=textwrap.dedent('''\
415 ... Please do not mess up this text!
416 ... --------------------------------
417 ... I have indented it
418 ... exactly the way
419 ... I want it
420 ... '''))
421 >>> parser.print_help()
422 usage: PROG [-h]
423
424 Please do not mess up this text!
425 --------------------------------
426 I have indented it
427 exactly the way
428 I want it
429
430 optional arguments:
431 -h, --help show this help message and exit
432
Éric Araujo543edbd2011-08-19 01:45:12 +0200433:class:`RawTextHelpFormatter` maintains whitespace for all sorts of help text,
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000434including argument descriptions.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000435
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000436The other formatter class available, :class:`ArgumentDefaultsHelpFormatter`,
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000437will add information about the default value of each of the arguments::
438
439 >>> parser = argparse.ArgumentParser(
440 ... prog='PROG',
441 ... formatter_class=argparse.ArgumentDefaultsHelpFormatter)
442 >>> parser.add_argument('--foo', type=int, default=42, help='FOO!')
443 >>> parser.add_argument('bar', nargs='*', default=[1, 2, 3], help='BAR!')
444 >>> parser.print_help()
445 usage: PROG [-h] [--foo FOO] [bar [bar ...]]
446
447 positional arguments:
448 bar BAR! (default: [1, 2, 3])
449
450 optional arguments:
451 -h, --help show this help message and exit
452 --foo FOO FOO! (default: 42)
453
454
455conflict_handler
456^^^^^^^^^^^^^^^^
457
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000458:class:`ArgumentParser` objects do not allow two actions with the same option
459string. By default, :class:`ArgumentParser` objects raises an exception if an
460attempt is made to create an argument with an option string that is already in
461use::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000462
463 >>> parser = argparse.ArgumentParser(prog='PROG')
464 >>> parser.add_argument('-f', '--foo', help='old foo help')
465 >>> parser.add_argument('--foo', help='new foo help')
466 Traceback (most recent call last):
467 ..
468 ArgumentError: argument --foo: conflicting option string(s): --foo
469
470Sometimes (e.g. when using parents_) it may be useful to simply override any
471older arguments with the same option string. To get this behavior, the value
472``'resolve'`` can be supplied to the ``conflict_handler=`` argument of
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000473:class:`ArgumentParser`::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000474
475 >>> parser = argparse.ArgumentParser(prog='PROG', conflict_handler='resolve')
476 >>> parser.add_argument('-f', '--foo', help='old foo help')
477 >>> parser.add_argument('--foo', help='new foo help')
478 >>> parser.print_help()
479 usage: PROG [-h] [-f FOO] [--foo FOO]
480
481 optional arguments:
482 -h, --help show this help message and exit
483 -f FOO old foo help
484 --foo FOO new foo help
485
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000486Note that :class:`ArgumentParser` objects only remove an action if all of its
487option strings are overridden. So, in the example above, the old ``-f/--foo``
488action is retained as the ``-f`` action, because only the ``--foo`` option
489string was overridden.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000490
491
492prog
493^^^^
494
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000495By default, :class:`ArgumentParser` objects uses ``sys.argv[0]`` to determine
496how to display the name of the program in help messages. This default is almost
Ezio Melottif82340d2010-05-27 22:38:16 +0000497always desirable because it will make the help messages match how the program was
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000498invoked on the command line. For example, consider a file named
499``myprogram.py`` with the following code::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000500
501 import argparse
502 parser = argparse.ArgumentParser()
503 parser.add_argument('--foo', help='foo help')
504 args = parser.parse_args()
505
506The help for this program will display ``myprogram.py`` as the program name
507(regardless of where the program was invoked from)::
508
509 $ python myprogram.py --help
510 usage: myprogram.py [-h] [--foo FOO]
511
512 optional arguments:
513 -h, --help show this help message and exit
514 --foo FOO foo help
515 $ cd ..
516 $ python subdir\myprogram.py --help
517 usage: myprogram.py [-h] [--foo FOO]
518
519 optional arguments:
520 -h, --help show this help message and exit
521 --foo FOO foo help
522
523To change this default behavior, another value can be supplied using the
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000524``prog=`` argument to :class:`ArgumentParser`::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000525
526 >>> parser = argparse.ArgumentParser(prog='myprogram')
527 >>> parser.print_help()
528 usage: myprogram [-h]
529
530 optional arguments:
531 -h, --help show this help message and exit
532
533Note that the program name, whether determined from ``sys.argv[0]`` or from the
534``prog=`` argument, is available to help messages using the ``%(prog)s`` format
535specifier.
536
537::
538
539 >>> parser = argparse.ArgumentParser(prog='myprogram')
540 >>> parser.add_argument('--foo', help='foo of the %(prog)s program')
541 >>> parser.print_help()
542 usage: myprogram [-h] [--foo FOO]
543
544 optional arguments:
545 -h, --help show this help message and exit
546 --foo FOO foo of the myprogram program
547
548
549usage
550^^^^^
551
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000552By default, :class:`ArgumentParser` calculates the usage message from the
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000553arguments it contains::
554
555 >>> parser = argparse.ArgumentParser(prog='PROG')
556 >>> parser.add_argument('--foo', nargs='?', help='foo help')
557 >>> parser.add_argument('bar', nargs='+', help='bar help')
558 >>> parser.print_help()
559 usage: PROG [-h] [--foo [FOO]] bar [bar ...]
560
561 positional arguments:
562 bar bar help
563
564 optional arguments:
565 -h, --help show this help message and exit
566 --foo [FOO] foo help
567
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000568The default message can be overridden with the ``usage=`` keyword argument::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000569
570 >>> parser = argparse.ArgumentParser(prog='PROG', usage='%(prog)s [options]')
571 >>> parser.add_argument('--foo', nargs='?', help='foo help')
572 >>> parser.add_argument('bar', nargs='+', help='bar help')
573 >>> parser.print_help()
574 usage: PROG [options]
575
576 positional arguments:
577 bar bar help
578
579 optional arguments:
580 -h, --help show this help message and exit
581 --foo [FOO] foo help
582
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000583The ``%(prog)s`` format specifier is available to fill in the program name in
584your usage messages.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000585
586
587The add_argument() method
588-------------------------
589
Georg Brandlc9007082011-01-09 09:04:08 +0000590.. method:: ArgumentParser.add_argument(name or flags..., [action], [nargs], \
591 [const], [default], [type], [choices], [required], \
592 [help], [metavar], [dest])
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000593
Georg Brandl1d827ff2011-04-16 16:44:54 +0200594 Define how a single command-line argument should be parsed. Each parameter
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000595 has its own more detailed description below, but in short they are:
596
597 * `name or flags`_ - Either a name or a list of option strings, e.g. ``foo``
Ezio Melottidca309d2011-04-21 23:09:27 +0300598 or ``-f, --foo``.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000599
600 * action_ - The basic type of action to be taken when this argument is
Georg Brandl1d827ff2011-04-16 16:44:54 +0200601 encountered at the command line.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000602
603 * nargs_ - The number of command-line arguments that should be consumed.
604
605 * const_ - A constant value required by some action_ and nargs_ selections.
606
607 * default_ - The value produced if the argument is absent from the
Georg Brandl1d827ff2011-04-16 16:44:54 +0200608 command line.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000609
Ezio Melotti2409d772011-04-16 23:13:50 +0300610 * type_ - The type to which the command-line argument should be converted.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000611
612 * choices_ - A container of the allowable values for the argument.
613
614 * required_ - Whether or not the command-line option may be omitted
615 (optionals only).
616
617 * help_ - A brief description of what the argument does.
618
619 * metavar_ - A name for the argument in usage messages.
620
621 * dest_ - The name of the attribute to be added to the object returned by
622 :meth:`parse_args`.
623
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000624The following sections describe how each of these are used.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000625
Georg Brandle0bf91d2010-10-17 10:34:28 +0000626
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000627name or flags
628^^^^^^^^^^^^^
629
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300630The :meth:`~ArgumentParser.add_argument` method must know whether an optional
631argument, like ``-f`` or ``--foo``, or a positional argument, like a list of
632filenames, is expected. The first arguments passed to
633:meth:`~ArgumentParser.add_argument` must therefore be either a series of
634flags, or a simple argument name. For example, an optional argument could
635be created like::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000636
637 >>> parser.add_argument('-f', '--foo')
638
639while a positional argument could be created like::
640
641 >>> parser.add_argument('bar')
642
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300643When :meth:`~ArgumentParser.parse_args` is called, optional arguments will be
644identified by the ``-`` prefix, and the remaining arguments will be assumed to
645be positional::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000646
647 >>> parser = argparse.ArgumentParser(prog='PROG')
648 >>> parser.add_argument('-f', '--foo')
649 >>> parser.add_argument('bar')
650 >>> parser.parse_args(['BAR'])
651 Namespace(bar='BAR', foo=None)
652 >>> parser.parse_args(['BAR', '--foo', 'FOO'])
653 Namespace(bar='BAR', foo='FOO')
654 >>> parser.parse_args(['--foo', 'FOO'])
655 usage: PROG [-h] [-f FOO] bar
656 PROG: error: too few arguments
657
Georg Brandle0bf91d2010-10-17 10:34:28 +0000658
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000659action
660^^^^^^
661
Éric Araujod9d7bca2011-08-10 04:19:03 +0200662:class:`ArgumentParser` objects associate command-line arguments with actions. These
663actions can do just about anything with the command-line arguments associated with
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000664them, though most actions simply add an attribute to the object returned by
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300665:meth:`~ArgumentParser.parse_args`. The ``action`` keyword argument specifies
Éric Araujod9d7bca2011-08-10 04:19:03 +0200666how the command-line arguments should be handled. The supported actions are:
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000667
668* ``'store'`` - This just stores the argument's value. This is the default
Ezio Melotti2f1db7d2011-04-21 23:06:48 +0300669 action. For example::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000670
671 >>> parser = argparse.ArgumentParser()
672 >>> parser.add_argument('--foo')
673 >>> parser.parse_args('--foo 1'.split())
674 Namespace(foo='1')
675
676* ``'store_const'`` - This stores the value specified by the const_ keyword
Ezio Melotti2f1db7d2011-04-21 23:06:48 +0300677 argument. (Note that the const_ keyword argument defaults to the rather
678 unhelpful ``None``.) The ``'store_const'`` action is most commonly used with
679 optional arguments that specify some sort of flag. For example::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000680
681 >>> parser = argparse.ArgumentParser()
682 >>> parser.add_argument('--foo', action='store_const', const=42)
683 >>> parser.parse_args('--foo'.split())
684 Namespace(foo=42)
685
686* ``'store_true'`` and ``'store_false'`` - These store the values ``True`` and
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000687 ``False`` respectively. These are special cases of ``'store_const'``. For
688 example::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000689
690 >>> parser = argparse.ArgumentParser()
691 >>> parser.add_argument('--foo', action='store_true')
692 >>> parser.add_argument('--bar', action='store_false')
693 >>> parser.parse_args('--foo --bar'.split())
694 Namespace(bar=False, foo=True)
695
696* ``'append'`` - This stores a list, and appends each argument value to the
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000697 list. This is useful to allow an option to be specified multiple times.
698 Example usage::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000699
700 >>> parser = argparse.ArgumentParser()
701 >>> parser.add_argument('--foo', action='append')
702 >>> parser.parse_args('--foo 1 --foo 2'.split())
703 Namespace(foo=['1', '2'])
704
705* ``'append_const'`` - This stores a list, and appends the value specified by
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000706 the const_ keyword argument to the list. (Note that the const_ keyword
707 argument defaults to ``None``.) The ``'append_const'`` action is typically
708 useful when multiple arguments need to store constants to the same list. For
709 example::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000710
711 >>> parser = argparse.ArgumentParser()
712 >>> parser.add_argument('--str', dest='types', action='append_const', const=str)
713 >>> parser.add_argument('--int', dest='types', action='append_const', const=int)
714 >>> parser.parse_args('--str --int'.split())
Florent Xicluna74e64952011-10-28 11:21:19 +0200715 Namespace(types=[<class 'str'>, <class 'int'>])
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000716
Sandro Tosi98492a52012-01-04 23:25:04 +0100717* ``'count'`` - This counts the number of times a keyword argument occurs. For
718 example, this is useful for increasing verbosity levels::
719
720 >>> parser = argparse.ArgumentParser()
721 >>> parser.add_argument('--verbose', '-v', action='count')
722 >>> parser.parse_args('-vvv'.split())
723 Namespace(verbose=3)
724
725* ``'help'`` - This prints a complete help message for all the options in the
726 current parser and then exits. By default a help action is automatically
727 added to the parser. See :class:`ArgumentParser` for details of how the
728 output is created.
729
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000730* ``'version'`` - This expects a ``version=`` keyword argument in the
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300731 :meth:`~ArgumentParser.add_argument` call, and prints version information
Éric Araujoc3ef0372012-02-20 01:44:55 +0100732 and exits when invoked::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000733
734 >>> import argparse
735 >>> parser = argparse.ArgumentParser(prog='PROG')
Steven Bethard59710962010-05-24 03:21:08 +0000736 >>> parser.add_argument('--version', action='version', version='%(prog)s 2.0')
737 >>> parser.parse_args(['--version'])
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000738 PROG 2.0
739
740You can also specify an arbitrary action by passing an object that implements
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000741the Action API. The easiest way to do this is to extend
742:class:`argparse.Action`, supplying an appropriate ``__call__`` method. The
743``__call__`` method should accept four parameters:
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000744
745* ``parser`` - The ArgumentParser object which contains this action.
746
Éric Araujo63b18a42011-07-29 17:59:17 +0200747* ``namespace`` - The :class:`Namespace` object that will be returned by
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300748 :meth:`~ArgumentParser.parse_args`. Most actions add an attribute to this
749 object.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000750
Éric Araujod9d7bca2011-08-10 04:19:03 +0200751* ``values`` - The associated command-line arguments, with any type conversions
752 applied. (Type conversions are specified with the type_ keyword argument to
Sandro Tosiee903c52012-08-12 10:49:26 +0200753 :meth:`~ArgumentParser.add_argument`.)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000754
755* ``option_string`` - The option string that was used to invoke this action.
756 The ``option_string`` argument is optional, and will be absent if the action
757 is associated with a positional argument.
758
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000759An example of a custom action::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000760
761 >>> class FooAction(argparse.Action):
762 ... def __call__(self, parser, namespace, values, option_string=None):
Georg Brandl571a9532010-07-26 17:00:20 +0000763 ... print('%r %r %r' % (namespace, values, option_string))
764 ... setattr(namespace, self.dest, values)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000765 ...
766 >>> parser = argparse.ArgumentParser()
767 >>> parser.add_argument('--foo', action=FooAction)
768 >>> parser.add_argument('bar', action=FooAction)
769 >>> args = parser.parse_args('1 --foo 2'.split())
770 Namespace(bar=None, foo=None) '1' None
771 Namespace(bar='1', foo=None) '2' '--foo'
772 >>> args
773 Namespace(bar='1', foo='2')
774
775
776nargs
777^^^^^
778
779ArgumentParser objects usually associate a single command-line argument with a
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000780single action to be taken. The ``nargs`` keyword argument associates a
Ezio Melotti00f53af2011-04-21 22:56:51 +0300781different number of command-line arguments with a single action. The supported
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000782values are:
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000783
Éric Araujoc3ef0372012-02-20 01:44:55 +0100784* ``N`` (an integer). ``N`` arguments from the command line will be gathered
785 together into a list. For example::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000786
Georg Brandl682d7e02010-10-06 10:26:05 +0000787 >>> parser = argparse.ArgumentParser()
788 >>> parser.add_argument('--foo', nargs=2)
789 >>> parser.add_argument('bar', nargs=1)
790 >>> parser.parse_args('c --foo a b'.split())
791 Namespace(bar=['c'], foo=['a', 'b'])
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000792
Georg Brandl682d7e02010-10-06 10:26:05 +0000793 Note that ``nargs=1`` produces a list of one item. This is different from
794 the default, in which the item is produced by itself.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000795
Éric Araujofde92422011-08-19 01:30:26 +0200796* ``'?'``. One argument will be consumed from the command line if possible, and
797 produced as a single item. If no command-line argument is present, the value from
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000798 default_ will be produced. Note that for optional arguments, there is an
799 additional case - the option string is present but not followed by a
Éric Araujofde92422011-08-19 01:30:26 +0200800 command-line argument. In this case the value from const_ will be produced. Some
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000801 examples to illustrate this::
802
803 >>> parser = argparse.ArgumentParser()
804 >>> parser.add_argument('--foo', nargs='?', const='c', default='d')
805 >>> parser.add_argument('bar', nargs='?', default='d')
806 >>> parser.parse_args('XX --foo YY'.split())
807 Namespace(bar='XX', foo='YY')
808 >>> parser.parse_args('XX --foo'.split())
809 Namespace(bar='XX', foo='c')
810 >>> parser.parse_args(''.split())
811 Namespace(bar='d', foo='d')
812
813 One of the more common uses of ``nargs='?'`` is to allow optional input and
814 output files::
815
816 >>> parser = argparse.ArgumentParser()
Georg Brandle0bf91d2010-10-17 10:34:28 +0000817 >>> parser.add_argument('infile', nargs='?', type=argparse.FileType('r'),
818 ... default=sys.stdin)
819 >>> parser.add_argument('outfile', nargs='?', type=argparse.FileType('w'),
820 ... default=sys.stdout)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000821 >>> parser.parse_args(['input.txt', 'output.txt'])
Georg Brandl04536b02011-01-09 09:31:01 +0000822 Namespace(infile=<_io.TextIOWrapper name='input.txt' encoding='UTF-8'>,
823 outfile=<_io.TextIOWrapper name='output.txt' encoding='UTF-8'>)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000824 >>> parser.parse_args([])
Georg Brandl04536b02011-01-09 09:31:01 +0000825 Namespace(infile=<_io.TextIOWrapper name='<stdin>' encoding='UTF-8'>,
826 outfile=<_io.TextIOWrapper name='<stdout>' encoding='UTF-8'>)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000827
Éric Araujod9d7bca2011-08-10 04:19:03 +0200828* ``'*'``. All command-line arguments present are gathered into a list. Note that
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000829 it generally doesn't make much sense to have more than one positional argument
830 with ``nargs='*'``, but multiple optional arguments with ``nargs='*'`` is
831 possible. For example::
832
833 >>> parser = argparse.ArgumentParser()
834 >>> parser.add_argument('--foo', nargs='*')
835 >>> parser.add_argument('--bar', nargs='*')
836 >>> parser.add_argument('baz', nargs='*')
837 >>> parser.parse_args('a b --foo x y --bar 1 2'.split())
838 Namespace(bar=['1', '2'], baz=['a', 'b'], foo=['x', 'y'])
839
840* ``'+'``. Just like ``'*'``, all command-line args present are gathered into a
841 list. Additionally, an error message will be generated if there wasn't at
Éric Araujofde92422011-08-19 01:30:26 +0200842 least one command-line argument present. For example::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000843
844 >>> parser = argparse.ArgumentParser(prog='PROG')
845 >>> parser.add_argument('foo', nargs='+')
846 >>> parser.parse_args('a b'.split())
847 Namespace(foo=['a', 'b'])
848 >>> parser.parse_args(''.split())
849 usage: PROG [-h] foo [foo ...]
850 PROG: error: too few arguments
851
Sandro Tosida8e11a2012-01-19 22:23:00 +0100852* ``argparse.REMAINDER``. All the remaining command-line arguments are gathered
853 into a list. This is commonly useful for command line utilities that dispatch
Éric Araujoc3ef0372012-02-20 01:44:55 +0100854 to other command line utilities::
Sandro Tosi16bd0b42012-01-19 21:59:55 +0100855
856 >>> parser = argparse.ArgumentParser(prog='PROG')
857 >>> parser.add_argument('--foo')
858 >>> parser.add_argument('command')
859 >>> parser.add_argument('args', nargs=argparse.REMAINDER)
Sandro Tosi04676862012-02-19 19:54:00 +0100860 >>> print(parser.parse_args('--foo B cmd --arg1 XX ZZ'.split()))
Sandro Tosida8e11a2012-01-19 22:23:00 +0100861 Namespace(args=['--arg1', 'XX', 'ZZ'], command='cmd', foo='B')
Sandro Tosi16bd0b42012-01-19 21:59:55 +0100862
Éric Araujod9d7bca2011-08-10 04:19:03 +0200863If the ``nargs`` keyword argument is not provided, the number of arguments consumed
Éric Araujofde92422011-08-19 01:30:26 +0200864is determined by the action_. Generally this means a single command-line argument
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000865will be consumed and a single item (not a list) will be produced.
866
867
868const
869^^^^^
870
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300871The ``const`` argument of :meth:`~ArgumentParser.add_argument` is used to hold
872constant values that are not read from the command line but are required for
873the various :class:`ArgumentParser` actions. The two most common uses of it are:
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000874
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300875* When :meth:`~ArgumentParser.add_argument` is called with
876 ``action='store_const'`` or ``action='append_const'``. These actions add the
Éric Araujoc3ef0372012-02-20 01:44:55 +0100877 ``const`` value to one of the attributes of the object returned by
878 :meth:`~ArgumentParser.parse_args`. See the action_ description for examples.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000879
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300880* When :meth:`~ArgumentParser.add_argument` is called with option strings
881 (like ``-f`` or ``--foo``) and ``nargs='?'``. This creates an optional
Éric Araujod9d7bca2011-08-10 04:19:03 +0200882 argument that can be followed by zero or one command-line arguments.
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300883 When parsing the command line, if the option string is encountered with no
Éric Araujofde92422011-08-19 01:30:26 +0200884 command-line argument following it, the value of ``const`` will be assumed instead.
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300885 See the nargs_ description for examples.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000886
887The ``const`` keyword argument defaults to ``None``.
888
889
890default
891^^^^^^^
892
893All optional arguments and some positional arguments may be omitted at the
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300894command line. The ``default`` keyword argument of
895:meth:`~ArgumentParser.add_argument`, whose value defaults to ``None``,
Éric Araujofde92422011-08-19 01:30:26 +0200896specifies what value should be used if the command-line argument is not present.
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300897For optional arguments, the ``default`` value is used when the option string
898was not present at the command line::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000899
900 >>> parser = argparse.ArgumentParser()
901 >>> parser.add_argument('--foo', default=42)
902 >>> parser.parse_args('--foo 2'.split())
903 Namespace(foo='2')
904 >>> parser.parse_args(''.split())
905 Namespace(foo=42)
906
Éric Araujo543edbd2011-08-19 01:45:12 +0200907For positional arguments with nargs_ equal to ``?`` or ``*``, the ``default`` value
Éric Araujofde92422011-08-19 01:30:26 +0200908is used when no command-line argument was present::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000909
910 >>> parser = argparse.ArgumentParser()
911 >>> parser.add_argument('foo', nargs='?', default=42)
912 >>> parser.parse_args('a'.split())
913 Namespace(foo='a')
914 >>> parser.parse_args(''.split())
915 Namespace(foo=42)
916
917
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000918Providing ``default=argparse.SUPPRESS`` causes no attribute to be added if the
919command-line argument was not present.::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000920
921 >>> parser = argparse.ArgumentParser()
922 >>> parser.add_argument('--foo', default=argparse.SUPPRESS)
923 >>> parser.parse_args([])
924 Namespace()
925 >>> parser.parse_args(['--foo', '1'])
926 Namespace(foo='1')
927
928
929type
930^^^^
931
Éric Araujod9d7bca2011-08-10 04:19:03 +0200932By default, :class:`ArgumentParser` objects read command-line arguments in as simple
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300933strings. However, quite often the command-line string should instead be
934interpreted as another type, like a :class:`float` or :class:`int`. The
935``type`` keyword argument of :meth:`~ArgumentParser.add_argument` allows any
Éric Araujod9d7bca2011-08-10 04:19:03 +0200936necessary type-checking and type conversions to be performed. Common built-in
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300937types and functions can be used directly as the value of the ``type`` argument::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000938
939 >>> parser = argparse.ArgumentParser()
940 >>> parser.add_argument('foo', type=int)
Georg Brandl04536b02011-01-09 09:31:01 +0000941 >>> parser.add_argument('bar', type=open)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000942 >>> parser.parse_args('2 temp.txt'.split())
Georg Brandl04536b02011-01-09 09:31:01 +0000943 Namespace(bar=<_io.TextIOWrapper name='temp.txt' encoding='UTF-8'>, foo=2)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000944
945To ease the use of various types of files, the argparse module provides the
946factory FileType which takes the ``mode=`` and ``bufsize=`` arguments of the
Georg Brandl04536b02011-01-09 09:31:01 +0000947:func:`open` function. For example, ``FileType('w')`` can be used to create a
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000948writable file::
949
950 >>> parser = argparse.ArgumentParser()
951 >>> parser.add_argument('bar', type=argparse.FileType('w'))
952 >>> parser.parse_args(['out.txt'])
Georg Brandl04536b02011-01-09 09:31:01 +0000953 Namespace(bar=<_io.TextIOWrapper name='out.txt' encoding='UTF-8'>)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000954
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000955``type=`` can take any callable that takes a single string argument and returns
Éric Araujod9d7bca2011-08-10 04:19:03 +0200956the converted value::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000957
958 >>> def perfect_square(string):
959 ... value = int(string)
960 ... sqrt = math.sqrt(value)
961 ... if sqrt != int(sqrt):
962 ... msg = "%r is not a perfect square" % string
963 ... raise argparse.ArgumentTypeError(msg)
964 ... return value
965 ...
966 >>> parser = argparse.ArgumentParser(prog='PROG')
967 >>> parser.add_argument('foo', type=perfect_square)
968 >>> parser.parse_args('9'.split())
969 Namespace(foo=9)
970 >>> parser.parse_args('7'.split())
971 usage: PROG [-h] foo
972 PROG: error: argument foo: '7' is not a perfect square
973
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000974The choices_ keyword argument may be more convenient for type checkers that
975simply check against a range of values::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000976
977 >>> parser = argparse.ArgumentParser(prog='PROG')
Fred Drakec7eb7892011-03-03 05:29:59 +0000978 >>> parser.add_argument('foo', type=int, choices=range(5, 10))
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000979 >>> parser.parse_args('7'.split())
980 Namespace(foo=7)
981 >>> parser.parse_args('11'.split())
982 usage: PROG [-h] {5,6,7,8,9}
983 PROG: error: argument foo: invalid choice: 11 (choose from 5, 6, 7, 8, 9)
984
985See the choices_ section for more details.
986
987
988choices
989^^^^^^^
990
Éric Araujod9d7bca2011-08-10 04:19:03 +0200991Some command-line arguments should be selected from a restricted set of values.
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000992These can be handled by passing a container object as the ``choices`` keyword
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300993argument to :meth:`~ArgumentParser.add_argument`. When the command line is
Éric Araujofde92422011-08-19 01:30:26 +0200994parsed, argument values will be checked, and an error message will be displayed if
995the argument was not one of the acceptable values::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000996
997 >>> parser = argparse.ArgumentParser(prog='PROG')
998 >>> parser.add_argument('foo', choices='abc')
999 >>> parser.parse_args('c'.split())
1000 Namespace(foo='c')
1001 >>> parser.parse_args('X'.split())
1002 usage: PROG [-h] {a,b,c}
1003 PROG: error: argument foo: invalid choice: 'X' (choose from 'a', 'b', 'c')
1004
1005Note that inclusion in the ``choices`` container is checked after any type_
1006conversions have been performed, so the type of the objects in the ``choices``
1007container should match the type_ specified::
1008
1009 >>> parser = argparse.ArgumentParser(prog='PROG')
1010 >>> parser.add_argument('foo', type=complex, choices=[1, 1j])
1011 >>> parser.parse_args('1j'.split())
1012 Namespace(foo=1j)
1013 >>> parser.parse_args('-- -4'.split())
1014 usage: PROG [-h] {1,1j}
1015 PROG: error: argument foo: invalid choice: (-4+0j) (choose from 1, 1j)
1016
1017Any object that supports the ``in`` operator can be passed as the ``choices``
1018value, so :class:`dict` objects, :class:`set` objects, custom containers,
1019etc. are all supported.
1020
1021
1022required
1023^^^^^^^^
1024
Ezio Melotti0ee9c1b2011-04-21 16:12:17 +03001025In general, the :mod:`argparse` module assumes that flags like ``-f`` and ``--bar``
Georg Brandl1d827ff2011-04-16 16:44:54 +02001026indicate *optional* arguments, which can always be omitted at the command line.
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001027To make an option *required*, ``True`` can be specified for the ``required=``
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001028keyword argument to :meth:`~ArgumentParser.add_argument`::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001029
1030 >>> parser = argparse.ArgumentParser()
1031 >>> parser.add_argument('--foo', required=True)
1032 >>> parser.parse_args(['--foo', 'BAR'])
1033 Namespace(foo='BAR')
1034 >>> parser.parse_args([])
1035 usage: argparse.py [-h] [--foo FOO]
1036 argparse.py: error: option --foo is required
1037
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001038As the example shows, if an option is marked as ``required``,
1039:meth:`~ArgumentParser.parse_args` will report an error if that option is not
1040present at the command line.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001041
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001042.. note::
1043
1044 Required options are generally considered bad form because users expect
1045 *options* to be *optional*, and thus they should be avoided when possible.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001046
1047
1048help
1049^^^^
1050
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001051The ``help`` value is a string containing a brief description of the argument.
1052When a user requests help (usually by using ``-h`` or ``--help`` at the
Georg Brandl1d827ff2011-04-16 16:44:54 +02001053command line), these ``help`` descriptions will be displayed with each
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001054argument::
1055
1056 >>> parser = argparse.ArgumentParser(prog='frobble')
1057 >>> parser.add_argument('--foo', action='store_true',
1058 ... help='foo the bars before frobbling')
1059 >>> parser.add_argument('bar', nargs='+',
1060 ... help='one of the bars to be frobbled')
1061 >>> parser.parse_args('-h'.split())
1062 usage: frobble [-h] [--foo] bar [bar ...]
1063
1064 positional arguments:
1065 bar one of the bars to be frobbled
1066
1067 optional arguments:
1068 -h, --help show this help message and exit
1069 --foo foo the bars before frobbling
1070
1071The ``help`` strings can include various format specifiers to avoid repetition
1072of things like the program name or the argument default_. The available
1073specifiers include the program name, ``%(prog)s`` and most keyword arguments to
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001074:meth:`~ArgumentParser.add_argument`, e.g. ``%(default)s``, ``%(type)s``, etc.::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001075
1076 >>> parser = argparse.ArgumentParser(prog='frobble')
1077 >>> parser.add_argument('bar', nargs='?', type=int, default=42,
1078 ... help='the bar to %(prog)s (default: %(default)s)')
1079 >>> parser.print_help()
1080 usage: frobble [-h] [bar]
1081
1082 positional arguments:
1083 bar the bar to frobble (default: 42)
1084
1085 optional arguments:
1086 -h, --help show this help message and exit
1087
Senthil Kumaranf21804a2012-06-26 14:17:19 +08001088As the help string supports %-formatting, if you want a literal ``%`` to appear
1089in the help string, you must escape it as ``%%``.
1090
Sandro Tosiea320ab2012-01-03 18:37:03 +01001091:mod:`argparse` supports silencing the help entry for certain options, by
1092setting the ``help`` value to ``argparse.SUPPRESS``::
1093
1094 >>> parser = argparse.ArgumentParser(prog='frobble')
1095 >>> parser.add_argument('--foo', help=argparse.SUPPRESS)
1096 >>> parser.print_help()
1097 usage: frobble [-h]
1098
1099 optional arguments:
1100 -h, --help show this help message and exit
1101
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001102
1103metavar
1104^^^^^^^
1105
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001106When :class:`ArgumentParser` generates help messages, it need some way to refer
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001107to each expected argument. By default, ArgumentParser objects use the dest_
1108value as the "name" of each object. By default, for positional argument
1109actions, the dest_ value is used directly, and for optional argument actions,
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001110the dest_ value is uppercased. So, a single positional argument with
Eli Benderskya7795db2011-11-11 10:57:01 +02001111``dest='bar'`` will be referred to as ``bar``. A single
Éric Araujofde92422011-08-19 01:30:26 +02001112optional argument ``--foo`` that should be followed by a single command-line argument
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001113will be referred to as ``FOO``. An example::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001114
1115 >>> parser = argparse.ArgumentParser()
1116 >>> parser.add_argument('--foo')
1117 >>> parser.add_argument('bar')
1118 >>> parser.parse_args('X --foo Y'.split())
1119 Namespace(bar='X', foo='Y')
1120 >>> parser.print_help()
1121 usage: [-h] [--foo FOO] bar
1122
1123 positional arguments:
1124 bar
1125
1126 optional arguments:
1127 -h, --help show this help message and exit
1128 --foo FOO
1129
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001130An alternative name can be specified with ``metavar``::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001131
1132 >>> parser = argparse.ArgumentParser()
1133 >>> parser.add_argument('--foo', metavar='YYY')
1134 >>> parser.add_argument('bar', metavar='XXX')
1135 >>> parser.parse_args('X --foo Y'.split())
1136 Namespace(bar='X', foo='Y')
1137 >>> parser.print_help()
1138 usage: [-h] [--foo YYY] XXX
1139
1140 positional arguments:
1141 XXX
1142
1143 optional arguments:
1144 -h, --help show this help message and exit
1145 --foo YYY
1146
1147Note that ``metavar`` only changes the *displayed* name - the name of the
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001148attribute on the :meth:`~ArgumentParser.parse_args` object is still determined
1149by the dest_ value.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001150
1151Different values of ``nargs`` may cause the metavar to be used multiple times.
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001152Providing a tuple to ``metavar`` specifies a different display for each of the
1153arguments::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001154
1155 >>> parser = argparse.ArgumentParser(prog='PROG')
1156 >>> parser.add_argument('-x', nargs=2)
1157 >>> parser.add_argument('--foo', nargs=2, metavar=('bar', 'baz'))
1158 >>> parser.print_help()
1159 usage: PROG [-h] [-x X X] [--foo bar baz]
1160
1161 optional arguments:
1162 -h, --help show this help message and exit
1163 -x X X
1164 --foo bar baz
1165
1166
1167dest
1168^^^^
1169
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001170Most :class:`ArgumentParser` actions add some value as an attribute of the
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001171object returned by :meth:`~ArgumentParser.parse_args`. The name of this
1172attribute is determined by the ``dest`` keyword argument of
1173:meth:`~ArgumentParser.add_argument`. For positional argument actions,
1174``dest`` is normally supplied as the first argument to
1175:meth:`~ArgumentParser.add_argument`::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001176
1177 >>> parser = argparse.ArgumentParser()
1178 >>> parser.add_argument('bar')
1179 >>> parser.parse_args('XXX'.split())
1180 Namespace(bar='XXX')
1181
1182For optional argument actions, the value of ``dest`` is normally inferred from
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001183the option strings. :class:`ArgumentParser` generates the value of ``dest`` by
Éric Araujo543edbd2011-08-19 01:45:12 +02001184taking the first long option string and stripping away the initial ``--``
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001185string. If no long option strings were supplied, ``dest`` will be derived from
Éric Araujo543edbd2011-08-19 01:45:12 +02001186the first short option string by stripping the initial ``-`` character. Any
1187internal ``-`` characters will be converted to ``_`` characters to make sure
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001188the string is a valid attribute name. The examples below illustrate this
1189behavior::
1190
1191 >>> parser = argparse.ArgumentParser()
1192 >>> parser.add_argument('-f', '--foo-bar', '--foo')
1193 >>> parser.add_argument('-x', '-y')
1194 >>> parser.parse_args('-f 1 -x 2'.split())
1195 Namespace(foo_bar='1', x='2')
1196 >>> parser.parse_args('--foo 1 -y 2'.split())
1197 Namespace(foo_bar='1', x='2')
1198
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001199``dest`` allows a custom attribute name to be provided::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001200
1201 >>> parser = argparse.ArgumentParser()
1202 >>> parser.add_argument('--foo', dest='bar')
1203 >>> parser.parse_args('--foo XXX'.split())
1204 Namespace(bar='XXX')
1205
1206
1207The parse_args() method
1208-----------------------
1209
Georg Brandle0bf91d2010-10-17 10:34:28 +00001210.. method:: ArgumentParser.parse_args(args=None, namespace=None)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001211
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001212 Convert argument strings to objects and assign them as attributes of the
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001213 namespace. Return the populated namespace.
1214
1215 Previous calls to :meth:`add_argument` determine exactly what objects are
1216 created and how they are assigned. See the documentation for
1217 :meth:`add_argument` for details.
1218
Éric Araujofde92422011-08-19 01:30:26 +02001219 By default, the argument strings are taken from :data:`sys.argv`, and a new empty
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001220 :class:`Namespace` object is created for the attributes.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001221
Georg Brandle0bf91d2010-10-17 10:34:28 +00001222
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001223Option value syntax
1224^^^^^^^^^^^^^^^^^^^
1225
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001226The :meth:`~ArgumentParser.parse_args` method supports several ways of
1227specifying the value of an option (if it takes one). In the simplest case, the
1228option and its value are passed as two separate arguments::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001229
1230 >>> parser = argparse.ArgumentParser(prog='PROG')
1231 >>> parser.add_argument('-x')
1232 >>> parser.add_argument('--foo')
1233 >>> parser.parse_args('-x X'.split())
1234 Namespace(foo=None, x='X')
1235 >>> parser.parse_args('--foo FOO'.split())
1236 Namespace(foo='FOO', x=None)
1237
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001238For long options (options with names longer than a single character), the option
Georg Brandl1d827ff2011-04-16 16:44:54 +02001239and value can also be passed as a single command-line argument, using ``=`` to
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001240separate them::
1241
1242 >>> parser.parse_args('--foo=FOO'.split())
1243 Namespace(foo='FOO', x=None)
1244
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001245For short options (options only one character long), the option and its value
1246can be concatenated::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001247
1248 >>> parser.parse_args('-xX'.split())
1249 Namespace(foo=None, x='X')
1250
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001251Several short options can be joined together, using only a single ``-`` prefix,
1252as long as only the last option (or none of them) requires a value::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001253
1254 >>> parser = argparse.ArgumentParser(prog='PROG')
1255 >>> parser.add_argument('-x', action='store_true')
1256 >>> parser.add_argument('-y', action='store_true')
1257 >>> parser.add_argument('-z')
1258 >>> parser.parse_args('-xyzZ'.split())
1259 Namespace(x=True, y=True, z='Z')
1260
1261
1262Invalid arguments
1263^^^^^^^^^^^^^^^^^
1264
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001265While parsing the command line, :meth:`~ArgumentParser.parse_args` checks for a
1266variety of errors, including ambiguous options, invalid types, invalid options,
1267wrong number of positional arguments, etc. When it encounters such an error,
1268it exits and prints the error along with a usage message::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001269
1270 >>> parser = argparse.ArgumentParser(prog='PROG')
1271 >>> parser.add_argument('--foo', type=int)
1272 >>> parser.add_argument('bar', nargs='?')
1273
1274 >>> # invalid type
1275 >>> parser.parse_args(['--foo', 'spam'])
1276 usage: PROG [-h] [--foo FOO] [bar]
1277 PROG: error: argument --foo: invalid int value: 'spam'
1278
1279 >>> # invalid option
1280 >>> parser.parse_args(['--bar'])
1281 usage: PROG [-h] [--foo FOO] [bar]
1282 PROG: error: no such option: --bar
1283
1284 >>> # wrong number of arguments
1285 >>> parser.parse_args(['spam', 'badger'])
1286 usage: PROG [-h] [--foo FOO] [bar]
1287 PROG: error: extra arguments found: badger
1288
1289
Éric Araujo543edbd2011-08-19 01:45:12 +02001290Arguments containing ``-``
1291^^^^^^^^^^^^^^^^^^^^^^^^^^
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001292
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001293The :meth:`~ArgumentParser.parse_args` method attempts to give errors whenever
1294the user has clearly made a mistake, but some situations are inherently
Éric Araujo543edbd2011-08-19 01:45:12 +02001295ambiguous. For example, the command-line argument ``-1`` could either be an
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001296attempt to specify an option or an attempt to provide a positional argument.
1297The :meth:`~ArgumentParser.parse_args` method is cautious here: positional
Éric Araujo543edbd2011-08-19 01:45:12 +02001298arguments may only begin with ``-`` if they look like negative numbers and
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001299there are no options in the parser that look like negative numbers::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001300
1301 >>> parser = argparse.ArgumentParser(prog='PROG')
1302 >>> parser.add_argument('-x')
1303 >>> parser.add_argument('foo', nargs='?')
1304
1305 >>> # no negative number options, so -1 is a positional argument
1306 >>> parser.parse_args(['-x', '-1'])
1307 Namespace(foo=None, x='-1')
1308
1309 >>> # no negative number options, so -1 and -5 are positional arguments
1310 >>> parser.parse_args(['-x', '-1', '-5'])
1311 Namespace(foo='-5', x='-1')
1312
1313 >>> parser = argparse.ArgumentParser(prog='PROG')
1314 >>> parser.add_argument('-1', dest='one')
1315 >>> parser.add_argument('foo', nargs='?')
1316
1317 >>> # negative number options present, so -1 is an option
1318 >>> parser.parse_args(['-1', 'X'])
1319 Namespace(foo=None, one='X')
1320
1321 >>> # negative number options present, so -2 is an option
1322 >>> parser.parse_args(['-2'])
1323 usage: PROG [-h] [-1 ONE] [foo]
1324 PROG: error: no such option: -2
1325
1326 >>> # negative number options present, so both -1s are options
1327 >>> parser.parse_args(['-1', '-1'])
1328 usage: PROG [-h] [-1 ONE] [foo]
1329 PROG: error: argument -1: expected one argument
1330
Éric Araujo543edbd2011-08-19 01:45:12 +02001331If you have positional arguments that must begin with ``-`` and don't look
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001332like negative numbers, you can insert the pseudo-argument ``'--'`` which tells
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001333:meth:`~ArgumentParser.parse_args` that everything after that is a positional
1334argument::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001335
1336 >>> parser.parse_args(['--', '-f'])
1337 Namespace(foo='-f', one=None)
1338
1339
1340Argument abbreviations
1341^^^^^^^^^^^^^^^^^^^^^^
1342
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001343The :meth:`~ArgumentParser.parse_args` method allows long options to be
1344abbreviated if the abbreviation is unambiguous::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001345
1346 >>> parser = argparse.ArgumentParser(prog='PROG')
1347 >>> parser.add_argument('-bacon')
1348 >>> parser.add_argument('-badger')
1349 >>> parser.parse_args('-bac MMM'.split())
1350 Namespace(bacon='MMM', badger=None)
1351 >>> parser.parse_args('-bad WOOD'.split())
1352 Namespace(bacon=None, badger='WOOD')
1353 >>> parser.parse_args('-ba BA'.split())
1354 usage: PROG [-h] [-bacon BACON] [-badger BADGER]
1355 PROG: error: ambiguous option: -ba could match -badger, -bacon
1356
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001357An error is produced for arguments that could produce more than one options.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001358
1359
1360Beyond ``sys.argv``
1361^^^^^^^^^^^^^^^^^^^
1362
Éric Araujod9d7bca2011-08-10 04:19:03 +02001363Sometimes it may be useful to have an ArgumentParser parse arguments other than those
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001364of :data:`sys.argv`. This can be accomplished by passing a list of strings to
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001365:meth:`~ArgumentParser.parse_args`. This is useful for testing at the
1366interactive prompt::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001367
1368 >>> parser = argparse.ArgumentParser()
1369 >>> parser.add_argument(
Fred Drakec7eb7892011-03-03 05:29:59 +00001370 ... 'integers', metavar='int', type=int, choices=range(10),
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001371 ... nargs='+', help='an integer in the range 0..9')
1372 >>> parser.add_argument(
1373 ... '--sum', dest='accumulate', action='store_const', const=sum,
1374 ... default=max, help='sum the integers (default: find the max)')
1375 >>> parser.parse_args(['1', '2', '3', '4'])
1376 Namespace(accumulate=<built-in function max>, integers=[1, 2, 3, 4])
1377 >>> parser.parse_args('1 2 3 4 --sum'.split())
1378 Namespace(accumulate=<built-in function sum>, integers=[1, 2, 3, 4])
1379
1380
Steven Bethardd8f2d502011-03-26 19:50:06 +01001381The Namespace object
1382^^^^^^^^^^^^^^^^^^^^
1383
Éric Araujo63b18a42011-07-29 17:59:17 +02001384.. class:: Namespace
1385
1386 Simple class used by default by :meth:`~ArgumentParser.parse_args` to create
1387 an object holding attributes and return it.
1388
1389This class is deliberately simple, just an :class:`object` subclass with a
1390readable string representation. If you prefer to have dict-like view of the
1391attributes, you can use the standard Python idiom, :func:`vars`::
Steven Bethardd8f2d502011-03-26 19:50:06 +01001392
1393 >>> parser = argparse.ArgumentParser()
1394 >>> parser.add_argument('--foo')
1395 >>> args = parser.parse_args(['--foo', 'BAR'])
1396 >>> vars(args)
1397 {'foo': 'BAR'}
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001398
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001399It may also be useful to have an :class:`ArgumentParser` assign attributes to an
Steven Bethardd8f2d502011-03-26 19:50:06 +01001400already existing object, rather than a new :class:`Namespace` object. This can
1401be achieved by specifying the ``namespace=`` keyword argument::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001402
Éric Araujo28053fb2010-11-22 03:09:19 +00001403 >>> class C:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001404 ... pass
1405 ...
1406 >>> c = C()
1407 >>> parser = argparse.ArgumentParser()
1408 >>> parser.add_argument('--foo')
1409 >>> parser.parse_args(args=['--foo', 'BAR'], namespace=c)
1410 >>> c.foo
1411 'BAR'
1412
1413
1414Other utilities
1415---------------
1416
1417Sub-commands
1418^^^^^^^^^^^^
1419
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001420.. method:: ArgumentParser.add_subparsers()
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001421
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001422 Many programs split up their functionality into a number of sub-commands,
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001423 for example, the ``svn`` program can invoke sub-commands like ``svn
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001424 checkout``, ``svn update``, and ``svn commit``. Splitting up functionality
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001425 this way can be a particularly good idea when a program performs several
1426 different functions which require different kinds of command-line arguments.
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001427 :class:`ArgumentParser` supports the creation of such sub-commands with the
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001428 :meth:`add_subparsers` method. The :meth:`add_subparsers` method is normally
1429 called with no arguments and returns an special action object. This object
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001430 has a single method, :meth:`~ArgumentParser.add_parser`, which takes a
1431 command name and any :class:`ArgumentParser` constructor arguments, and
1432 returns an :class:`ArgumentParser` object that can be modified as usual.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001433
1434 Some example usage::
1435
1436 >>> # create the top-level parser
1437 >>> parser = argparse.ArgumentParser(prog='PROG')
1438 >>> parser.add_argument('--foo', action='store_true', help='foo help')
1439 >>> subparsers = parser.add_subparsers(help='sub-command help')
1440 >>>
1441 >>> # create the parser for the "a" command
1442 >>> parser_a = subparsers.add_parser('a', help='a help')
1443 >>> parser_a.add_argument('bar', type=int, help='bar help')
1444 >>>
1445 >>> # create the parser for the "b" command
1446 >>> parser_b = subparsers.add_parser('b', help='b help')
1447 >>> parser_b.add_argument('--baz', choices='XYZ', help='baz help')
1448 >>>
Éric Araujofde92422011-08-19 01:30:26 +02001449 >>> # parse some argument lists
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001450 >>> parser.parse_args(['a', '12'])
1451 Namespace(bar=12, foo=False)
1452 >>> parser.parse_args(['--foo', 'b', '--baz', 'Z'])
1453 Namespace(baz='Z', foo=True)
1454
1455 Note that the object returned by :meth:`parse_args` will only contain
1456 attributes for the main parser and the subparser that was selected by the
1457 command line (and not any other subparsers). So in the example above, when
Éric Araujo543edbd2011-08-19 01:45:12 +02001458 the ``a`` command is specified, only the ``foo`` and ``bar`` attributes are
1459 present, and when the ``b`` command is specified, only the ``foo`` and
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001460 ``baz`` attributes are present.
1461
1462 Similarly, when a help message is requested from a subparser, only the help
1463 for that particular parser will be printed. The help message will not
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001464 include parent parser or sibling parser messages. (A help message for each
1465 subparser command, however, can be given by supplying the ``help=`` argument
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001466 to :meth:`add_parser` as above.)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001467
1468 ::
1469
1470 >>> parser.parse_args(['--help'])
1471 usage: PROG [-h] [--foo] {a,b} ...
1472
1473 positional arguments:
1474 {a,b} sub-command help
1475 a a help
1476 b b help
1477
1478 optional arguments:
1479 -h, --help show this help message and exit
1480 --foo foo help
1481
1482 >>> parser.parse_args(['a', '--help'])
1483 usage: PROG a [-h] bar
1484
1485 positional arguments:
1486 bar bar help
1487
1488 optional arguments:
1489 -h, --help show this help message and exit
1490
1491 >>> parser.parse_args(['b', '--help'])
1492 usage: PROG b [-h] [--baz {X,Y,Z}]
1493
1494 optional arguments:
1495 -h, --help show this help message and exit
1496 --baz {X,Y,Z} baz help
1497
1498 The :meth:`add_subparsers` method also supports ``title`` and ``description``
1499 keyword arguments. When either is present, the subparser's commands will
1500 appear in their own group in the help output. For example::
1501
1502 >>> parser = argparse.ArgumentParser()
1503 >>> subparsers = parser.add_subparsers(title='subcommands',
1504 ... description='valid subcommands',
1505 ... help='additional help')
1506 >>> subparsers.add_parser('foo')
1507 >>> subparsers.add_parser('bar')
1508 >>> parser.parse_args(['-h'])
1509 usage: [-h] {foo,bar} ...
1510
1511 optional arguments:
1512 -h, --help show this help message and exit
1513
1514 subcommands:
1515 valid subcommands
1516
1517 {foo,bar} additional help
1518
Steven Bethardfd311a72010-12-18 11:19:23 +00001519 Furthermore, ``add_parser`` supports an additional ``aliases`` argument,
1520 which allows multiple strings to refer to the same subparser. This example,
1521 like ``svn``, aliases ``co`` as a shorthand for ``checkout``::
1522
1523 >>> parser = argparse.ArgumentParser()
1524 >>> subparsers = parser.add_subparsers()
1525 >>> checkout = subparsers.add_parser('checkout', aliases=['co'])
1526 >>> checkout.add_argument('foo')
1527 >>> parser.parse_args(['co', 'bar'])
1528 Namespace(foo='bar')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001529
1530 One particularly effective way of handling sub-commands is to combine the use
1531 of the :meth:`add_subparsers` method with calls to :meth:`set_defaults` so
1532 that each subparser knows which Python function it should execute. For
1533 example::
1534
1535 >>> # sub-command functions
1536 >>> def foo(args):
Benjamin Petersonb2deb112010-03-03 02:09:18 +00001537 ... print(args.x * args.y)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001538 ...
1539 >>> def bar(args):
Benjamin Petersonb2deb112010-03-03 02:09:18 +00001540 ... print('((%s))' % args.z)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001541 ...
1542 >>> # create the top-level parser
1543 >>> parser = argparse.ArgumentParser()
1544 >>> subparsers = parser.add_subparsers()
1545 >>>
1546 >>> # create the parser for the "foo" command
1547 >>> parser_foo = subparsers.add_parser('foo')
1548 >>> parser_foo.add_argument('-x', type=int, default=1)
1549 >>> parser_foo.add_argument('y', type=float)
1550 >>> parser_foo.set_defaults(func=foo)
1551 >>>
1552 >>> # create the parser for the "bar" command
1553 >>> parser_bar = subparsers.add_parser('bar')
1554 >>> parser_bar.add_argument('z')
1555 >>> parser_bar.set_defaults(func=bar)
1556 >>>
1557 >>> # parse the args and call whatever function was selected
1558 >>> args = parser.parse_args('foo 1 -x 2'.split())
1559 >>> args.func(args)
1560 2.0
1561 >>>
1562 >>> # parse the args and call whatever function was selected
1563 >>> args = parser.parse_args('bar XYZYX'.split())
1564 >>> args.func(args)
1565 ((XYZYX))
1566
Steven Bethardfd311a72010-12-18 11:19:23 +00001567 This way, you can let :meth:`parse_args` do the job of calling the
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001568 appropriate function after argument parsing is complete. Associating
1569 functions with actions like this is typically the easiest way to handle the
1570 different actions for each of your subparsers. However, if it is necessary
1571 to check the name of the subparser that was invoked, the ``dest`` keyword
1572 argument to the :meth:`add_subparsers` call will work::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001573
1574 >>> parser = argparse.ArgumentParser()
1575 >>> subparsers = parser.add_subparsers(dest='subparser_name')
1576 >>> subparser1 = subparsers.add_parser('1')
1577 >>> subparser1.add_argument('-x')
1578 >>> subparser2 = subparsers.add_parser('2')
1579 >>> subparser2.add_argument('y')
1580 >>> parser.parse_args(['2', 'frobble'])
1581 Namespace(subparser_name='2', y='frobble')
1582
1583
1584FileType objects
1585^^^^^^^^^^^^^^^^
1586
1587.. class:: FileType(mode='r', bufsize=None)
1588
1589 The :class:`FileType` factory creates objects that can be passed to the type
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001590 argument of :meth:`ArgumentParser.add_argument`. Arguments that have
Éric Araujod9d7bca2011-08-10 04:19:03 +02001591 :class:`FileType` objects as their type will open command-line arguments as files
Éric Araujoc3ef0372012-02-20 01:44:55 +01001592 with the requested modes and buffer sizes::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001593
Éric Araujoc3ef0372012-02-20 01:44:55 +01001594 >>> parser = argparse.ArgumentParser()
1595 >>> parser.add_argument('--output', type=argparse.FileType('wb', 0))
1596 >>> parser.parse_args(['--output', 'out'])
1597 Namespace(output=<_io.BufferedWriter name='out'>)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001598
1599 FileType objects understand the pseudo-argument ``'-'`` and automatically
1600 convert this into ``sys.stdin`` for readable :class:`FileType` objects and
Éric Araujoc3ef0372012-02-20 01:44:55 +01001601 ``sys.stdout`` for writable :class:`FileType` objects::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001602
Éric Araujoc3ef0372012-02-20 01:44:55 +01001603 >>> parser = argparse.ArgumentParser()
1604 >>> parser.add_argument('infile', type=argparse.FileType('r'))
1605 >>> parser.parse_args(['-'])
1606 Namespace(infile=<_io.TextIOWrapper name='<stdin>' encoding='UTF-8'>)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001607
1608
1609Argument groups
1610^^^^^^^^^^^^^^^
1611
Georg Brandle0bf91d2010-10-17 10:34:28 +00001612.. method:: ArgumentParser.add_argument_group(title=None, description=None)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001613
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001614 By default, :class:`ArgumentParser` groups command-line arguments into
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001615 "positional arguments" and "optional arguments" when displaying help
1616 messages. When there is a better conceptual grouping of arguments than this
1617 default one, appropriate groups can be created using the
1618 :meth:`add_argument_group` method::
1619
1620 >>> parser = argparse.ArgumentParser(prog='PROG', add_help=False)
1621 >>> group = parser.add_argument_group('group')
1622 >>> group.add_argument('--foo', help='foo help')
1623 >>> group.add_argument('bar', help='bar help')
1624 >>> parser.print_help()
1625 usage: PROG [--foo FOO] bar
1626
1627 group:
1628 bar bar help
1629 --foo FOO foo help
1630
1631 The :meth:`add_argument_group` method returns an argument group object which
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001632 has an :meth:`~ArgumentParser.add_argument` method just like a regular
1633 :class:`ArgumentParser`. When an argument is added to the group, the parser
1634 treats it just like a normal argument, but displays the argument in a
1635 separate group for help messages. The :meth:`add_argument_group` method
Georg Brandle0bf91d2010-10-17 10:34:28 +00001636 accepts *title* and *description* arguments which can be used to
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001637 customize this display::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001638
1639 >>> parser = argparse.ArgumentParser(prog='PROG', add_help=False)
1640 >>> group1 = parser.add_argument_group('group1', 'group1 description')
1641 >>> group1.add_argument('foo', help='foo help')
1642 >>> group2 = parser.add_argument_group('group2', 'group2 description')
1643 >>> group2.add_argument('--bar', help='bar help')
1644 >>> parser.print_help()
1645 usage: PROG [--bar BAR] foo
1646
1647 group1:
1648 group1 description
1649
1650 foo foo help
1651
1652 group2:
1653 group2 description
1654
1655 --bar BAR bar help
1656
Sandro Tosi99e7d072012-03-26 19:36:23 +02001657 Note that any arguments not in your user-defined groups will end up back
1658 in the usual "positional arguments" and "optional arguments" sections.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001659
1660
1661Mutual exclusion
1662^^^^^^^^^^^^^^^^
1663
Georg Brandle0bf91d2010-10-17 10:34:28 +00001664.. method:: add_mutually_exclusive_group(required=False)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001665
Ezio Melotti0ee9c1b2011-04-21 16:12:17 +03001666 Create a mutually exclusive group. :mod:`argparse` will make sure that only
1667 one of the arguments in the mutually exclusive group was present on the
1668 command line::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001669
1670 >>> parser = argparse.ArgumentParser(prog='PROG')
1671 >>> group = parser.add_mutually_exclusive_group()
1672 >>> group.add_argument('--foo', action='store_true')
1673 >>> group.add_argument('--bar', action='store_false')
1674 >>> parser.parse_args(['--foo'])
1675 Namespace(bar=True, foo=True)
1676 >>> parser.parse_args(['--bar'])
1677 Namespace(bar=False, foo=False)
1678 >>> parser.parse_args(['--foo', '--bar'])
1679 usage: PROG [-h] [--foo | --bar]
1680 PROG: error: argument --bar: not allowed with argument --foo
1681
Georg Brandle0bf91d2010-10-17 10:34:28 +00001682 The :meth:`add_mutually_exclusive_group` method also accepts a *required*
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001683 argument, to indicate that at least one of the mutually exclusive arguments
1684 is required::
1685
1686 >>> parser = argparse.ArgumentParser(prog='PROG')
1687 >>> group = parser.add_mutually_exclusive_group(required=True)
1688 >>> group.add_argument('--foo', action='store_true')
1689 >>> group.add_argument('--bar', action='store_false')
1690 >>> parser.parse_args([])
1691 usage: PROG [-h] (--foo | --bar)
1692 PROG: error: one of the arguments --foo --bar is required
1693
1694 Note that currently mutually exclusive argument groups do not support the
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001695 *title* and *description* arguments of
1696 :meth:`~ArgumentParser.add_argument_group`.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001697
1698
1699Parser defaults
1700^^^^^^^^^^^^^^^
1701
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001702.. method:: ArgumentParser.set_defaults(**kwargs)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001703
1704 Most of the time, the attributes of the object returned by :meth:`parse_args`
Éric Araujod9d7bca2011-08-10 04:19:03 +02001705 will be fully determined by inspecting the command-line arguments and the argument
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001706 actions. :meth:`set_defaults` allows some additional
Georg Brandl1d827ff2011-04-16 16:44:54 +02001707 attributes that are determined without any inspection of the command line to
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001708 be added::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001709
1710 >>> parser = argparse.ArgumentParser()
1711 >>> parser.add_argument('foo', type=int)
1712 >>> parser.set_defaults(bar=42, baz='badger')
1713 >>> parser.parse_args(['736'])
1714 Namespace(bar=42, baz='badger', foo=736)
1715
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001716 Note that parser-level defaults always override argument-level defaults::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001717
1718 >>> parser = argparse.ArgumentParser()
1719 >>> parser.add_argument('--foo', default='bar')
1720 >>> parser.set_defaults(foo='spam')
1721 >>> parser.parse_args([])
1722 Namespace(foo='spam')
1723
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001724 Parser-level defaults can be particularly useful when working with multiple
1725 parsers. See the :meth:`~ArgumentParser.add_subparsers` method for an
1726 example of this type.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001727
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001728.. method:: ArgumentParser.get_default(dest)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001729
1730 Get the default value for a namespace attribute, as set by either
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001731 :meth:`~ArgumentParser.add_argument` or by
1732 :meth:`~ArgumentParser.set_defaults`::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001733
1734 >>> parser = argparse.ArgumentParser()
1735 >>> parser.add_argument('--foo', default='badger')
1736 >>> parser.get_default('foo')
1737 'badger'
1738
1739
1740Printing help
1741^^^^^^^^^^^^^
1742
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001743In most typical applications, :meth:`~ArgumentParser.parse_args` will take
1744care of formatting and printing any usage or error messages. However, several
1745formatting methods are available:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001746
Georg Brandle0bf91d2010-10-17 10:34:28 +00001747.. method:: ArgumentParser.print_usage(file=None)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001748
1749 Print a brief description of how the :class:`ArgumentParser` should be
R. David Murray32e17712010-12-18 16:39:06 +00001750 invoked on the command line. If *file* is ``None``, :data:`sys.stdout` is
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001751 assumed.
1752
Georg Brandle0bf91d2010-10-17 10:34:28 +00001753.. method:: ArgumentParser.print_help(file=None)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001754
1755 Print a help message, including the program usage and information about the
Georg Brandle0bf91d2010-10-17 10:34:28 +00001756 arguments registered with the :class:`ArgumentParser`. If *file* is
R. David Murray32e17712010-12-18 16:39:06 +00001757 ``None``, :data:`sys.stdout` is assumed.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001758
1759There are also variants of these methods that simply return a string instead of
1760printing it:
1761
Georg Brandle0bf91d2010-10-17 10:34:28 +00001762.. method:: ArgumentParser.format_usage()
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001763
1764 Return a string containing a brief description of how the
1765 :class:`ArgumentParser` should be invoked on the command line.
1766
Georg Brandle0bf91d2010-10-17 10:34:28 +00001767.. method:: ArgumentParser.format_help()
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001768
1769 Return a string containing a help message, including the program usage and
1770 information about the arguments registered with the :class:`ArgumentParser`.
1771
1772
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001773Partial parsing
1774^^^^^^^^^^^^^^^
1775
Georg Brandle0bf91d2010-10-17 10:34:28 +00001776.. method:: ArgumentParser.parse_known_args(args=None, namespace=None)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001777
Georg Brandl1d827ff2011-04-16 16:44:54 +02001778Sometimes a script may only parse a few of the command-line arguments, passing
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001779the remaining arguments on to another script or program. In these cases, the
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001780:meth:`~ArgumentParser.parse_known_args` method can be useful. It works much like
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001781:meth:`~ArgumentParser.parse_args` except that it does not produce an error when
1782extra arguments are present. Instead, it returns a two item tuple containing
1783the populated namespace and the list of remaining argument strings.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001784
1785::
1786
1787 >>> parser = argparse.ArgumentParser()
1788 >>> parser.add_argument('--foo', action='store_true')
1789 >>> parser.add_argument('bar')
1790 >>> parser.parse_known_args(['--foo', '--badger', 'BAR', 'spam'])
1791 (Namespace(bar='BAR', foo=True), ['--badger', 'spam'])
1792
1793
1794Customizing file parsing
1795^^^^^^^^^^^^^^^^^^^^^^^^
1796
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001797.. method:: ArgumentParser.convert_arg_line_to_args(arg_line)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001798
Georg Brandle0bf91d2010-10-17 10:34:28 +00001799 Arguments that are read from a file (see the *fromfile_prefix_chars*
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001800 keyword argument to the :class:`ArgumentParser` constructor) are read one
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001801 argument per line. :meth:`convert_arg_line_to_args` can be overriden for
1802 fancier reading.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001803
Georg Brandle0bf91d2010-10-17 10:34:28 +00001804 This method takes a single argument *arg_line* which is a string read from
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001805 the argument file. It returns a list of arguments parsed from this string.
1806 The method is called once per line read from the argument file, in order.
1807
1808 A useful override of this method is one that treats each space-separated word
1809 as an argument::
1810
1811 def convert_arg_line_to_args(self, arg_line):
1812 for arg in arg_line.split():
1813 if not arg.strip():
1814 continue
1815 yield arg
1816
1817
Georg Brandl93754922010-10-17 10:28:04 +00001818Exiting methods
1819^^^^^^^^^^^^^^^
1820
1821.. method:: ArgumentParser.exit(status=0, message=None)
1822
1823 This method terminates the program, exiting with the specified *status*
1824 and, if given, it prints a *message* before that.
1825
1826.. method:: ArgumentParser.error(message)
1827
1828 This method prints a usage message including the *message* to the
Senthil Kumaran86a1a892011-08-03 07:42:18 +08001829 standard error and terminates the program with a status code of 2.
Georg Brandl93754922010-10-17 10:28:04 +00001830
Raymond Hettinger677e10a2010-12-07 06:45:30 +00001831.. _upgrading-optparse-code:
Georg Brandl93754922010-10-17 10:28:04 +00001832
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001833Upgrading optparse code
1834-----------------------
1835
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001836Originally, the :mod:`argparse` module had attempted to maintain compatibility
Ezio Melotti0ee9c1b2011-04-21 16:12:17 +03001837with :mod:`optparse`. However, :mod:`optparse` was difficult to extend
1838transparently, particularly with the changes required to support the new
1839``nargs=`` specifiers and better usage messages. When most everything in
1840:mod:`optparse` had either been copy-pasted over or monkey-patched, it no
1841longer seemed practical to try to maintain the backwards compatibility.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001842
Ezio Melotti0ee9c1b2011-04-21 16:12:17 +03001843A partial upgrade path from :mod:`optparse` to :mod:`argparse`:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001844
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001845* Replace all :meth:`optparse.OptionParser.add_option` calls with
1846 :meth:`ArgumentParser.add_argument` calls.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001847
R David Murray5e0c5712012-03-30 18:07:42 -04001848* Replace ``(options, args) = parser.parse_args()`` with ``args =
Georg Brandlc9007082011-01-09 09:04:08 +00001849 parser.parse_args()`` and add additional :meth:`ArgumentParser.add_argument`
R David Murray5e0c5712012-03-30 18:07:42 -04001850 calls for the positional arguments. Keep in mind that what was previously
1851 called ``options``, now in :mod:`argparse` context is called ``args``.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001852
1853* Replace callback actions and the ``callback_*`` keyword arguments with
1854 ``type`` or ``action`` arguments.
1855
1856* Replace string names for ``type`` keyword arguments with the corresponding
1857 type objects (e.g. int, float, complex, etc).
1858
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001859* Replace :class:`optparse.Values` with :class:`Namespace` and
1860 :exc:`optparse.OptionError` and :exc:`optparse.OptionValueError` with
1861 :exc:`ArgumentError`.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001862
1863* Replace strings with implicit arguments such as ``%default`` or ``%prog`` with
Ezio Melotticca4ef82011-04-21 15:26:46 +03001864 the standard Python syntax to use dictionaries to format strings, that is,
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001865 ``%(default)s`` and ``%(prog)s``.
Steven Bethard59710962010-05-24 03:21:08 +00001866
1867* Replace the OptionParser constructor ``version`` argument with a call to
1868 ``parser.add_argument('--version', action='version', version='<the version>')``