blob: 8bd3ca53bb5e846adcf0b0cbe5a2832a82901973 [file] [log] [blame]
Georg Brandle0bf91d2010-10-17 10:34:28 +00001:mod:`argparse` --- Parser for command line options, arguments and sub-commands
2===============================================================================
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003
4.. module:: argparse
5 :synopsis: Command-line option and argument parsing library.
6.. 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**Source code:** :source:`Lib/argparse.py`
10
11.. versionadded:: 3.2
12
13--------------
Benjamin Peterson698a18a2010-03-02 22:34:37 +000014
15The :mod:`argparse` module makes it easy to write user friendly command line
Benjamin Peterson98047eb2010-03-03 02:07:08 +000016interfaces. The program defines what arguments it requires, and :mod:`argparse`
Benjamin Peterson698a18a2010-03-02 22:34:37 +000017will figure out how to parse those out of :data:`sys.argv`. The :mod:`argparse`
Benjamin Peterson98047eb2010-03-03 02:07:08 +000018module also automatically generates help and usage messages and issues errors
19when users give the program invalid arguments.
Benjamin Peterson698a18a2010-03-02 22:34:37 +000020
Georg Brandle0bf91d2010-10-17 10:34:28 +000021
Benjamin Peterson698a18a2010-03-02 22:34:37 +000022Example
23-------
24
Benjamin Peterson98047eb2010-03-03 02:07:08 +000025The following code is a Python program that takes a list of integers and
26produces either the sum or the max::
Benjamin Peterson698a18a2010-03-02 22:34:37 +000027
28 import argparse
29
30 parser = argparse.ArgumentParser(description='Process some integers.')
31 parser.add_argument('integers', metavar='N', type=int, nargs='+',
32 help='an integer for the accumulator')
33 parser.add_argument('--sum', dest='accumulate', action='store_const',
34 const=sum, default=max,
35 help='sum the integers (default: find the max)')
36
37 args = parser.parse_args()
Benjamin Petersonb2deb112010-03-03 02:09:18 +000038 print(args.accumulate(args.integers))
Benjamin Peterson698a18a2010-03-02 22:34:37 +000039
40Assuming the Python code above is saved into a file called ``prog.py``, it can
41be run at the command line and provides useful help messages::
42
43 $ prog.py -h
44 usage: prog.py [-h] [--sum] N [N ...]
45
46 Process some integers.
47
48 positional arguments:
49 N an integer for the accumulator
50
51 optional arguments:
52 -h, --help show this help message and exit
53 --sum sum the integers (default: find the max)
54
55When run with the appropriate arguments, it prints either the sum or the max of
56the command-line integers::
57
58 $ prog.py 1 2 3 4
59 4
60
61 $ prog.py 1 2 3 4 --sum
62 10
63
64If invalid arguments are passed in, it will issue an error::
65
66 $ prog.py a b c
67 usage: prog.py [-h] [--sum] N [N ...]
68 prog.py: error: argument N: invalid int value: 'a'
69
70The following sections walk you through this example.
71
Georg Brandle0bf91d2010-10-17 10:34:28 +000072
Benjamin Peterson698a18a2010-03-02 22:34:37 +000073Creating a parser
74^^^^^^^^^^^^^^^^^
75
Benjamin Peterson2614cda2010-03-21 22:36:19 +000076The first step in using the :mod:`argparse` is creating an
Benjamin Peterson98047eb2010-03-03 02:07:08 +000077:class:`ArgumentParser` object::
Benjamin Peterson698a18a2010-03-02 22:34:37 +000078
79 >>> parser = argparse.ArgumentParser(description='Process some integers.')
80
81The :class:`ArgumentParser` object will hold all the information necessary to
Benjamin Peterson98047eb2010-03-03 02:07:08 +000082parse the command line into python data types.
Benjamin Peterson698a18a2010-03-02 22:34:37 +000083
84
85Adding arguments
86^^^^^^^^^^^^^^^^
87
Benjamin Peterson98047eb2010-03-03 02:07:08 +000088Filling an :class:`ArgumentParser` with information about program arguments is
89done by making calls to the :meth:`~ArgumentParser.add_argument` method.
90Generally, these calls tell the :class:`ArgumentParser` how to take the strings
91on the command line and turn them into objects. This information is stored and
92used when :meth:`~ArgumentParser.parse_args` is called. For example::
Benjamin Peterson698a18a2010-03-02 22:34:37 +000093
94 >>> parser.add_argument('integers', metavar='N', type=int, nargs='+',
95 ... help='an integer for the accumulator')
96 >>> parser.add_argument('--sum', dest='accumulate', action='store_const',
97 ... const=sum, default=max,
98 ... help='sum the integers (default: find the max)')
99
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000100Later, calling :meth:`parse_args` will return an object with
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000101two attributes, ``integers`` and ``accumulate``. The ``integers`` attribute
102will be a list of one or more ints, and the ``accumulate`` attribute will be
103either the :func:`sum` function, if ``--sum`` was specified at the command line,
104or the :func:`max` function if it was not.
105
Georg Brandle0bf91d2010-10-17 10:34:28 +0000106
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000107Parsing arguments
108^^^^^^^^^^^^^^^^^
109
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000110:class:`ArgumentParser` parses args through the
111:meth:`~ArgumentParser.parse_args` method. This will inspect the command-line,
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000112convert each arg to the appropriate type and then invoke the appropriate action.
113In most cases, this means a simple namespace object will be built up from
114attributes parsed out of the command-line::
115
116 >>> parser.parse_args(['--sum', '7', '-1', '42'])
117 Namespace(accumulate=<built-in function sum>, integers=[7, -1, 42])
118
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000119In a script, :meth:`~ArgumentParser.parse_args` will typically be called with no
120arguments, and the :class:`ArgumentParser` will automatically determine the
121command-line args from :data:`sys.argv`.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000122
123
124ArgumentParser objects
125----------------------
126
Georg Brandlc9007082011-01-09 09:04:08 +0000127.. class:: ArgumentParser([description], [epilog], [prog], [usage], [add_help], \
128 [argument_default], [parents], [prefix_chars], \
129 [conflict_handler], [formatter_class])
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000130
131 Create a new :class:`ArgumentParser` object. Each parameter has its own more
132 detailed description below, but in short they are:
133
134 * description_ - Text to display before the argument help.
135
136 * epilog_ - Text to display after the argument help.
137
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000138 * add_help_ - Add a -h/--help option to the parser. (default: ``True``)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000139
140 * argument_default_ - Set the global default value for arguments.
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000141 (default: ``None``)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000142
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000143 * parents_ - A list of :class:`ArgumentParser` objects whose arguments should
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000144 also be included.
145
146 * prefix_chars_ - The set of characters that prefix optional arguments.
147 (default: '-')
148
149 * fromfile_prefix_chars_ - The set of characters that prefix files from
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000150 which additional arguments should be read. (default: ``None``)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000151
152 * formatter_class_ - A class for customizing the help output.
153
154 * conflict_handler_ - Usually unnecessary, defines strategy for resolving
155 conflicting optionals.
156
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000157 * prog_ - The name of the program (default:
158 :data:`sys.argv[0]`)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000159
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000160 * usage_ - The string describing the program usage (default: generated)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000161
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000162The following sections describe how each of these are used.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000163
164
165description
166^^^^^^^^^^^
167
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000168Most calls to the :class:`ArgumentParser` constructor will use the
169``description=`` keyword argument. This argument gives a brief description of
170what the program does and how it works. In help messages, the description is
171displayed between the command-line usage string and the help messages for the
172various arguments::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000173
174 >>> parser = argparse.ArgumentParser(description='A foo that bars')
175 >>> parser.print_help()
176 usage: argparse.py [-h]
177
178 A foo that bars
179
180 optional arguments:
181 -h, --help show this help message and exit
182
183By default, the description will be line-wrapped so that it fits within the
184given space. To change this behavior, see the formatter_class_ argument.
185
186
187epilog
188^^^^^^
189
190Some programs like to display additional description of the program after the
191description of the arguments. Such text can be specified using the ``epilog=``
192argument to :class:`ArgumentParser`::
193
194 >>> parser = argparse.ArgumentParser(
195 ... description='A foo that bars',
196 ... epilog="And that's how you'd foo a bar")
197 >>> parser.print_help()
198 usage: argparse.py [-h]
199
200 A foo that bars
201
202 optional arguments:
203 -h, --help show this help message and exit
204
205 And that's how you'd foo a bar
206
207As with the description_ argument, the ``epilog=`` text is by default
208line-wrapped, but this behavior can be adjusted with the formatter_class_
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000209argument to :class:`ArgumentParser`.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000210
211
212add_help
213^^^^^^^^
214
R. David Murray88c49fe2010-08-03 17:56:09 +0000215By default, ArgumentParser objects add an option which simply displays
216the parser's help message. For example, consider a file named
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000217``myprogram.py`` containing the following code::
218
219 import argparse
220 parser = argparse.ArgumentParser()
221 parser.add_argument('--foo', help='foo help')
222 args = parser.parse_args()
223
224If ``-h`` or ``--help`` is supplied is at the command-line, the ArgumentParser
225help will be printed::
226
227 $ python myprogram.py --help
228 usage: myprogram.py [-h] [--foo FOO]
229
230 optional arguments:
231 -h, --help show this help message and exit
232 --foo FOO foo help
233
234Occasionally, it may be useful to disable the addition of this help option.
235This can be achieved by passing ``False`` as the ``add_help=`` argument to
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000236:class:`ArgumentParser`::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000237
238 >>> parser = argparse.ArgumentParser(prog='PROG', add_help=False)
239 >>> parser.add_argument('--foo', help='foo help')
240 >>> parser.print_help()
241 usage: PROG [--foo FOO]
242
243 optional arguments:
244 --foo FOO foo help
245
R. David Murray88c49fe2010-08-03 17:56:09 +0000246The help option is typically ``-h/--help``. The exception to this is
247if the ``prefix_chars=`` is specified and does not include ``'-'``, in
248which case ``-h`` and ``--help`` are not valid options. In
249this case, the first character in ``prefix_chars`` is used to prefix
250the help options::
251
252 >>> parser = argparse.ArgumentParser(prog='PROG', prefix_chars='+/')
253 >>> parser.print_help()
254 usage: PROG [+h]
255
256 optional arguments:
257 +h, ++help show this help message and exit
258
259
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000260prefix_chars
261^^^^^^^^^^^^
262
263Most command-line options will use ``'-'`` as the prefix, e.g. ``-f/--foo``.
R. David Murray88c49fe2010-08-03 17:56:09 +0000264Parsers that need to support different or additional prefix
265characters, e.g. for options
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000266like ``+f`` or ``/foo``, may specify them using the ``prefix_chars=`` argument
267to the ArgumentParser constructor::
268
269 >>> parser = argparse.ArgumentParser(prog='PROG', prefix_chars='-+')
270 >>> parser.add_argument('+f')
271 >>> parser.add_argument('++bar')
272 >>> parser.parse_args('+f X ++bar Y'.split())
273 Namespace(bar='Y', f='X')
274
275The ``prefix_chars=`` argument defaults to ``'-'``. Supplying a set of
276characters that does not include ``'-'`` will cause ``-f/--foo`` options to be
277disallowed.
278
279
280fromfile_prefix_chars
281^^^^^^^^^^^^^^^^^^^^^
282
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000283Sometimes, for example when dealing with a particularly long argument lists, it
284may make sense to keep the list of arguments in a file rather than typing it out
285at the command line. If the ``fromfile_prefix_chars=`` argument is given to the
286:class:`ArgumentParser` constructor, then arguments that start with any of the
287specified characters will be treated as files, and will be replaced by the
288arguments they contain. For example::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000289
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000290 >>> with open('args.txt', 'w') as fp:
291 ... fp.write('-f\nbar')
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000292 >>> parser = argparse.ArgumentParser(fromfile_prefix_chars='@')
293 >>> parser.add_argument('-f')
294 >>> parser.parse_args(['-f', 'foo', '@args.txt'])
295 Namespace(f='bar')
296
297Arguments read from a file must by default be one per line (but see also
298:meth:`convert_arg_line_to_args`) and are treated as if they were in the same
299place as the original file referencing argument on the command line. So in the
300example above, the expression ``['-f', 'foo', '@args.txt']`` is considered
301equivalent to the expression ``['-f', 'foo', '-f', 'bar']``.
302
303The ``fromfile_prefix_chars=`` argument defaults to ``None``, meaning that
304arguments will never be treated as file references.
305
Georg Brandle0bf91d2010-10-17 10:34:28 +0000306
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000307argument_default
308^^^^^^^^^^^^^^^^
309
310Generally, argument defaults are specified either by passing a default to
311:meth:`add_argument` or by calling the :meth:`set_defaults` methods with a
312specific set of name-value pairs. Sometimes however, it may be useful to
313specify a single parser-wide default for arguments. This can be accomplished by
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000314passing the ``argument_default=`` keyword argument to :class:`ArgumentParser`.
315For example, to globally suppress attribute creation on :meth:`parse_args`
316calls, we supply ``argument_default=SUPPRESS``::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000317
318 >>> parser = argparse.ArgumentParser(argument_default=argparse.SUPPRESS)
319 >>> parser.add_argument('--foo')
320 >>> parser.add_argument('bar', nargs='?')
321 >>> parser.parse_args(['--foo', '1', 'BAR'])
322 Namespace(bar='BAR', foo='1')
323 >>> parser.parse_args([])
324 Namespace()
325
326
327parents
328^^^^^^^
329
330Sometimes, several parsers share a common set of arguments. Rather than
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000331repeating the definitions of these arguments, a single parser with all the
332shared arguments and passed to ``parents=`` argument to :class:`ArgumentParser`
333can be used. The ``parents=`` argument takes a list of :class:`ArgumentParser`
334objects, collects all the positional and optional actions from them, and adds
335these actions to the :class:`ArgumentParser` object being constructed::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000336
337 >>> parent_parser = argparse.ArgumentParser(add_help=False)
338 >>> parent_parser.add_argument('--parent', type=int)
339
340 >>> foo_parser = argparse.ArgumentParser(parents=[parent_parser])
341 >>> foo_parser.add_argument('foo')
342 >>> foo_parser.parse_args(['--parent', '2', 'XXX'])
343 Namespace(foo='XXX', parent=2)
344
345 >>> bar_parser = argparse.ArgumentParser(parents=[parent_parser])
346 >>> bar_parser.add_argument('--bar')
347 >>> bar_parser.parse_args(['--bar', 'YYY'])
348 Namespace(bar='YYY', parent=None)
349
350Note that most parent parsers will specify ``add_help=False``. Otherwise, the
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000351:class:`ArgumentParser` will see two ``-h/--help`` options (one in the parent
352and one in the child) and raise an error.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000353
354
355formatter_class
356^^^^^^^^^^^^^^^
357
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000358:class:`ArgumentParser` objects allow the help formatting to be customized by
359specifying an alternate formatting class. Currently, there are three such
360classes: :class:`argparse.RawDescriptionHelpFormatter`,
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000361:class:`argparse.RawTextHelpFormatter` and
362:class:`argparse.ArgumentDefaultsHelpFormatter`. The first two allow more
363control over how textual descriptions are displayed, while the last
364automatically adds information about argument default values.
365
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000366By default, :class:`ArgumentParser` objects line-wrap the description_ and
367epilog_ texts in command-line help messages::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000368
369 >>> parser = argparse.ArgumentParser(
370 ... prog='PROG',
371 ... description='''this description
372 ... was indented weird
373 ... but that is okay''',
374 ... epilog='''
375 ... likewise for this epilog whose whitespace will
376 ... be cleaned up and whose words will be wrapped
377 ... across a couple lines''')
378 >>> parser.print_help()
379 usage: PROG [-h]
380
381 this description was indented weird but that is okay
382
383 optional arguments:
384 -h, --help show this help message and exit
385
386 likewise for this epilog whose whitespace will be cleaned up and whose words
387 will be wrapped across a couple lines
388
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000389Passing :class:`argparse.RawDescriptionHelpFormatter` as ``formatter_class=``
390indicates that description_ and epilog_ are already correctly formatted and
391should not be line-wrapped::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000392
393 >>> parser = argparse.ArgumentParser(
394 ... prog='PROG',
395 ... formatter_class=argparse.RawDescriptionHelpFormatter,
396 ... description=textwrap.dedent('''\
397 ... Please do not mess up this text!
398 ... --------------------------------
399 ... I have indented it
400 ... exactly the way
401 ... I want it
402 ... '''))
403 >>> parser.print_help()
404 usage: PROG [-h]
405
406 Please do not mess up this text!
407 --------------------------------
408 I have indented it
409 exactly the way
410 I want it
411
412 optional arguments:
413 -h, --help show this help message and exit
414
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000415:class:`RawTextHelpFormatter` maintains whitespace for all sorts of help text
416including argument descriptions.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000417
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000418The other formatter class available, :class:`ArgumentDefaultsHelpFormatter`,
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000419will add information about the default value of each of the arguments::
420
421 >>> parser = argparse.ArgumentParser(
422 ... prog='PROG',
423 ... formatter_class=argparse.ArgumentDefaultsHelpFormatter)
424 >>> parser.add_argument('--foo', type=int, default=42, help='FOO!')
425 >>> parser.add_argument('bar', nargs='*', default=[1, 2, 3], help='BAR!')
426 >>> parser.print_help()
427 usage: PROG [-h] [--foo FOO] [bar [bar ...]]
428
429 positional arguments:
430 bar BAR! (default: [1, 2, 3])
431
432 optional arguments:
433 -h, --help show this help message and exit
434 --foo FOO FOO! (default: 42)
435
436
437conflict_handler
438^^^^^^^^^^^^^^^^
439
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000440:class:`ArgumentParser` objects do not allow two actions with the same option
441string. By default, :class:`ArgumentParser` objects raises an exception if an
442attempt is made to create an argument with an option string that is already in
443use::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000444
445 >>> parser = argparse.ArgumentParser(prog='PROG')
446 >>> parser.add_argument('-f', '--foo', help='old foo help')
447 >>> parser.add_argument('--foo', help='new foo help')
448 Traceback (most recent call last):
449 ..
450 ArgumentError: argument --foo: conflicting option string(s): --foo
451
452Sometimes (e.g. when using parents_) it may be useful to simply override any
453older arguments with the same option string. To get this behavior, the value
454``'resolve'`` can be supplied to the ``conflict_handler=`` argument of
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000455:class:`ArgumentParser`::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000456
457 >>> parser = argparse.ArgumentParser(prog='PROG', conflict_handler='resolve')
458 >>> parser.add_argument('-f', '--foo', help='old foo help')
459 >>> parser.add_argument('--foo', help='new foo help')
460 >>> parser.print_help()
461 usage: PROG [-h] [-f FOO] [--foo FOO]
462
463 optional arguments:
464 -h, --help show this help message and exit
465 -f FOO old foo help
466 --foo FOO new foo help
467
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000468Note that :class:`ArgumentParser` objects only remove an action if all of its
469option strings are overridden. So, in the example above, the old ``-f/--foo``
470action is retained as the ``-f`` action, because only the ``--foo`` option
471string was overridden.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000472
473
474prog
475^^^^
476
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000477By default, :class:`ArgumentParser` objects uses ``sys.argv[0]`` to determine
478how to display the name of the program in help messages. This default is almost
Ezio Melottif82340d2010-05-27 22:38:16 +0000479always desirable because it will make the help messages match how the program was
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000480invoked on the command line. For example, consider a file named
481``myprogram.py`` with the following code::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000482
483 import argparse
484 parser = argparse.ArgumentParser()
485 parser.add_argument('--foo', help='foo help')
486 args = parser.parse_args()
487
488The help for this program will display ``myprogram.py`` as the program name
489(regardless of where the program was invoked from)::
490
491 $ python myprogram.py --help
492 usage: myprogram.py [-h] [--foo FOO]
493
494 optional arguments:
495 -h, --help show this help message and exit
496 --foo FOO foo help
497 $ cd ..
498 $ python subdir\myprogram.py --help
499 usage: myprogram.py [-h] [--foo FOO]
500
501 optional arguments:
502 -h, --help show this help message and exit
503 --foo FOO foo help
504
505To change this default behavior, another value can be supplied using the
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000506``prog=`` argument to :class:`ArgumentParser`::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000507
508 >>> parser = argparse.ArgumentParser(prog='myprogram')
509 >>> parser.print_help()
510 usage: myprogram [-h]
511
512 optional arguments:
513 -h, --help show this help message and exit
514
515Note that the program name, whether determined from ``sys.argv[0]`` or from the
516``prog=`` argument, is available to help messages using the ``%(prog)s`` format
517specifier.
518
519::
520
521 >>> parser = argparse.ArgumentParser(prog='myprogram')
522 >>> parser.add_argument('--foo', help='foo of the %(prog)s program')
523 >>> parser.print_help()
524 usage: myprogram [-h] [--foo FOO]
525
526 optional arguments:
527 -h, --help show this help message and exit
528 --foo FOO foo of the myprogram program
529
530
531usage
532^^^^^
533
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000534By default, :class:`ArgumentParser` calculates the usage message from the
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000535arguments it contains::
536
537 >>> parser = argparse.ArgumentParser(prog='PROG')
538 >>> parser.add_argument('--foo', nargs='?', help='foo help')
539 >>> parser.add_argument('bar', nargs='+', help='bar help')
540 >>> parser.print_help()
541 usage: PROG [-h] [--foo [FOO]] bar [bar ...]
542
543 positional arguments:
544 bar bar help
545
546 optional arguments:
547 -h, --help show this help message and exit
548 --foo [FOO] foo help
549
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000550The default message can be overridden with the ``usage=`` keyword argument::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000551
552 >>> parser = argparse.ArgumentParser(prog='PROG', usage='%(prog)s [options]')
553 >>> parser.add_argument('--foo', nargs='?', help='foo help')
554 >>> parser.add_argument('bar', nargs='+', help='bar help')
555 >>> parser.print_help()
556 usage: PROG [options]
557
558 positional arguments:
559 bar bar help
560
561 optional arguments:
562 -h, --help show this help message and exit
563 --foo [FOO] foo help
564
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000565The ``%(prog)s`` format specifier is available to fill in the program name in
566your usage messages.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000567
568
569The add_argument() method
570-------------------------
571
Georg Brandlc9007082011-01-09 09:04:08 +0000572.. method:: ArgumentParser.add_argument(name or flags..., [action], [nargs], \
573 [const], [default], [type], [choices], [required], \
574 [help], [metavar], [dest])
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000575
576 Define how a single command line argument should be parsed. Each parameter
577 has its own more detailed description below, but in short they are:
578
579 * `name or flags`_ - Either a name or a list of option strings, e.g. ``foo``
580 or ``-f, --foo``
581
582 * action_ - The basic type of action to be taken when this argument is
583 encountered at the command-line.
584
585 * nargs_ - The number of command-line arguments that should be consumed.
586
587 * const_ - A constant value required by some action_ and nargs_ selections.
588
589 * default_ - The value produced if the argument is absent from the
590 command-line.
591
592 * type_ - The type to which the command-line arg should be converted.
593
594 * choices_ - A container of the allowable values for the argument.
595
596 * required_ - Whether or not the command-line option may be omitted
597 (optionals only).
598
599 * help_ - A brief description of what the argument does.
600
601 * metavar_ - A name for the argument in usage messages.
602
603 * dest_ - The name of the attribute to be added to the object returned by
604 :meth:`parse_args`.
605
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000606The following sections describe how each of these are used.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000607
Georg Brandle0bf91d2010-10-17 10:34:28 +0000608
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000609name or flags
610^^^^^^^^^^^^^
611
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000612The :meth:`add_argument` method must know whether an optional argument, like
613``-f`` or ``--foo``, or a positional argument, like a list of filenames, is
614expected. The first arguments passed to :meth:`add_argument` must therefore be
615either a series of flags, or a simple argument name. For example, an optional
616argument could be created like::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000617
618 >>> parser.add_argument('-f', '--foo')
619
620while a positional argument could be created like::
621
622 >>> parser.add_argument('bar')
623
624When :meth:`parse_args` is called, optional arguments will be identified by the
625``-`` prefix, and the remaining arguments will be assumed to be positional::
626
627 >>> parser = argparse.ArgumentParser(prog='PROG')
628 >>> parser.add_argument('-f', '--foo')
629 >>> parser.add_argument('bar')
630 >>> parser.parse_args(['BAR'])
631 Namespace(bar='BAR', foo=None)
632 >>> parser.parse_args(['BAR', '--foo', 'FOO'])
633 Namespace(bar='BAR', foo='FOO')
634 >>> parser.parse_args(['--foo', 'FOO'])
635 usage: PROG [-h] [-f FOO] bar
636 PROG: error: too few arguments
637
Georg Brandle0bf91d2010-10-17 10:34:28 +0000638
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000639action
640^^^^^^
641
642:class:`ArgumentParser` objects associate command-line args with actions. These
643actions can do just about anything with the command-line args associated with
644them, though most actions simply add an attribute to the object returned by
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000645:meth:`parse_args`. The ``action`` keyword argument specifies how the
646command-line args should be handled. The supported actions are:
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000647
648* ``'store'`` - This just stores the argument's value. This is the default
649 action. For example::
650
651 >>> parser = argparse.ArgumentParser()
652 >>> parser.add_argument('--foo')
653 >>> parser.parse_args('--foo 1'.split())
654 Namespace(foo='1')
655
656* ``'store_const'`` - This stores the value specified by the const_ keyword
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000657 argument. (Note that the const_ keyword argument defaults to the rather
658 unhelpful ``None``.) The ``'store_const'`` action is most commonly used with
659 optional arguments that specify some sort of flag. For example::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000660
661 >>> parser = argparse.ArgumentParser()
662 >>> parser.add_argument('--foo', action='store_const', const=42)
663 >>> parser.parse_args('--foo'.split())
664 Namespace(foo=42)
665
666* ``'store_true'`` and ``'store_false'`` - These store the values ``True`` and
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000667 ``False`` respectively. These are special cases of ``'store_const'``. For
668 example::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000669
670 >>> parser = argparse.ArgumentParser()
671 >>> parser.add_argument('--foo', action='store_true')
672 >>> parser.add_argument('--bar', action='store_false')
673 >>> parser.parse_args('--foo --bar'.split())
674 Namespace(bar=False, foo=True)
675
676* ``'append'`` - This stores a list, and appends each argument value to the
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000677 list. This is useful to allow an option to be specified multiple times.
678 Example usage::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000679
680 >>> parser = argparse.ArgumentParser()
681 >>> parser.add_argument('--foo', action='append')
682 >>> parser.parse_args('--foo 1 --foo 2'.split())
683 Namespace(foo=['1', '2'])
684
685* ``'append_const'`` - This stores a list, and appends the value specified by
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000686 the const_ keyword argument to the list. (Note that the const_ keyword
687 argument defaults to ``None``.) The ``'append_const'`` action is typically
688 useful when multiple arguments need to store constants to the same list. For
689 example::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000690
691 >>> parser = argparse.ArgumentParser()
692 >>> parser.add_argument('--str', dest='types', action='append_const', const=str)
693 >>> parser.add_argument('--int', dest='types', action='append_const', const=int)
694 >>> parser.parse_args('--str --int'.split())
695 Namespace(types=[<type 'str'>, <type 'int'>])
696
697* ``'version'`` - This expects a ``version=`` keyword argument in the
698 :meth:`add_argument` call, and prints version information and exits when
699 invoked.
700
701 >>> import argparse
702 >>> parser = argparse.ArgumentParser(prog='PROG')
Steven Bethard59710962010-05-24 03:21:08 +0000703 >>> parser.add_argument('--version', action='version', version='%(prog)s 2.0')
704 >>> parser.parse_args(['--version'])
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000705 PROG 2.0
706
707You can also specify an arbitrary action by passing an object that implements
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000708the Action API. The easiest way to do this is to extend
709:class:`argparse.Action`, supplying an appropriate ``__call__`` method. The
710``__call__`` method should accept four parameters:
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000711
712* ``parser`` - The ArgumentParser object which contains this action.
713
714* ``namespace`` - The namespace object that will be returned by
715 :meth:`parse_args`. Most actions add an attribute to this object.
716
717* ``values`` - The associated command-line args, with any type-conversions
718 applied. (Type-conversions are specified with the type_ keyword argument to
719 :meth:`add_argument`.
720
721* ``option_string`` - The option string that was used to invoke this action.
722 The ``option_string`` argument is optional, and will be absent if the action
723 is associated with a positional argument.
724
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000725An example of a custom action::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000726
727 >>> class FooAction(argparse.Action):
728 ... def __call__(self, parser, namespace, values, option_string=None):
Georg Brandl571a9532010-07-26 17:00:20 +0000729 ... print('%r %r %r' % (namespace, values, option_string))
730 ... setattr(namespace, self.dest, values)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000731 ...
732 >>> parser = argparse.ArgumentParser()
733 >>> parser.add_argument('--foo', action=FooAction)
734 >>> parser.add_argument('bar', action=FooAction)
735 >>> args = parser.parse_args('1 --foo 2'.split())
736 Namespace(bar=None, foo=None) '1' None
737 Namespace(bar='1', foo=None) '2' '--foo'
738 >>> args
739 Namespace(bar='1', foo='2')
740
741
742nargs
743^^^^^
744
745ArgumentParser objects usually associate a single command-line argument with a
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000746single action to be taken. The ``nargs`` keyword argument associates a
747different number of command-line arguments with a single action.. The supported
748values are:
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000749
750* N (an integer). N args from the command-line will be gathered together into a
751 list. For example::
752
Georg Brandl682d7e02010-10-06 10:26:05 +0000753 >>> parser = argparse.ArgumentParser()
754 >>> parser.add_argument('--foo', nargs=2)
755 >>> parser.add_argument('bar', nargs=1)
756 >>> parser.parse_args('c --foo a b'.split())
757 Namespace(bar=['c'], foo=['a', 'b'])
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000758
Georg Brandl682d7e02010-10-06 10:26:05 +0000759 Note that ``nargs=1`` produces a list of one item. This is different from
760 the default, in which the item is produced by itself.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000761
762* ``'?'``. One arg will be consumed from the command-line if possible, and
763 produced as a single item. If no command-line arg is present, the value from
764 default_ will be produced. Note that for optional arguments, there is an
765 additional case - the option string is present but not followed by a
766 command-line arg. In this case the value from const_ will be produced. Some
767 examples to illustrate this::
768
769 >>> parser = argparse.ArgumentParser()
770 >>> parser.add_argument('--foo', nargs='?', const='c', default='d')
771 >>> parser.add_argument('bar', nargs='?', default='d')
772 >>> parser.parse_args('XX --foo YY'.split())
773 Namespace(bar='XX', foo='YY')
774 >>> parser.parse_args('XX --foo'.split())
775 Namespace(bar='XX', foo='c')
776 >>> parser.parse_args(''.split())
777 Namespace(bar='d', foo='d')
778
779 One of the more common uses of ``nargs='?'`` is to allow optional input and
780 output files::
781
782 >>> parser = argparse.ArgumentParser()
Georg Brandle0bf91d2010-10-17 10:34:28 +0000783 >>> parser.add_argument('infile', nargs='?', type=argparse.FileType('r'),
784 ... default=sys.stdin)
785 >>> parser.add_argument('outfile', nargs='?', type=argparse.FileType('w'),
786 ... default=sys.stdout)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000787 >>> parser.parse_args(['input.txt', 'output.txt'])
Georg Brandl04536b02011-01-09 09:31:01 +0000788 Namespace(infile=<_io.TextIOWrapper name='input.txt' encoding='UTF-8'>,
789 outfile=<_io.TextIOWrapper name='output.txt' encoding='UTF-8'>)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000790 >>> parser.parse_args([])
Georg Brandl04536b02011-01-09 09:31:01 +0000791 Namespace(infile=<_io.TextIOWrapper name='<stdin>' encoding='UTF-8'>,
792 outfile=<_io.TextIOWrapper name='<stdout>' encoding='UTF-8'>)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000793
794* ``'*'``. All command-line args present are gathered into a list. Note that
795 it generally doesn't make much sense to have more than one positional argument
796 with ``nargs='*'``, but multiple optional arguments with ``nargs='*'`` is
797 possible. For example::
798
799 >>> parser = argparse.ArgumentParser()
800 >>> parser.add_argument('--foo', nargs='*')
801 >>> parser.add_argument('--bar', nargs='*')
802 >>> parser.add_argument('baz', nargs='*')
803 >>> parser.parse_args('a b --foo x y --bar 1 2'.split())
804 Namespace(bar=['1', '2'], baz=['a', 'b'], foo=['x', 'y'])
805
806* ``'+'``. Just like ``'*'``, all command-line args present are gathered into a
807 list. Additionally, an error message will be generated if there wasn't at
808 least one command-line arg present. For example::
809
810 >>> parser = argparse.ArgumentParser(prog='PROG')
811 >>> parser.add_argument('foo', nargs='+')
812 >>> parser.parse_args('a b'.split())
813 Namespace(foo=['a', 'b'])
814 >>> parser.parse_args(''.split())
815 usage: PROG [-h] foo [foo ...]
816 PROG: error: too few arguments
817
818If the ``nargs`` keyword argument is not provided, the number of args consumed
819is determined by the action_. Generally this means a single command-line arg
820will be consumed and a single item (not a list) will be produced.
821
822
823const
824^^^^^
825
826The ``const`` argument of :meth:`add_argument` is used to hold constant values
827that are not read from the command line but are required for the various
828ArgumentParser actions. The two most common uses of it are:
829
830* When :meth:`add_argument` is called with ``action='store_const'`` or
831 ``action='append_const'``. These actions add the ``const`` value to one of
832 the attributes of the object returned by :meth:`parse_args`. See the action_
833 description for examples.
834
835* When :meth:`add_argument` is called with option strings (like ``-f`` or
836 ``--foo``) and ``nargs='?'``. This creates an optional argument that can be
837 followed by zero or one command-line args. When parsing the command-line, if
838 the option string is encountered with no command-line arg following it, the
839 value of ``const`` will be assumed instead. See the nargs_ description for
840 examples.
841
842The ``const`` keyword argument defaults to ``None``.
843
844
845default
846^^^^^^^
847
848All optional arguments and some positional arguments may be omitted at the
849command-line. The ``default`` keyword argument of :meth:`add_argument`, whose
850value defaults to ``None``, specifies what value should be used if the
851command-line arg is not present. For optional arguments, the ``default`` value
852is used when the option string was not present at the command line::
853
854 >>> parser = argparse.ArgumentParser()
855 >>> parser.add_argument('--foo', default=42)
856 >>> parser.parse_args('--foo 2'.split())
857 Namespace(foo='2')
858 >>> parser.parse_args(''.split())
859 Namespace(foo=42)
860
861For positional arguments with nargs_ ``='?'`` or ``'*'``, the ``default`` value
862is used when no command-line arg was present::
863
864 >>> parser = argparse.ArgumentParser()
865 >>> parser.add_argument('foo', nargs='?', default=42)
866 >>> parser.parse_args('a'.split())
867 Namespace(foo='a')
868 >>> parser.parse_args(''.split())
869 Namespace(foo=42)
870
871
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000872Providing ``default=argparse.SUPPRESS`` causes no attribute to be added if the
873command-line argument was not present.::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000874
875 >>> parser = argparse.ArgumentParser()
876 >>> parser.add_argument('--foo', default=argparse.SUPPRESS)
877 >>> parser.parse_args([])
878 Namespace()
879 >>> parser.parse_args(['--foo', '1'])
880 Namespace(foo='1')
881
882
883type
884^^^^
885
886By default, ArgumentParser objects read command-line args in as simple strings.
887However, quite often the command-line string should instead be interpreted as
Georg Brandl04536b02011-01-09 09:31:01 +0000888another type, like a :class:`float` or :class:`int`. The ``type`` keyword
889argument of :meth:`add_argument` allows any necessary type-checking and
890type-conversions to be performed. Common built-in types and functions can be
891used directly as the value of the ``type`` argument::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000892
893 >>> parser = argparse.ArgumentParser()
894 >>> parser.add_argument('foo', type=int)
Georg Brandl04536b02011-01-09 09:31:01 +0000895 >>> parser.add_argument('bar', type=open)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000896 >>> parser.parse_args('2 temp.txt'.split())
Georg Brandl04536b02011-01-09 09:31:01 +0000897 Namespace(bar=<_io.TextIOWrapper name='temp.txt' encoding='UTF-8'>, foo=2)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000898
899To ease the use of various types of files, the argparse module provides the
900factory FileType which takes the ``mode=`` and ``bufsize=`` arguments of the
Georg Brandl04536b02011-01-09 09:31:01 +0000901:func:`open` function. For example, ``FileType('w')`` can be used to create a
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000902writable file::
903
904 >>> parser = argparse.ArgumentParser()
905 >>> parser.add_argument('bar', type=argparse.FileType('w'))
906 >>> parser.parse_args(['out.txt'])
Georg Brandl04536b02011-01-09 09:31:01 +0000907 Namespace(bar=<_io.TextIOWrapper name='out.txt' encoding='UTF-8'>)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000908
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000909``type=`` can take any callable that takes a single string argument and returns
910the type-converted value::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000911
912 >>> def perfect_square(string):
913 ... value = int(string)
914 ... sqrt = math.sqrt(value)
915 ... if sqrt != int(sqrt):
916 ... msg = "%r is not a perfect square" % string
917 ... raise argparse.ArgumentTypeError(msg)
918 ... return value
919 ...
920 >>> parser = argparse.ArgumentParser(prog='PROG')
921 >>> parser.add_argument('foo', type=perfect_square)
922 >>> parser.parse_args('9'.split())
923 Namespace(foo=9)
924 >>> parser.parse_args('7'.split())
925 usage: PROG [-h] foo
926 PROG: error: argument foo: '7' is not a perfect square
927
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000928The choices_ keyword argument may be more convenient for type checkers that
929simply check against a range of values::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000930
931 >>> parser = argparse.ArgumentParser(prog='PROG')
Fred Drake44623062011-03-03 05:27:17 +0000932 >>> parser.add_argument('foo', type=int, choices=range(5, 10))
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000933 >>> parser.parse_args('7'.split())
934 Namespace(foo=7)
935 >>> parser.parse_args('11'.split())
936 usage: PROG [-h] {5,6,7,8,9}
937 PROG: error: argument foo: invalid choice: 11 (choose from 5, 6, 7, 8, 9)
938
939See the choices_ section for more details.
940
941
942choices
943^^^^^^^
944
945Some command-line args should be selected from a restricted set of values.
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000946These can be handled by passing a container object as the ``choices`` keyword
947argument to :meth:`add_argument`. When the command-line is parsed, arg values
948will be checked, and an error message will be displayed if the arg was not one
949of the acceptable values::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000950
951 >>> parser = argparse.ArgumentParser(prog='PROG')
952 >>> parser.add_argument('foo', choices='abc')
953 >>> parser.parse_args('c'.split())
954 Namespace(foo='c')
955 >>> parser.parse_args('X'.split())
956 usage: PROG [-h] {a,b,c}
957 PROG: error: argument foo: invalid choice: 'X' (choose from 'a', 'b', 'c')
958
959Note that inclusion in the ``choices`` container is checked after any type_
960conversions have been performed, so the type of the objects in the ``choices``
961container should match the type_ specified::
962
963 >>> parser = argparse.ArgumentParser(prog='PROG')
964 >>> parser.add_argument('foo', type=complex, choices=[1, 1j])
965 >>> parser.parse_args('1j'.split())
966 Namespace(foo=1j)
967 >>> parser.parse_args('-- -4'.split())
968 usage: PROG [-h] {1,1j}
969 PROG: error: argument foo: invalid choice: (-4+0j) (choose from 1, 1j)
970
971Any object that supports the ``in`` operator can be passed as the ``choices``
972value, so :class:`dict` objects, :class:`set` objects, custom containers,
973etc. are all supported.
974
975
976required
977^^^^^^^^
978
979In general, the argparse module assumes that flags like ``-f`` and ``--bar``
980indicate *optional* arguments, which can always be omitted at the command-line.
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000981To make an option *required*, ``True`` can be specified for the ``required=``
982keyword argument to :meth:`add_argument`::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000983
984 >>> parser = argparse.ArgumentParser()
985 >>> parser.add_argument('--foo', required=True)
986 >>> parser.parse_args(['--foo', 'BAR'])
987 Namespace(foo='BAR')
988 >>> parser.parse_args([])
989 usage: argparse.py [-h] [--foo FOO]
990 argparse.py: error: option --foo is required
991
992As the example shows, if an option is marked as ``required``, :meth:`parse_args`
993will report an error if that option is not present at the command line.
994
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000995.. note::
996
997 Required options are generally considered bad form because users expect
998 *options* to be *optional*, and thus they should be avoided when possible.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000999
1000
1001help
1002^^^^
1003
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001004The ``help`` value is a string containing a brief description of the argument.
1005When a user requests help (usually by using ``-h`` or ``--help`` at the
1006command-line), these ``help`` descriptions will be displayed with each
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001007argument::
1008
1009 >>> parser = argparse.ArgumentParser(prog='frobble')
1010 >>> parser.add_argument('--foo', action='store_true',
1011 ... help='foo the bars before frobbling')
1012 >>> parser.add_argument('bar', nargs='+',
1013 ... help='one of the bars to be frobbled')
1014 >>> parser.parse_args('-h'.split())
1015 usage: frobble [-h] [--foo] bar [bar ...]
1016
1017 positional arguments:
1018 bar one of the bars to be frobbled
1019
1020 optional arguments:
1021 -h, --help show this help message and exit
1022 --foo foo the bars before frobbling
1023
1024The ``help`` strings can include various format specifiers to avoid repetition
1025of things like the program name or the argument default_. The available
1026specifiers include the program name, ``%(prog)s`` and most keyword arguments to
1027:meth:`add_argument`, e.g. ``%(default)s``, ``%(type)s``, etc.::
1028
1029 >>> parser = argparse.ArgumentParser(prog='frobble')
1030 >>> parser.add_argument('bar', nargs='?', type=int, default=42,
1031 ... help='the bar to %(prog)s (default: %(default)s)')
1032 >>> parser.print_help()
1033 usage: frobble [-h] [bar]
1034
1035 positional arguments:
1036 bar the bar to frobble (default: 42)
1037
1038 optional arguments:
1039 -h, --help show this help message and exit
1040
1041
1042metavar
1043^^^^^^^
1044
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001045When :class:`ArgumentParser` generates help messages, it need some way to refer
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001046to each expected argument. By default, ArgumentParser objects use the dest_
1047value as the "name" of each object. By default, for positional argument
1048actions, the dest_ value is used directly, and for optional argument actions,
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001049the dest_ value is uppercased. So, a single positional argument with
1050``dest='bar'`` will that argument will be referred to as ``bar``. A single
1051optional argument ``--foo`` that should be followed by a single command-line arg
1052will be referred to as ``FOO``. An example::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001053
1054 >>> parser = argparse.ArgumentParser()
1055 >>> parser.add_argument('--foo')
1056 >>> parser.add_argument('bar')
1057 >>> parser.parse_args('X --foo Y'.split())
1058 Namespace(bar='X', foo='Y')
1059 >>> parser.print_help()
1060 usage: [-h] [--foo FOO] bar
1061
1062 positional arguments:
1063 bar
1064
1065 optional arguments:
1066 -h, --help show this help message and exit
1067 --foo FOO
1068
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001069An alternative name can be specified with ``metavar``::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001070
1071 >>> parser = argparse.ArgumentParser()
1072 >>> parser.add_argument('--foo', metavar='YYY')
1073 >>> parser.add_argument('bar', metavar='XXX')
1074 >>> parser.parse_args('X --foo Y'.split())
1075 Namespace(bar='X', foo='Y')
1076 >>> parser.print_help()
1077 usage: [-h] [--foo YYY] XXX
1078
1079 positional arguments:
1080 XXX
1081
1082 optional arguments:
1083 -h, --help show this help message and exit
1084 --foo YYY
1085
1086Note that ``metavar`` only changes the *displayed* name - the name of the
1087attribute on the :meth:`parse_args` object is still determined by the dest_
1088value.
1089
1090Different values of ``nargs`` may cause the metavar to be used multiple times.
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001091Providing a tuple to ``metavar`` specifies a different display for each of the
1092arguments::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001093
1094 >>> parser = argparse.ArgumentParser(prog='PROG')
1095 >>> parser.add_argument('-x', nargs=2)
1096 >>> parser.add_argument('--foo', nargs=2, metavar=('bar', 'baz'))
1097 >>> parser.print_help()
1098 usage: PROG [-h] [-x X X] [--foo bar baz]
1099
1100 optional arguments:
1101 -h, --help show this help message and exit
1102 -x X X
1103 --foo bar baz
1104
1105
1106dest
1107^^^^
1108
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001109Most :class:`ArgumentParser` actions add some value as an attribute of the
1110object returned by :meth:`parse_args`. The name of this attribute is determined
1111by the ``dest`` keyword argument of :meth:`add_argument`. For positional
1112argument actions, ``dest`` is normally supplied as the first argument to
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001113:meth:`add_argument`::
1114
1115 >>> parser = argparse.ArgumentParser()
1116 >>> parser.add_argument('bar')
1117 >>> parser.parse_args('XXX'.split())
1118 Namespace(bar='XXX')
1119
1120For optional argument actions, the value of ``dest`` is normally inferred from
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001121the option strings. :class:`ArgumentParser` generates the value of ``dest`` by
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001122taking the first long option string and stripping away the initial ``'--'``
1123string. If no long option strings were supplied, ``dest`` will be derived from
1124the first short option string by stripping the initial ``'-'`` character. Any
1125internal ``'-'`` characters will be converted to ``'_'`` characters to make sure
1126the string is a valid attribute name. The examples below illustrate this
1127behavior::
1128
1129 >>> parser = argparse.ArgumentParser()
1130 >>> parser.add_argument('-f', '--foo-bar', '--foo')
1131 >>> parser.add_argument('-x', '-y')
1132 >>> parser.parse_args('-f 1 -x 2'.split())
1133 Namespace(foo_bar='1', x='2')
1134 >>> parser.parse_args('--foo 1 -y 2'.split())
1135 Namespace(foo_bar='1', x='2')
1136
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001137``dest`` allows a custom attribute name to be provided::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001138
1139 >>> parser = argparse.ArgumentParser()
1140 >>> parser.add_argument('--foo', dest='bar')
1141 >>> parser.parse_args('--foo XXX'.split())
1142 Namespace(bar='XXX')
1143
1144
1145The parse_args() method
1146-----------------------
1147
Georg Brandle0bf91d2010-10-17 10:34:28 +00001148.. method:: ArgumentParser.parse_args(args=None, namespace=None)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001149
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001150 Convert argument strings to objects and assign them as attributes of the
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001151 namespace. Return the populated namespace.
1152
1153 Previous calls to :meth:`add_argument` determine exactly what objects are
1154 created and how they are assigned. See the documentation for
1155 :meth:`add_argument` for details.
1156
1157 By default, the arg strings are taken from :data:`sys.argv`, and a new empty
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001158 :class:`Namespace` object is created for the attributes.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001159
Georg Brandle0bf91d2010-10-17 10:34:28 +00001160
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001161Option value syntax
1162^^^^^^^^^^^^^^^^^^^
1163
1164The :meth:`parse_args` method supports several ways of specifying the value of
1165an option (if it takes one). In the simplest case, the option and its value are
1166passed as two separate arguments::
1167
1168 >>> parser = argparse.ArgumentParser(prog='PROG')
1169 >>> parser.add_argument('-x')
1170 >>> parser.add_argument('--foo')
1171 >>> parser.parse_args('-x X'.split())
1172 Namespace(foo=None, x='X')
1173 >>> parser.parse_args('--foo FOO'.split())
1174 Namespace(foo='FOO', x=None)
1175
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001176For long options (options with names longer than a single character), the option
1177and value can also be passed as a single command line argument, using ``=`` to
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001178separate them::
1179
1180 >>> parser.parse_args('--foo=FOO'.split())
1181 Namespace(foo='FOO', x=None)
1182
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001183For short options (options only one character long), the option and its value
1184can be concatenated::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001185
1186 >>> parser.parse_args('-xX'.split())
1187 Namespace(foo=None, x='X')
1188
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001189Several short options can be joined together, using only a single ``-`` prefix,
1190as long as only the last option (or none of them) requires a value::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001191
1192 >>> parser = argparse.ArgumentParser(prog='PROG')
1193 >>> parser.add_argument('-x', action='store_true')
1194 >>> parser.add_argument('-y', action='store_true')
1195 >>> parser.add_argument('-z')
1196 >>> parser.parse_args('-xyzZ'.split())
1197 Namespace(x=True, y=True, z='Z')
1198
1199
1200Invalid arguments
1201^^^^^^^^^^^^^^^^^
1202
1203While parsing the command-line, ``parse_args`` checks for a variety of errors,
1204including ambiguous options, invalid types, invalid options, wrong number of
1205positional arguments, etc. When it encounters such an error, it exits and
1206prints the error along with a usage message::
1207
1208 >>> parser = argparse.ArgumentParser(prog='PROG')
1209 >>> parser.add_argument('--foo', type=int)
1210 >>> parser.add_argument('bar', nargs='?')
1211
1212 >>> # invalid type
1213 >>> parser.parse_args(['--foo', 'spam'])
1214 usage: PROG [-h] [--foo FOO] [bar]
1215 PROG: error: argument --foo: invalid int value: 'spam'
1216
1217 >>> # invalid option
1218 >>> parser.parse_args(['--bar'])
1219 usage: PROG [-h] [--foo FOO] [bar]
1220 PROG: error: no such option: --bar
1221
1222 >>> # wrong number of arguments
1223 >>> parser.parse_args(['spam', 'badger'])
1224 usage: PROG [-h] [--foo FOO] [bar]
1225 PROG: error: extra arguments found: badger
1226
1227
1228Arguments containing ``"-"``
1229^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1230
1231The ``parse_args`` method attempts to give errors whenever the user has clearly
1232made a mistake, but some situations are inherently ambiguous. For example, the
1233command-line arg ``'-1'`` could either be an attempt to specify an option or an
1234attempt to provide a positional argument. The ``parse_args`` method is cautious
1235here: positional arguments may only begin with ``'-'`` if they look like
1236negative numbers and there are no options in the parser that look like negative
1237numbers::
1238
1239 >>> parser = argparse.ArgumentParser(prog='PROG')
1240 >>> parser.add_argument('-x')
1241 >>> parser.add_argument('foo', nargs='?')
1242
1243 >>> # no negative number options, so -1 is a positional argument
1244 >>> parser.parse_args(['-x', '-1'])
1245 Namespace(foo=None, x='-1')
1246
1247 >>> # no negative number options, so -1 and -5 are positional arguments
1248 >>> parser.parse_args(['-x', '-1', '-5'])
1249 Namespace(foo='-5', x='-1')
1250
1251 >>> parser = argparse.ArgumentParser(prog='PROG')
1252 >>> parser.add_argument('-1', dest='one')
1253 >>> parser.add_argument('foo', nargs='?')
1254
1255 >>> # negative number options present, so -1 is an option
1256 >>> parser.parse_args(['-1', 'X'])
1257 Namespace(foo=None, one='X')
1258
1259 >>> # negative number options present, so -2 is an option
1260 >>> parser.parse_args(['-2'])
1261 usage: PROG [-h] [-1 ONE] [foo]
1262 PROG: error: no such option: -2
1263
1264 >>> # negative number options present, so both -1s are options
1265 >>> parser.parse_args(['-1', '-1'])
1266 usage: PROG [-h] [-1 ONE] [foo]
1267 PROG: error: argument -1: expected one argument
1268
1269If you have positional arguments that must begin with ``'-'`` and don't look
1270like negative numbers, you can insert the pseudo-argument ``'--'`` which tells
1271``parse_args`` that everything after that is a positional argument::
1272
1273 >>> parser.parse_args(['--', '-f'])
1274 Namespace(foo='-f', one=None)
1275
1276
1277Argument abbreviations
1278^^^^^^^^^^^^^^^^^^^^^^
1279
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001280The :meth:`parse_args` method allows long options to be abbreviated if the
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001281abbreviation is unambiguous::
1282
1283 >>> parser = argparse.ArgumentParser(prog='PROG')
1284 >>> parser.add_argument('-bacon')
1285 >>> parser.add_argument('-badger')
1286 >>> parser.parse_args('-bac MMM'.split())
1287 Namespace(bacon='MMM', badger=None)
1288 >>> parser.parse_args('-bad WOOD'.split())
1289 Namespace(bacon=None, badger='WOOD')
1290 >>> parser.parse_args('-ba BA'.split())
1291 usage: PROG [-h] [-bacon BACON] [-badger BADGER]
1292 PROG: error: ambiguous option: -ba could match -badger, -bacon
1293
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001294An error is produced for arguments that could produce more than one options.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001295
1296
1297Beyond ``sys.argv``
1298^^^^^^^^^^^^^^^^^^^
1299
1300Sometimes it may be useful to have an ArgumentParser parse args other than those
1301of :data:`sys.argv`. This can be accomplished by passing a list of strings to
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001302``parse_args``. This is useful for testing at the interactive prompt::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001303
1304 >>> parser = argparse.ArgumentParser()
1305 >>> parser.add_argument(
Fred Drake44623062011-03-03 05:27:17 +00001306 ... 'integers', metavar='int', type=int, choices=range(10),
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001307 ... nargs='+', help='an integer in the range 0..9')
1308 >>> parser.add_argument(
1309 ... '--sum', dest='accumulate', action='store_const', const=sum,
1310 ... default=max, help='sum the integers (default: find the max)')
1311 >>> parser.parse_args(['1', '2', '3', '4'])
1312 Namespace(accumulate=<built-in function max>, integers=[1, 2, 3, 4])
1313 >>> parser.parse_args('1 2 3 4 --sum'.split())
1314 Namespace(accumulate=<built-in function sum>, integers=[1, 2, 3, 4])
1315
1316
1317Custom namespaces
1318^^^^^^^^^^^^^^^^^
1319
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001320It may also be useful to have an :class:`ArgumentParser` assign attributes to an
1321already existing object, rather than the newly-created :class:`Namespace` object
1322that is normally used. This can be achieved by specifying the ``namespace=``
1323keyword argument::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001324
Éric Araujo28053fb2010-11-22 03:09:19 +00001325 >>> class C:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001326 ... pass
1327 ...
1328 >>> c = C()
1329 >>> parser = argparse.ArgumentParser()
1330 >>> parser.add_argument('--foo')
1331 >>> parser.parse_args(args=['--foo', 'BAR'], namespace=c)
1332 >>> c.foo
1333 'BAR'
1334
1335
1336Other utilities
1337---------------
1338
1339Sub-commands
1340^^^^^^^^^^^^
1341
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001342.. method:: ArgumentParser.add_subparsers()
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001343
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001344 Many programs split up their functionality into a number of sub-commands,
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001345 for example, the ``svn`` program can invoke sub-commands like ``svn
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001346 checkout``, ``svn update``, and ``svn commit``. Splitting up functionality
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001347 this way can be a particularly good idea when a program performs several
1348 different functions which require different kinds of command-line arguments.
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001349 :class:`ArgumentParser` supports the creation of such sub-commands with the
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001350 :meth:`add_subparsers` method. The :meth:`add_subparsers` method is normally
1351 called with no arguments and returns an special action object. This object
1352 has a single method, ``add_parser``, which takes a command name and any
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001353 :class:`ArgumentParser` constructor arguments, and returns an
1354 :class:`ArgumentParser` object that can be modified as usual.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001355
1356 Some example usage::
1357
1358 >>> # create the top-level parser
1359 >>> parser = argparse.ArgumentParser(prog='PROG')
1360 >>> parser.add_argument('--foo', action='store_true', help='foo help')
1361 >>> subparsers = parser.add_subparsers(help='sub-command help')
1362 >>>
1363 >>> # create the parser for the "a" command
1364 >>> parser_a = subparsers.add_parser('a', help='a help')
1365 >>> parser_a.add_argument('bar', type=int, help='bar help')
1366 >>>
1367 >>> # create the parser for the "b" command
1368 >>> parser_b = subparsers.add_parser('b', help='b help')
1369 >>> parser_b.add_argument('--baz', choices='XYZ', help='baz help')
1370 >>>
1371 >>> # parse some arg lists
1372 >>> parser.parse_args(['a', '12'])
1373 Namespace(bar=12, foo=False)
1374 >>> parser.parse_args(['--foo', 'b', '--baz', 'Z'])
1375 Namespace(baz='Z', foo=True)
1376
1377 Note that the object returned by :meth:`parse_args` will only contain
1378 attributes for the main parser and the subparser that was selected by the
1379 command line (and not any other subparsers). So in the example above, when
1380 the ``"a"`` command is specified, only the ``foo`` and ``bar`` attributes are
1381 present, and when the ``"b"`` command is specified, only the ``foo`` and
1382 ``baz`` attributes are present.
1383
1384 Similarly, when a help message is requested from a subparser, only the help
1385 for that particular parser will be printed. The help message will not
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001386 include parent parser or sibling parser messages. (A help message for each
1387 subparser command, however, can be given by supplying the ``help=`` argument
1388 to ``add_parser`` as above.)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001389
1390 ::
1391
1392 >>> parser.parse_args(['--help'])
1393 usage: PROG [-h] [--foo] {a,b} ...
1394
1395 positional arguments:
1396 {a,b} sub-command help
1397 a a help
1398 b b help
1399
1400 optional arguments:
1401 -h, --help show this help message and exit
1402 --foo foo help
1403
1404 >>> parser.parse_args(['a', '--help'])
1405 usage: PROG a [-h] bar
1406
1407 positional arguments:
1408 bar bar help
1409
1410 optional arguments:
1411 -h, --help show this help message and exit
1412
1413 >>> parser.parse_args(['b', '--help'])
1414 usage: PROG b [-h] [--baz {X,Y,Z}]
1415
1416 optional arguments:
1417 -h, --help show this help message and exit
1418 --baz {X,Y,Z} baz help
1419
1420 The :meth:`add_subparsers` method also supports ``title`` and ``description``
1421 keyword arguments. When either is present, the subparser's commands will
1422 appear in their own group in the help output. For example::
1423
1424 >>> parser = argparse.ArgumentParser()
1425 >>> subparsers = parser.add_subparsers(title='subcommands',
1426 ... description='valid subcommands',
1427 ... help='additional help')
1428 >>> subparsers.add_parser('foo')
1429 >>> subparsers.add_parser('bar')
1430 >>> parser.parse_args(['-h'])
1431 usage: [-h] {foo,bar} ...
1432
1433 optional arguments:
1434 -h, --help show this help message and exit
1435
1436 subcommands:
1437 valid subcommands
1438
1439 {foo,bar} additional help
1440
Steven Bethardfd311a72010-12-18 11:19:23 +00001441 Furthermore, ``add_parser`` supports an additional ``aliases`` argument,
1442 which allows multiple strings to refer to the same subparser. This example,
1443 like ``svn``, aliases ``co`` as a shorthand for ``checkout``::
1444
1445 >>> parser = argparse.ArgumentParser()
1446 >>> subparsers = parser.add_subparsers()
1447 >>> checkout = subparsers.add_parser('checkout', aliases=['co'])
1448 >>> checkout.add_argument('foo')
1449 >>> parser.parse_args(['co', 'bar'])
1450 Namespace(foo='bar')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001451
1452 One particularly effective way of handling sub-commands is to combine the use
1453 of the :meth:`add_subparsers` method with calls to :meth:`set_defaults` so
1454 that each subparser knows which Python function it should execute. For
1455 example::
1456
1457 >>> # sub-command functions
1458 >>> def foo(args):
Benjamin Petersonb2deb112010-03-03 02:09:18 +00001459 ... print(args.x * args.y)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001460 ...
1461 >>> def bar(args):
Benjamin Petersonb2deb112010-03-03 02:09:18 +00001462 ... print('((%s))' % args.z)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001463 ...
1464 >>> # create the top-level parser
1465 >>> parser = argparse.ArgumentParser()
1466 >>> subparsers = parser.add_subparsers()
1467 >>>
1468 >>> # create the parser for the "foo" command
1469 >>> parser_foo = subparsers.add_parser('foo')
1470 >>> parser_foo.add_argument('-x', type=int, default=1)
1471 >>> parser_foo.add_argument('y', type=float)
1472 >>> parser_foo.set_defaults(func=foo)
1473 >>>
1474 >>> # create the parser for the "bar" command
1475 >>> parser_bar = subparsers.add_parser('bar')
1476 >>> parser_bar.add_argument('z')
1477 >>> parser_bar.set_defaults(func=bar)
1478 >>>
1479 >>> # parse the args and call whatever function was selected
1480 >>> args = parser.parse_args('foo 1 -x 2'.split())
1481 >>> args.func(args)
1482 2.0
1483 >>>
1484 >>> # parse the args and call whatever function was selected
1485 >>> args = parser.parse_args('bar XYZYX'.split())
1486 >>> args.func(args)
1487 ((XYZYX))
1488
Steven Bethardfd311a72010-12-18 11:19:23 +00001489 This way, you can let :meth:`parse_args` do the job of calling the
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001490 appropriate function after argument parsing is complete. Associating
1491 functions with actions like this is typically the easiest way to handle the
1492 different actions for each of your subparsers. However, if it is necessary
1493 to check the name of the subparser that was invoked, the ``dest`` keyword
1494 argument to the :meth:`add_subparsers` call will work::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001495
1496 >>> parser = argparse.ArgumentParser()
1497 >>> subparsers = parser.add_subparsers(dest='subparser_name')
1498 >>> subparser1 = subparsers.add_parser('1')
1499 >>> subparser1.add_argument('-x')
1500 >>> subparser2 = subparsers.add_parser('2')
1501 >>> subparser2.add_argument('y')
1502 >>> parser.parse_args(['2', 'frobble'])
1503 Namespace(subparser_name='2', y='frobble')
1504
1505
1506FileType objects
1507^^^^^^^^^^^^^^^^
1508
1509.. class:: FileType(mode='r', bufsize=None)
1510
1511 The :class:`FileType` factory creates objects that can be passed to the type
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001512 argument of :meth:`ArgumentParser.add_argument`. Arguments that have
1513 :class:`FileType` objects as their type will open command-line args as files
1514 with the requested modes and buffer sizes:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001515
1516 >>> parser = argparse.ArgumentParser()
1517 >>> parser.add_argument('--output', type=argparse.FileType('wb', 0))
1518 >>> parser.parse_args(['--output', 'out'])
Georg Brandl04536b02011-01-09 09:31:01 +00001519 Namespace(output=<_io.BufferedWriter name='out'>)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001520
1521 FileType objects understand the pseudo-argument ``'-'`` and automatically
1522 convert this into ``sys.stdin`` for readable :class:`FileType` objects and
1523 ``sys.stdout`` for writable :class:`FileType` objects:
1524
1525 >>> parser = argparse.ArgumentParser()
1526 >>> parser.add_argument('infile', type=argparse.FileType('r'))
1527 >>> parser.parse_args(['-'])
Georg Brandl04536b02011-01-09 09:31:01 +00001528 Namespace(infile=<_io.TextIOWrapper name='<stdin>' encoding='UTF-8'>)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001529
1530
1531Argument groups
1532^^^^^^^^^^^^^^^
1533
Georg Brandle0bf91d2010-10-17 10:34:28 +00001534.. method:: ArgumentParser.add_argument_group(title=None, description=None)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001535
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001536 By default, :class:`ArgumentParser` groups command-line arguments into
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001537 "positional arguments" and "optional arguments" when displaying help
1538 messages. When there is a better conceptual grouping of arguments than this
1539 default one, appropriate groups can be created using the
1540 :meth:`add_argument_group` method::
1541
1542 >>> parser = argparse.ArgumentParser(prog='PROG', add_help=False)
1543 >>> group = parser.add_argument_group('group')
1544 >>> group.add_argument('--foo', help='foo help')
1545 >>> group.add_argument('bar', help='bar help')
1546 >>> parser.print_help()
1547 usage: PROG [--foo FOO] bar
1548
1549 group:
1550 bar bar help
1551 --foo FOO foo help
1552
1553 The :meth:`add_argument_group` method returns an argument group object which
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001554 has an :meth:`~ArgumentParser.add_argument` method just like a regular
1555 :class:`ArgumentParser`. When an argument is added to the group, the parser
1556 treats it just like a normal argument, but displays the argument in a
1557 separate group for help messages. The :meth:`add_argument_group` method
Georg Brandle0bf91d2010-10-17 10:34:28 +00001558 accepts *title* and *description* arguments which can be used to
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001559 customize this display::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001560
1561 >>> parser = argparse.ArgumentParser(prog='PROG', add_help=False)
1562 >>> group1 = parser.add_argument_group('group1', 'group1 description')
1563 >>> group1.add_argument('foo', help='foo help')
1564 >>> group2 = parser.add_argument_group('group2', 'group2 description')
1565 >>> group2.add_argument('--bar', help='bar help')
1566 >>> parser.print_help()
1567 usage: PROG [--bar BAR] foo
1568
1569 group1:
1570 group1 description
1571
1572 foo foo help
1573
1574 group2:
1575 group2 description
1576
1577 --bar BAR bar help
1578
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001579 Note that any arguments not your user defined groups will end up back in the
1580 usual "positional arguments" and "optional arguments" sections.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001581
1582
1583Mutual exclusion
1584^^^^^^^^^^^^^^^^
1585
Georg Brandle0bf91d2010-10-17 10:34:28 +00001586.. method:: add_mutually_exclusive_group(required=False)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001587
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001588 Create a mutually exclusive group. argparse will make sure that only one of
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001589 the arguments in the mutually exclusive group was present on the command
1590 line::
1591
1592 >>> parser = argparse.ArgumentParser(prog='PROG')
1593 >>> group = parser.add_mutually_exclusive_group()
1594 >>> group.add_argument('--foo', action='store_true')
1595 >>> group.add_argument('--bar', action='store_false')
1596 >>> parser.parse_args(['--foo'])
1597 Namespace(bar=True, foo=True)
1598 >>> parser.parse_args(['--bar'])
1599 Namespace(bar=False, foo=False)
1600 >>> parser.parse_args(['--foo', '--bar'])
1601 usage: PROG [-h] [--foo | --bar]
1602 PROG: error: argument --bar: not allowed with argument --foo
1603
Georg Brandle0bf91d2010-10-17 10:34:28 +00001604 The :meth:`add_mutually_exclusive_group` method also accepts a *required*
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001605 argument, to indicate that at least one of the mutually exclusive arguments
1606 is required::
1607
1608 >>> parser = argparse.ArgumentParser(prog='PROG')
1609 >>> group = parser.add_mutually_exclusive_group(required=True)
1610 >>> group.add_argument('--foo', action='store_true')
1611 >>> group.add_argument('--bar', action='store_false')
1612 >>> parser.parse_args([])
1613 usage: PROG [-h] (--foo | --bar)
1614 PROG: error: one of the arguments --foo --bar is required
1615
1616 Note that currently mutually exclusive argument groups do not support the
Georg Brandle0bf91d2010-10-17 10:34:28 +00001617 *title* and *description* arguments of :meth:`add_argument_group`.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001618
1619
1620Parser defaults
1621^^^^^^^^^^^^^^^
1622
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001623.. method:: ArgumentParser.set_defaults(**kwargs)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001624
1625 Most of the time, the attributes of the object returned by :meth:`parse_args`
1626 will be fully determined by inspecting the command-line args and the argument
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001627 actions. :meth:`ArgumentParser.set_defaults` allows some additional
1628 attributes that are determined without any inspection of the command-line to
1629 be added::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001630
1631 >>> parser = argparse.ArgumentParser()
1632 >>> parser.add_argument('foo', type=int)
1633 >>> parser.set_defaults(bar=42, baz='badger')
1634 >>> parser.parse_args(['736'])
1635 Namespace(bar=42, baz='badger', foo=736)
1636
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001637 Note that parser-level defaults always override argument-level defaults::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001638
1639 >>> parser = argparse.ArgumentParser()
1640 >>> parser.add_argument('--foo', default='bar')
1641 >>> parser.set_defaults(foo='spam')
1642 >>> parser.parse_args([])
1643 Namespace(foo='spam')
1644
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001645 Parser-level defaults can be particularly useful when working with multiple
1646 parsers. See the :meth:`~ArgumentParser.add_subparsers` method for an
1647 example of this type.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001648
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001649.. method:: ArgumentParser.get_default(dest)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001650
1651 Get the default value for a namespace attribute, as set by either
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001652 :meth:`~ArgumentParser.add_argument` or by
1653 :meth:`~ArgumentParser.set_defaults`::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001654
1655 >>> parser = argparse.ArgumentParser()
1656 >>> parser.add_argument('--foo', default='badger')
1657 >>> parser.get_default('foo')
1658 'badger'
1659
1660
1661Printing help
1662^^^^^^^^^^^^^
1663
1664In most typical applications, :meth:`parse_args` will take care of formatting
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001665and printing any usage or error messages. However, several formatting methods
1666are available:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001667
Georg Brandle0bf91d2010-10-17 10:34:28 +00001668.. method:: ArgumentParser.print_usage(file=None)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001669
1670 Print a brief description of how the :class:`ArgumentParser` should be
R. David Murray32e17712010-12-18 16:39:06 +00001671 invoked on the command line. If *file* is ``None``, :data:`sys.stdout` is
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001672 assumed.
1673
Georg Brandle0bf91d2010-10-17 10:34:28 +00001674.. method:: ArgumentParser.print_help(file=None)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001675
1676 Print a help message, including the program usage and information about the
Georg Brandle0bf91d2010-10-17 10:34:28 +00001677 arguments registered with the :class:`ArgumentParser`. If *file* is
R. David Murray32e17712010-12-18 16:39:06 +00001678 ``None``, :data:`sys.stdout` is assumed.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001679
1680There are also variants of these methods that simply return a string instead of
1681printing it:
1682
Georg Brandle0bf91d2010-10-17 10:34:28 +00001683.. method:: ArgumentParser.format_usage()
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001684
1685 Return a string containing a brief description of how the
1686 :class:`ArgumentParser` should be invoked on the command line.
1687
Georg Brandle0bf91d2010-10-17 10:34:28 +00001688.. method:: ArgumentParser.format_help()
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001689
1690 Return a string containing a help message, including the program usage and
1691 information about the arguments registered with the :class:`ArgumentParser`.
1692
1693
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001694Partial parsing
1695^^^^^^^^^^^^^^^
1696
Georg Brandle0bf91d2010-10-17 10:34:28 +00001697.. method:: ArgumentParser.parse_known_args(args=None, namespace=None)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001698
1699Sometimes a script may only parse a few of the command line arguments, passing
1700the remaining arguments on to another script or program. In these cases, the
1701:meth:`parse_known_args` method can be useful. It works much like
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001702:meth:`~ArgumentParser.parse_args` except that it does not produce an error when
1703extra arguments are present. Instead, it returns a two item tuple containing
1704the populated namespace and the list of remaining argument strings.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001705
1706::
1707
1708 >>> parser = argparse.ArgumentParser()
1709 >>> parser.add_argument('--foo', action='store_true')
1710 >>> parser.add_argument('bar')
1711 >>> parser.parse_known_args(['--foo', '--badger', 'BAR', 'spam'])
1712 (Namespace(bar='BAR', foo=True), ['--badger', 'spam'])
1713
1714
1715Customizing file parsing
1716^^^^^^^^^^^^^^^^^^^^^^^^
1717
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001718.. method:: ArgumentParser.convert_arg_line_to_args(arg_line)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001719
Georg Brandle0bf91d2010-10-17 10:34:28 +00001720 Arguments that are read from a file (see the *fromfile_prefix_chars*
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001721 keyword argument to the :class:`ArgumentParser` constructor) are read one
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001722 argument per line. :meth:`convert_arg_line_to_args` can be overriden for
1723 fancier reading.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001724
Georg Brandle0bf91d2010-10-17 10:34:28 +00001725 This method takes a single argument *arg_line* which is a string read from
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001726 the argument file. It returns a list of arguments parsed from this string.
1727 The method is called once per line read from the argument file, in order.
1728
1729 A useful override of this method is one that treats each space-separated word
1730 as an argument::
1731
1732 def convert_arg_line_to_args(self, arg_line):
1733 for arg in arg_line.split():
1734 if not arg.strip():
1735 continue
1736 yield arg
1737
1738
Georg Brandl93754922010-10-17 10:28:04 +00001739Exiting methods
1740^^^^^^^^^^^^^^^
1741
1742.. method:: ArgumentParser.exit(status=0, message=None)
1743
1744 This method terminates the program, exiting with the specified *status*
1745 and, if given, it prints a *message* before that.
1746
1747.. method:: ArgumentParser.error(message)
1748
1749 This method prints a usage message including the *message* to the
1750 standard output and terminates the program with a status code of 2.
1751
Raymond Hettinger677e10a2010-12-07 06:45:30 +00001752.. _upgrading-optparse-code:
Georg Brandl93754922010-10-17 10:28:04 +00001753
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001754Upgrading optparse code
1755-----------------------
1756
1757Originally, the argparse module had attempted to maintain compatibility with
1758optparse. However, optparse was difficult to extend transparently, particularly
1759with the changes required to support the new ``nargs=`` specifiers and better
Georg Brandl386bc6d2010-04-25 10:19:53 +00001760usage messages. When most everything in optparse had either been copy-pasted
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001761over or monkey-patched, it no longer seemed practical to try to maintain the
1762backwards compatibility.
1763
1764A partial upgrade path from optparse to argparse:
1765
Georg Brandlc9007082011-01-09 09:04:08 +00001766* Replace all ``add_option()`` calls with :meth:`ArgumentParser.add_argument`
1767 calls.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001768
1769* Replace ``options, args = parser.parse_args()`` with ``args =
Georg Brandlc9007082011-01-09 09:04:08 +00001770 parser.parse_args()`` and add additional :meth:`ArgumentParser.add_argument`
1771 calls for the positional arguments.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001772
1773* Replace callback actions and the ``callback_*`` keyword arguments with
1774 ``type`` or ``action`` arguments.
1775
1776* Replace string names for ``type`` keyword arguments with the corresponding
1777 type objects (e.g. int, float, complex, etc).
1778
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001779* Replace :class:`optparse.Values` with :class:`Namespace` and
1780 :exc:`optparse.OptionError` and :exc:`optparse.OptionValueError` with
1781 :exc:`ArgumentError`.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001782
1783* Replace strings with implicit arguments such as ``%default`` or ``%prog`` with
1784 the standard python syntax to use dictionaries to format strings, that is,
1785 ``%(default)s`` and ``%(prog)s``.
Steven Bethard59710962010-05-24 03:21:08 +00001786
1787* Replace the OptionParser constructor ``version`` argument with a call to
1788 ``parser.add_argument('--version', action='version', version='<the version>')``