blob: 93d7647f6f61f9b134adca2fd95e39f7a7361d7a [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
Ezio Melotti2409d772011-04-16 23:13:50 +03005 :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**Source code:** :source:`Lib/argparse.py`
10
11.. versionadded:: 3.2
12
13--------------
Benjamin Peterson698a18a2010-03-02 22:34:37 +000014
Ezio Melotti2409d772011-04-16 23:13:50 +030015The :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
Ezio Melotticca4ef82011-04-21 15:26:46 +030082parse 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
Georg Brandl1d827ff2011-04-16 16:44:54 +0200111: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
Georg Brandl1d827ff2011-04-16 16:44:54 +0200114attributes parsed out of the command line::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000115
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
Georg Brandl1d827ff2011-04-16 16:44:54 +0200224If ``-h`` or ``--help`` is supplied at the command line, the ArgumentParser
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000225help 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
Steven Bethardd186f992011-03-26 21:49:00 +0100354.. note::
355 You must fully initialize the parsers before passing them via ``parents=``.
356 If you change the parent parsers after the child parser, those changes will
357 not be reflected in the child.
358
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000359
360formatter_class
361^^^^^^^^^^^^^^^
362
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000363:class:`ArgumentParser` objects allow the help formatting to be customized by
364specifying an alternate formatting class. Currently, there are three such
365classes: :class:`argparse.RawDescriptionHelpFormatter`,
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000366:class:`argparse.RawTextHelpFormatter` and
367:class:`argparse.ArgumentDefaultsHelpFormatter`. The first two allow more
368control over how textual descriptions are displayed, while the last
369automatically adds information about argument default values.
370
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000371By default, :class:`ArgumentParser` objects line-wrap the description_ and
372epilog_ texts in command-line help messages::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000373
374 >>> parser = argparse.ArgumentParser(
375 ... prog='PROG',
376 ... description='''this description
377 ... was indented weird
378 ... but that is okay''',
379 ... epilog='''
380 ... likewise for this epilog whose whitespace will
381 ... be cleaned up and whose words will be wrapped
382 ... across a couple lines''')
383 >>> parser.print_help()
384 usage: PROG [-h]
385
386 this description was indented weird but that is okay
387
388 optional arguments:
389 -h, --help show this help message and exit
390
391 likewise for this epilog whose whitespace will be cleaned up and whose words
392 will be wrapped across a couple lines
393
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000394Passing :class:`argparse.RawDescriptionHelpFormatter` as ``formatter_class=``
395indicates that description_ and epilog_ are already correctly formatted and
396should not be line-wrapped::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000397
398 >>> parser = argparse.ArgumentParser(
399 ... prog='PROG',
400 ... formatter_class=argparse.RawDescriptionHelpFormatter,
401 ... description=textwrap.dedent('''\
402 ... Please do not mess up this text!
403 ... --------------------------------
404 ... I have indented it
405 ... exactly the way
406 ... I want it
407 ... '''))
408 >>> parser.print_help()
409 usage: PROG [-h]
410
411 Please do not mess up this text!
412 --------------------------------
413 I have indented it
414 exactly the way
415 I want it
416
417 optional arguments:
418 -h, --help show this help message and exit
419
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000420:class:`RawTextHelpFormatter` maintains whitespace for all sorts of help text
421including argument descriptions.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000422
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000423The other formatter class available, :class:`ArgumentDefaultsHelpFormatter`,
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000424will add information about the default value of each of the arguments::
425
426 >>> parser = argparse.ArgumentParser(
427 ... prog='PROG',
428 ... formatter_class=argparse.ArgumentDefaultsHelpFormatter)
429 >>> parser.add_argument('--foo', type=int, default=42, help='FOO!')
430 >>> parser.add_argument('bar', nargs='*', default=[1, 2, 3], help='BAR!')
431 >>> parser.print_help()
432 usage: PROG [-h] [--foo FOO] [bar [bar ...]]
433
434 positional arguments:
435 bar BAR! (default: [1, 2, 3])
436
437 optional arguments:
438 -h, --help show this help message and exit
439 --foo FOO FOO! (default: 42)
440
441
442conflict_handler
443^^^^^^^^^^^^^^^^
444
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000445:class:`ArgumentParser` objects do not allow two actions with the same option
446string. By default, :class:`ArgumentParser` objects raises an exception if an
447attempt is made to create an argument with an option string that is already in
448use::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000449
450 >>> parser = argparse.ArgumentParser(prog='PROG')
451 >>> parser.add_argument('-f', '--foo', help='old foo help')
452 >>> parser.add_argument('--foo', help='new foo help')
453 Traceback (most recent call last):
454 ..
455 ArgumentError: argument --foo: conflicting option string(s): --foo
456
457Sometimes (e.g. when using parents_) it may be useful to simply override any
458older arguments with the same option string. To get this behavior, the value
459``'resolve'`` can be supplied to the ``conflict_handler=`` argument of
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000460:class:`ArgumentParser`::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000461
462 >>> parser = argparse.ArgumentParser(prog='PROG', conflict_handler='resolve')
463 >>> parser.add_argument('-f', '--foo', help='old foo help')
464 >>> parser.add_argument('--foo', help='new foo help')
465 >>> parser.print_help()
466 usage: PROG [-h] [-f FOO] [--foo FOO]
467
468 optional arguments:
469 -h, --help show this help message and exit
470 -f FOO old foo help
471 --foo FOO new foo help
472
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000473Note that :class:`ArgumentParser` objects only remove an action if all of its
474option strings are overridden. So, in the example above, the old ``-f/--foo``
475action is retained as the ``-f`` action, because only the ``--foo`` option
476string was overridden.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000477
478
479prog
480^^^^
481
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000482By default, :class:`ArgumentParser` objects uses ``sys.argv[0]`` to determine
483how to display the name of the program in help messages. This default is almost
Ezio Melottif82340d2010-05-27 22:38:16 +0000484always desirable because it will make the help messages match how the program was
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000485invoked on the command line. For example, consider a file named
486``myprogram.py`` with the following code::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000487
488 import argparse
489 parser = argparse.ArgumentParser()
490 parser.add_argument('--foo', help='foo help')
491 args = parser.parse_args()
492
493The help for this program will display ``myprogram.py`` as the program name
494(regardless of where the program was invoked from)::
495
496 $ python myprogram.py --help
497 usage: myprogram.py [-h] [--foo FOO]
498
499 optional arguments:
500 -h, --help show this help message and exit
501 --foo FOO foo help
502 $ cd ..
503 $ python subdir\myprogram.py --help
504 usage: myprogram.py [-h] [--foo FOO]
505
506 optional arguments:
507 -h, --help show this help message and exit
508 --foo FOO foo help
509
510To change this default behavior, another value can be supplied using the
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000511``prog=`` argument to :class:`ArgumentParser`::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000512
513 >>> parser = argparse.ArgumentParser(prog='myprogram')
514 >>> parser.print_help()
515 usage: myprogram [-h]
516
517 optional arguments:
518 -h, --help show this help message and exit
519
520Note that the program name, whether determined from ``sys.argv[0]`` or from the
521``prog=`` argument, is available to help messages using the ``%(prog)s`` format
522specifier.
523
524::
525
526 >>> parser = argparse.ArgumentParser(prog='myprogram')
527 >>> parser.add_argument('--foo', help='foo of the %(prog)s program')
528 >>> parser.print_help()
529 usage: myprogram [-h] [--foo FOO]
530
531 optional arguments:
532 -h, --help show this help message and exit
533 --foo FOO foo of the myprogram program
534
535
536usage
537^^^^^
538
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000539By default, :class:`ArgumentParser` calculates the usage message from the
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000540arguments it contains::
541
542 >>> parser = argparse.ArgumentParser(prog='PROG')
543 >>> parser.add_argument('--foo', nargs='?', help='foo help')
544 >>> parser.add_argument('bar', nargs='+', help='bar help')
545 >>> parser.print_help()
546 usage: PROG [-h] [--foo [FOO]] bar [bar ...]
547
548 positional arguments:
549 bar bar help
550
551 optional arguments:
552 -h, --help show this help message and exit
553 --foo [FOO] foo help
554
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000555The default message can be overridden with the ``usage=`` keyword argument::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000556
557 >>> parser = argparse.ArgumentParser(prog='PROG', usage='%(prog)s [options]')
558 >>> parser.add_argument('--foo', nargs='?', help='foo help')
559 >>> parser.add_argument('bar', nargs='+', help='bar help')
560 >>> parser.print_help()
561 usage: PROG [options]
562
563 positional arguments:
564 bar bar help
565
566 optional arguments:
567 -h, --help show this help message and exit
568 --foo [FOO] foo help
569
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000570The ``%(prog)s`` format specifier is available to fill in the program name in
571your usage messages.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000572
573
574The add_argument() method
575-------------------------
576
Georg Brandlc9007082011-01-09 09:04:08 +0000577.. method:: ArgumentParser.add_argument(name or flags..., [action], [nargs], \
578 [const], [default], [type], [choices], [required], \
579 [help], [metavar], [dest])
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000580
Georg Brandl1d827ff2011-04-16 16:44:54 +0200581 Define how a single command-line argument should be parsed. Each parameter
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000582 has its own more detailed description below, but in short they are:
583
584 * `name or flags`_ - Either a name or a list of option strings, e.g. ``foo``
585 or ``-f, --foo``
586
587 * action_ - The basic type of action to be taken when this argument is
Georg Brandl1d827ff2011-04-16 16:44:54 +0200588 encountered at the command line.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000589
590 * nargs_ - The number of command-line arguments that should be consumed.
591
592 * const_ - A constant value required by some action_ and nargs_ selections.
593
594 * default_ - The value produced if the argument is absent from the
Georg Brandl1d827ff2011-04-16 16:44:54 +0200595 command line.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000596
Ezio Melotti2409d772011-04-16 23:13:50 +0300597 * type_ - The type to which the command-line argument should be converted.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000598
599 * choices_ - A container of the allowable values for the argument.
600
601 * required_ - Whether or not the command-line option may be omitted
602 (optionals only).
603
604 * help_ - A brief description of what the argument does.
605
606 * metavar_ - A name for the argument in usage messages.
607
608 * dest_ - The name of the attribute to be added to the object returned by
609 :meth:`parse_args`.
610
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000611The following sections describe how each of these are used.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000612
Georg Brandle0bf91d2010-10-17 10:34:28 +0000613
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000614name or flags
615^^^^^^^^^^^^^
616
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000617The :meth:`add_argument` method must know whether an optional argument, like
618``-f`` or ``--foo``, or a positional argument, like a list of filenames, is
619expected. The first arguments passed to :meth:`add_argument` must therefore be
620either a series of flags, or a simple argument name. For example, an optional
621argument could be created like::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000622
623 >>> parser.add_argument('-f', '--foo')
624
625while a positional argument could be created like::
626
627 >>> parser.add_argument('bar')
628
629When :meth:`parse_args` is called, optional arguments will be identified by the
630``-`` prefix, and the remaining arguments will be assumed to be positional::
631
632 >>> parser = argparse.ArgumentParser(prog='PROG')
633 >>> parser.add_argument('-f', '--foo')
634 >>> parser.add_argument('bar')
635 >>> parser.parse_args(['BAR'])
636 Namespace(bar='BAR', foo=None)
637 >>> parser.parse_args(['BAR', '--foo', 'FOO'])
638 Namespace(bar='BAR', foo='FOO')
639 >>> parser.parse_args(['--foo', 'FOO'])
640 usage: PROG [-h] [-f FOO] bar
641 PROG: error: too few arguments
642
Georg Brandle0bf91d2010-10-17 10:34:28 +0000643
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000644action
645^^^^^^
646
647:class:`ArgumentParser` objects associate command-line args with actions. These
648actions can do just about anything with the command-line args associated with
649them, though most actions simply add an attribute to the object returned by
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000650:meth:`parse_args`. The ``action`` keyword argument specifies how the
651command-line args should be handled. The supported actions are:
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000652
653* ``'store'`` - This just stores the argument's value. This is the default
654 action. For example::
655
656 >>> parser = argparse.ArgumentParser()
657 >>> parser.add_argument('--foo')
658 >>> parser.parse_args('--foo 1'.split())
659 Namespace(foo='1')
660
661* ``'store_const'`` - This stores the value specified by the const_ keyword
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000662 argument. (Note that the const_ keyword argument defaults to the rather
663 unhelpful ``None``.) The ``'store_const'`` action is most commonly used with
664 optional arguments that specify some sort of flag. For example::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000665
666 >>> parser = argparse.ArgumentParser()
667 >>> parser.add_argument('--foo', action='store_const', const=42)
668 >>> parser.parse_args('--foo'.split())
669 Namespace(foo=42)
670
671* ``'store_true'`` and ``'store_false'`` - These store the values ``True`` and
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000672 ``False`` respectively. These are special cases of ``'store_const'``. For
673 example::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000674
675 >>> parser = argparse.ArgumentParser()
676 >>> parser.add_argument('--foo', action='store_true')
677 >>> parser.add_argument('--bar', action='store_false')
678 >>> parser.parse_args('--foo --bar'.split())
679 Namespace(bar=False, foo=True)
680
681* ``'append'`` - This stores a list, and appends each argument value to the
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000682 list. This is useful to allow an option to be specified multiple times.
683 Example usage::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000684
685 >>> parser = argparse.ArgumentParser()
686 >>> parser.add_argument('--foo', action='append')
687 >>> parser.parse_args('--foo 1 --foo 2'.split())
688 Namespace(foo=['1', '2'])
689
690* ``'append_const'`` - This stores a list, and appends the value specified by
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000691 the const_ keyword argument to the list. (Note that the const_ keyword
692 argument defaults to ``None``.) The ``'append_const'`` action is typically
693 useful when multiple arguments need to store constants to the same list. For
694 example::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000695
696 >>> parser = argparse.ArgumentParser()
697 >>> parser.add_argument('--str', dest='types', action='append_const', const=str)
698 >>> parser.add_argument('--int', dest='types', action='append_const', const=int)
699 >>> parser.parse_args('--str --int'.split())
700 Namespace(types=[<type 'str'>, <type 'int'>])
701
702* ``'version'`` - This expects a ``version=`` keyword argument in the
703 :meth:`add_argument` call, and prints version information and exits when
704 invoked.
705
706 >>> import argparse
707 >>> parser = argparse.ArgumentParser(prog='PROG')
Steven Bethard59710962010-05-24 03:21:08 +0000708 >>> parser.add_argument('--version', action='version', version='%(prog)s 2.0')
709 >>> parser.parse_args(['--version'])
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000710 PROG 2.0
711
712You can also specify an arbitrary action by passing an object that implements
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000713the Action API. The easiest way to do this is to extend
714:class:`argparse.Action`, supplying an appropriate ``__call__`` method. The
715``__call__`` method should accept four parameters:
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000716
717* ``parser`` - The ArgumentParser object which contains this action.
718
719* ``namespace`` - The namespace object that will be returned by
720 :meth:`parse_args`. Most actions add an attribute to this object.
721
722* ``values`` - The associated command-line args, with any type-conversions
723 applied. (Type-conversions are specified with the type_ keyword argument to
724 :meth:`add_argument`.
725
726* ``option_string`` - The option string that was used to invoke this action.
727 The ``option_string`` argument is optional, and will be absent if the action
728 is associated with a positional argument.
729
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000730An example of a custom action::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000731
732 >>> class FooAction(argparse.Action):
733 ... def __call__(self, parser, namespace, values, option_string=None):
Georg Brandl571a9532010-07-26 17:00:20 +0000734 ... print('%r %r %r' % (namespace, values, option_string))
735 ... setattr(namespace, self.dest, values)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000736 ...
737 >>> parser = argparse.ArgumentParser()
738 >>> parser.add_argument('--foo', action=FooAction)
739 >>> parser.add_argument('bar', action=FooAction)
740 >>> args = parser.parse_args('1 --foo 2'.split())
741 Namespace(bar=None, foo=None) '1' None
742 Namespace(bar='1', foo=None) '2' '--foo'
743 >>> args
744 Namespace(bar='1', foo='2')
745
746
747nargs
748^^^^^
749
750ArgumentParser objects usually associate a single command-line argument with a
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000751single action to be taken. The ``nargs`` keyword argument associates a
752different number of command-line arguments with a single action.. The supported
753values are:
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000754
Georg Brandl1d827ff2011-04-16 16:44:54 +0200755* N (an integer). N args from the command line will be gathered together into a
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000756 list. For example::
757
Georg Brandl682d7e02010-10-06 10:26:05 +0000758 >>> parser = argparse.ArgumentParser()
759 >>> parser.add_argument('--foo', nargs=2)
760 >>> parser.add_argument('bar', nargs=1)
761 >>> parser.parse_args('c --foo a b'.split())
762 Namespace(bar=['c'], foo=['a', 'b'])
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000763
Georg Brandl682d7e02010-10-06 10:26:05 +0000764 Note that ``nargs=1`` produces a list of one item. This is different from
765 the default, in which the item is produced by itself.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000766
Georg Brandl1d827ff2011-04-16 16:44:54 +0200767* ``'?'``. One arg will be consumed from the command line if possible, and
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000768 produced as a single item. If no command-line arg is present, the value from
769 default_ will be produced. Note that for optional arguments, there is an
770 additional case - the option string is present but not followed by a
771 command-line arg. In this case the value from const_ will be produced. Some
772 examples to illustrate this::
773
774 >>> parser = argparse.ArgumentParser()
775 >>> parser.add_argument('--foo', nargs='?', const='c', default='d')
776 >>> parser.add_argument('bar', nargs='?', default='d')
777 >>> parser.parse_args('XX --foo YY'.split())
778 Namespace(bar='XX', foo='YY')
779 >>> parser.parse_args('XX --foo'.split())
780 Namespace(bar='XX', foo='c')
781 >>> parser.parse_args(''.split())
782 Namespace(bar='d', foo='d')
783
784 One of the more common uses of ``nargs='?'`` is to allow optional input and
785 output files::
786
787 >>> parser = argparse.ArgumentParser()
Georg Brandle0bf91d2010-10-17 10:34:28 +0000788 >>> parser.add_argument('infile', nargs='?', type=argparse.FileType('r'),
789 ... default=sys.stdin)
790 >>> parser.add_argument('outfile', nargs='?', type=argparse.FileType('w'),
791 ... default=sys.stdout)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000792 >>> parser.parse_args(['input.txt', 'output.txt'])
Georg Brandl04536b02011-01-09 09:31:01 +0000793 Namespace(infile=<_io.TextIOWrapper name='input.txt' encoding='UTF-8'>,
794 outfile=<_io.TextIOWrapper name='output.txt' encoding='UTF-8'>)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000795 >>> parser.parse_args([])
Georg Brandl04536b02011-01-09 09:31:01 +0000796 Namespace(infile=<_io.TextIOWrapper name='<stdin>' encoding='UTF-8'>,
797 outfile=<_io.TextIOWrapper name='<stdout>' encoding='UTF-8'>)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000798
799* ``'*'``. All command-line args present are gathered into a list. Note that
800 it generally doesn't make much sense to have more than one positional argument
801 with ``nargs='*'``, but multiple optional arguments with ``nargs='*'`` is
802 possible. For example::
803
804 >>> parser = argparse.ArgumentParser()
805 >>> parser.add_argument('--foo', nargs='*')
806 >>> parser.add_argument('--bar', nargs='*')
807 >>> parser.add_argument('baz', nargs='*')
808 >>> parser.parse_args('a b --foo x y --bar 1 2'.split())
809 Namespace(bar=['1', '2'], baz=['a', 'b'], foo=['x', 'y'])
810
811* ``'+'``. Just like ``'*'``, all command-line args present are gathered into a
812 list. Additionally, an error message will be generated if there wasn't at
813 least one command-line arg present. For example::
814
815 >>> parser = argparse.ArgumentParser(prog='PROG')
816 >>> parser.add_argument('foo', nargs='+')
817 >>> parser.parse_args('a b'.split())
818 Namespace(foo=['a', 'b'])
819 >>> parser.parse_args(''.split())
820 usage: PROG [-h] foo [foo ...]
821 PROG: error: too few arguments
822
823If the ``nargs`` keyword argument is not provided, the number of args consumed
824is determined by the action_. Generally this means a single command-line arg
825will be consumed and a single item (not a list) will be produced.
826
827
828const
829^^^^^
830
831The ``const`` argument of :meth:`add_argument` is used to hold constant values
832that are not read from the command line but are required for the various
833ArgumentParser actions. The two most common uses of it are:
834
835* When :meth:`add_argument` is called with ``action='store_const'`` or
836 ``action='append_const'``. These actions add the ``const`` value to one of
837 the attributes of the object returned by :meth:`parse_args`. See the action_
838 description for examples.
839
840* When :meth:`add_argument` is called with option strings (like ``-f`` or
841 ``--foo``) and ``nargs='?'``. This creates an optional argument that can be
Georg Brandl1d827ff2011-04-16 16:44:54 +0200842 followed by zero or one command-line args. When parsing the command line, if
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000843 the option string is encountered with no command-line arg following it, the
844 value of ``const`` will be assumed instead. See the nargs_ description for
845 examples.
846
847The ``const`` keyword argument defaults to ``None``.
848
849
850default
851^^^^^^^
852
853All optional arguments and some positional arguments may be omitted at the
Georg Brandl1d827ff2011-04-16 16:44:54 +0200854command line. The ``default`` keyword argument of :meth:`add_argument`, whose
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000855value defaults to ``None``, specifies what value should be used if the
856command-line arg is not present. For optional arguments, the ``default`` value
857is used when the option string was not present at the command line::
858
859 >>> parser = argparse.ArgumentParser()
860 >>> parser.add_argument('--foo', default=42)
861 >>> parser.parse_args('--foo 2'.split())
862 Namespace(foo='2')
863 >>> parser.parse_args(''.split())
864 Namespace(foo=42)
865
866For positional arguments with nargs_ ``='?'`` or ``'*'``, the ``default`` value
867is used when no command-line arg was present::
868
869 >>> parser = argparse.ArgumentParser()
870 >>> parser.add_argument('foo', nargs='?', default=42)
871 >>> parser.parse_args('a'.split())
872 Namespace(foo='a')
873 >>> parser.parse_args(''.split())
874 Namespace(foo=42)
875
876
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000877Providing ``default=argparse.SUPPRESS`` causes no attribute to be added if the
878command-line argument was not present.::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000879
880 >>> parser = argparse.ArgumentParser()
881 >>> parser.add_argument('--foo', default=argparse.SUPPRESS)
882 >>> parser.parse_args([])
883 Namespace()
884 >>> parser.parse_args(['--foo', '1'])
885 Namespace(foo='1')
886
887
888type
889^^^^
890
891By default, ArgumentParser objects read command-line args in as simple strings.
892However, quite often the command-line string should instead be interpreted as
Georg Brandl04536b02011-01-09 09:31:01 +0000893another type, like a :class:`float` or :class:`int`. The ``type`` keyword
894argument of :meth:`add_argument` allows any necessary type-checking and
895type-conversions to be performed. Common built-in types and functions can be
896used directly as the value of the ``type`` argument::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000897
898 >>> parser = argparse.ArgumentParser()
899 >>> parser.add_argument('foo', type=int)
Georg Brandl04536b02011-01-09 09:31:01 +0000900 >>> parser.add_argument('bar', type=open)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000901 >>> parser.parse_args('2 temp.txt'.split())
Georg Brandl04536b02011-01-09 09:31:01 +0000902 Namespace(bar=<_io.TextIOWrapper name='temp.txt' encoding='UTF-8'>, foo=2)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000903
904To ease the use of various types of files, the argparse module provides the
905factory FileType which takes the ``mode=`` and ``bufsize=`` arguments of the
Georg Brandl04536b02011-01-09 09:31:01 +0000906:func:`open` function. For example, ``FileType('w')`` can be used to create a
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000907writable file::
908
909 >>> parser = argparse.ArgumentParser()
910 >>> parser.add_argument('bar', type=argparse.FileType('w'))
911 >>> parser.parse_args(['out.txt'])
Georg Brandl04536b02011-01-09 09:31:01 +0000912 Namespace(bar=<_io.TextIOWrapper name='out.txt' encoding='UTF-8'>)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000913
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000914``type=`` can take any callable that takes a single string argument and returns
915the type-converted value::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000916
917 >>> def perfect_square(string):
918 ... value = int(string)
919 ... sqrt = math.sqrt(value)
920 ... if sqrt != int(sqrt):
921 ... msg = "%r is not a perfect square" % string
922 ... raise argparse.ArgumentTypeError(msg)
923 ... return value
924 ...
925 >>> parser = argparse.ArgumentParser(prog='PROG')
926 >>> parser.add_argument('foo', type=perfect_square)
927 >>> parser.parse_args('9'.split())
928 Namespace(foo=9)
929 >>> parser.parse_args('7'.split())
930 usage: PROG [-h] foo
931 PROG: error: argument foo: '7' is not a perfect square
932
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000933The choices_ keyword argument may be more convenient for type checkers that
934simply check against a range of values::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000935
936 >>> parser = argparse.ArgumentParser(prog='PROG')
Fred Drakec7eb7892011-03-03 05:29:59 +0000937 >>> parser.add_argument('foo', type=int, choices=range(5, 10))
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000938 >>> parser.parse_args('7'.split())
939 Namespace(foo=7)
940 >>> parser.parse_args('11'.split())
941 usage: PROG [-h] {5,6,7,8,9}
942 PROG: error: argument foo: invalid choice: 11 (choose from 5, 6, 7, 8, 9)
943
944See the choices_ section for more details.
945
946
947choices
948^^^^^^^
949
950Some command-line args should be selected from a restricted set of values.
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000951These can be handled by passing a container object as the ``choices`` keyword
Georg Brandl1d827ff2011-04-16 16:44:54 +0200952argument to :meth:`add_argument`. When the command line is parsed, arg values
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000953will be checked, and an error message will be displayed if the arg was not one
954of the acceptable values::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000955
956 >>> parser = argparse.ArgumentParser(prog='PROG')
957 >>> parser.add_argument('foo', choices='abc')
958 >>> parser.parse_args('c'.split())
959 Namespace(foo='c')
960 >>> parser.parse_args('X'.split())
961 usage: PROG [-h] {a,b,c}
962 PROG: error: argument foo: invalid choice: 'X' (choose from 'a', 'b', 'c')
963
964Note that inclusion in the ``choices`` container is checked after any type_
965conversions have been performed, so the type of the objects in the ``choices``
966container should match the type_ specified::
967
968 >>> parser = argparse.ArgumentParser(prog='PROG')
969 >>> parser.add_argument('foo', type=complex, choices=[1, 1j])
970 >>> parser.parse_args('1j'.split())
971 Namespace(foo=1j)
972 >>> parser.parse_args('-- -4'.split())
973 usage: PROG [-h] {1,1j}
974 PROG: error: argument foo: invalid choice: (-4+0j) (choose from 1, 1j)
975
976Any object that supports the ``in`` operator can be passed as the ``choices``
977value, so :class:`dict` objects, :class:`set` objects, custom containers,
978etc. are all supported.
979
980
981required
982^^^^^^^^
983
984In general, the argparse module assumes that flags like ``-f`` and ``--bar``
Georg Brandl1d827ff2011-04-16 16:44:54 +0200985indicate *optional* arguments, which can always be omitted at the command line.
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000986To make an option *required*, ``True`` can be specified for the ``required=``
987keyword argument to :meth:`add_argument`::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000988
989 >>> parser = argparse.ArgumentParser()
990 >>> parser.add_argument('--foo', required=True)
991 >>> parser.parse_args(['--foo', 'BAR'])
992 Namespace(foo='BAR')
993 >>> parser.parse_args([])
994 usage: argparse.py [-h] [--foo FOO]
995 argparse.py: error: option --foo is required
996
997As the example shows, if an option is marked as ``required``, :meth:`parse_args`
998will report an error if that option is not present at the command line.
999
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001000.. note::
1001
1002 Required options are generally considered bad form because users expect
1003 *options* to be *optional*, and thus they should be avoided when possible.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001004
1005
1006help
1007^^^^
1008
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001009The ``help`` value is a string containing a brief description of the argument.
1010When a user requests help (usually by using ``-h`` or ``--help`` at the
Georg Brandl1d827ff2011-04-16 16:44:54 +02001011command line), these ``help`` descriptions will be displayed with each
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001012argument::
1013
1014 >>> parser = argparse.ArgumentParser(prog='frobble')
1015 >>> parser.add_argument('--foo', action='store_true',
1016 ... help='foo the bars before frobbling')
1017 >>> parser.add_argument('bar', nargs='+',
1018 ... help='one of the bars to be frobbled')
1019 >>> parser.parse_args('-h'.split())
1020 usage: frobble [-h] [--foo] bar [bar ...]
1021
1022 positional arguments:
1023 bar one of the bars to be frobbled
1024
1025 optional arguments:
1026 -h, --help show this help message and exit
1027 --foo foo the bars before frobbling
1028
1029The ``help`` strings can include various format specifiers to avoid repetition
1030of things like the program name or the argument default_. The available
1031specifiers include the program name, ``%(prog)s`` and most keyword arguments to
1032:meth:`add_argument`, e.g. ``%(default)s``, ``%(type)s``, etc.::
1033
1034 >>> parser = argparse.ArgumentParser(prog='frobble')
1035 >>> parser.add_argument('bar', nargs='?', type=int, default=42,
1036 ... help='the bar to %(prog)s (default: %(default)s)')
1037 >>> parser.print_help()
1038 usage: frobble [-h] [bar]
1039
1040 positional arguments:
1041 bar the bar to frobble (default: 42)
1042
1043 optional arguments:
1044 -h, --help show this help message and exit
1045
1046
1047metavar
1048^^^^^^^
1049
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001050When :class:`ArgumentParser` generates help messages, it need some way to refer
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001051to each expected argument. By default, ArgumentParser objects use the dest_
1052value as the "name" of each object. By default, for positional argument
1053actions, the dest_ value is used directly, and for optional argument actions,
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001054the dest_ value is uppercased. So, a single positional argument with
1055``dest='bar'`` will that argument will be referred to as ``bar``. A single
1056optional argument ``--foo`` that should be followed by a single command-line arg
1057will be referred to as ``FOO``. An example::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001058
1059 >>> parser = argparse.ArgumentParser()
1060 >>> parser.add_argument('--foo')
1061 >>> parser.add_argument('bar')
1062 >>> parser.parse_args('X --foo Y'.split())
1063 Namespace(bar='X', foo='Y')
1064 >>> parser.print_help()
1065 usage: [-h] [--foo FOO] bar
1066
1067 positional arguments:
1068 bar
1069
1070 optional arguments:
1071 -h, --help show this help message and exit
1072 --foo FOO
1073
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001074An alternative name can be specified with ``metavar``::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001075
1076 >>> parser = argparse.ArgumentParser()
1077 >>> parser.add_argument('--foo', metavar='YYY')
1078 >>> parser.add_argument('bar', metavar='XXX')
1079 >>> parser.parse_args('X --foo Y'.split())
1080 Namespace(bar='X', foo='Y')
1081 >>> parser.print_help()
1082 usage: [-h] [--foo YYY] XXX
1083
1084 positional arguments:
1085 XXX
1086
1087 optional arguments:
1088 -h, --help show this help message and exit
1089 --foo YYY
1090
1091Note that ``metavar`` only changes the *displayed* name - the name of the
1092attribute on the :meth:`parse_args` object is still determined by the dest_
1093value.
1094
1095Different values of ``nargs`` may cause the metavar to be used multiple times.
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001096Providing a tuple to ``metavar`` specifies a different display for each of the
1097arguments::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001098
1099 >>> parser = argparse.ArgumentParser(prog='PROG')
1100 >>> parser.add_argument('-x', nargs=2)
1101 >>> parser.add_argument('--foo', nargs=2, metavar=('bar', 'baz'))
1102 >>> parser.print_help()
1103 usage: PROG [-h] [-x X X] [--foo bar baz]
1104
1105 optional arguments:
1106 -h, --help show this help message and exit
1107 -x X X
1108 --foo bar baz
1109
1110
1111dest
1112^^^^
1113
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001114Most :class:`ArgumentParser` actions add some value as an attribute of the
1115object returned by :meth:`parse_args`. The name of this attribute is determined
1116by the ``dest`` keyword argument of :meth:`add_argument`. For positional
1117argument actions, ``dest`` is normally supplied as the first argument to
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001118:meth:`add_argument`::
1119
1120 >>> parser = argparse.ArgumentParser()
1121 >>> parser.add_argument('bar')
1122 >>> parser.parse_args('XXX'.split())
1123 Namespace(bar='XXX')
1124
1125For optional argument actions, the value of ``dest`` is normally inferred from
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001126the option strings. :class:`ArgumentParser` generates the value of ``dest`` by
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001127taking the first long option string and stripping away the initial ``'--'``
1128string. If no long option strings were supplied, ``dest`` will be derived from
1129the first short option string by stripping the initial ``'-'`` character. Any
1130internal ``'-'`` characters will be converted to ``'_'`` characters to make sure
1131the string is a valid attribute name. The examples below illustrate this
1132behavior::
1133
1134 >>> parser = argparse.ArgumentParser()
1135 >>> parser.add_argument('-f', '--foo-bar', '--foo')
1136 >>> parser.add_argument('-x', '-y')
1137 >>> parser.parse_args('-f 1 -x 2'.split())
1138 Namespace(foo_bar='1', x='2')
1139 >>> parser.parse_args('--foo 1 -y 2'.split())
1140 Namespace(foo_bar='1', x='2')
1141
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001142``dest`` allows a custom attribute name to be provided::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001143
1144 >>> parser = argparse.ArgumentParser()
1145 >>> parser.add_argument('--foo', dest='bar')
1146 >>> parser.parse_args('--foo XXX'.split())
1147 Namespace(bar='XXX')
1148
1149
1150The parse_args() method
1151-----------------------
1152
Georg Brandle0bf91d2010-10-17 10:34:28 +00001153.. method:: ArgumentParser.parse_args(args=None, namespace=None)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001154
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001155 Convert argument strings to objects and assign them as attributes of the
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001156 namespace. Return the populated namespace.
1157
1158 Previous calls to :meth:`add_argument` determine exactly what objects are
1159 created and how they are assigned. See the documentation for
1160 :meth:`add_argument` for details.
1161
1162 By default, the arg strings are taken from :data:`sys.argv`, and a new empty
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001163 :class:`Namespace` object is created for the attributes.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001164
Georg Brandle0bf91d2010-10-17 10:34:28 +00001165
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001166Option value syntax
1167^^^^^^^^^^^^^^^^^^^
1168
1169The :meth:`parse_args` method supports several ways of specifying the value of
1170an option (if it takes one). In the simplest case, the option and its value are
1171passed as two separate arguments::
1172
1173 >>> parser = argparse.ArgumentParser(prog='PROG')
1174 >>> parser.add_argument('-x')
1175 >>> parser.add_argument('--foo')
1176 >>> parser.parse_args('-x X'.split())
1177 Namespace(foo=None, x='X')
1178 >>> parser.parse_args('--foo FOO'.split())
1179 Namespace(foo='FOO', x=None)
1180
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001181For long options (options with names longer than a single character), the option
Georg Brandl1d827ff2011-04-16 16:44:54 +02001182and value can also be passed as a single command-line argument, using ``=`` to
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001183separate them::
1184
1185 >>> parser.parse_args('--foo=FOO'.split())
1186 Namespace(foo='FOO', x=None)
1187
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001188For short options (options only one character long), the option and its value
1189can be concatenated::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001190
1191 >>> parser.parse_args('-xX'.split())
1192 Namespace(foo=None, x='X')
1193
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001194Several short options can be joined together, using only a single ``-`` prefix,
1195as long as only the last option (or none of them) requires a value::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001196
1197 >>> parser = argparse.ArgumentParser(prog='PROG')
1198 >>> parser.add_argument('-x', action='store_true')
1199 >>> parser.add_argument('-y', action='store_true')
1200 >>> parser.add_argument('-z')
1201 >>> parser.parse_args('-xyzZ'.split())
1202 Namespace(x=True, y=True, z='Z')
1203
1204
1205Invalid arguments
1206^^^^^^^^^^^^^^^^^
1207
Georg Brandl1d827ff2011-04-16 16:44:54 +02001208While parsing the command line, ``parse_args`` checks for a variety of errors,
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001209including ambiguous options, invalid types, invalid options, wrong number of
1210positional arguments, etc. When it encounters such an error, it exits and
1211prints the error along with a usage message::
1212
1213 >>> parser = argparse.ArgumentParser(prog='PROG')
1214 >>> parser.add_argument('--foo', type=int)
1215 >>> parser.add_argument('bar', nargs='?')
1216
1217 >>> # invalid type
1218 >>> parser.parse_args(['--foo', 'spam'])
1219 usage: PROG [-h] [--foo FOO] [bar]
1220 PROG: error: argument --foo: invalid int value: 'spam'
1221
1222 >>> # invalid option
1223 >>> parser.parse_args(['--bar'])
1224 usage: PROG [-h] [--foo FOO] [bar]
1225 PROG: error: no such option: --bar
1226
1227 >>> # wrong number of arguments
1228 >>> parser.parse_args(['spam', 'badger'])
1229 usage: PROG [-h] [--foo FOO] [bar]
1230 PROG: error: extra arguments found: badger
1231
1232
1233Arguments containing ``"-"``
1234^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1235
1236The ``parse_args`` method attempts to give errors whenever the user has clearly
1237made a mistake, but some situations are inherently ambiguous. For example, the
1238command-line arg ``'-1'`` could either be an attempt to specify an option or an
1239attempt to provide a positional argument. The ``parse_args`` method is cautious
1240here: positional arguments may only begin with ``'-'`` if they look like
1241negative numbers and there are no options in the parser that look like negative
1242numbers::
1243
1244 >>> parser = argparse.ArgumentParser(prog='PROG')
1245 >>> parser.add_argument('-x')
1246 >>> parser.add_argument('foo', nargs='?')
1247
1248 >>> # no negative number options, so -1 is a positional argument
1249 >>> parser.parse_args(['-x', '-1'])
1250 Namespace(foo=None, x='-1')
1251
1252 >>> # no negative number options, so -1 and -5 are positional arguments
1253 >>> parser.parse_args(['-x', '-1', '-5'])
1254 Namespace(foo='-5', x='-1')
1255
1256 >>> parser = argparse.ArgumentParser(prog='PROG')
1257 >>> parser.add_argument('-1', dest='one')
1258 >>> parser.add_argument('foo', nargs='?')
1259
1260 >>> # negative number options present, so -1 is an option
1261 >>> parser.parse_args(['-1', 'X'])
1262 Namespace(foo=None, one='X')
1263
1264 >>> # negative number options present, so -2 is an option
1265 >>> parser.parse_args(['-2'])
1266 usage: PROG [-h] [-1 ONE] [foo]
1267 PROG: error: no such option: -2
1268
1269 >>> # negative number options present, so both -1s are options
1270 >>> parser.parse_args(['-1', '-1'])
1271 usage: PROG [-h] [-1 ONE] [foo]
1272 PROG: error: argument -1: expected one argument
1273
1274If you have positional arguments that must begin with ``'-'`` and don't look
1275like negative numbers, you can insert the pseudo-argument ``'--'`` which tells
1276``parse_args`` that everything after that is a positional argument::
1277
1278 >>> parser.parse_args(['--', '-f'])
1279 Namespace(foo='-f', one=None)
1280
1281
1282Argument abbreviations
1283^^^^^^^^^^^^^^^^^^^^^^
1284
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001285The :meth:`parse_args` method allows long options to be abbreviated if the
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001286abbreviation is unambiguous::
1287
1288 >>> parser = argparse.ArgumentParser(prog='PROG')
1289 >>> parser.add_argument('-bacon')
1290 >>> parser.add_argument('-badger')
1291 >>> parser.parse_args('-bac MMM'.split())
1292 Namespace(bacon='MMM', badger=None)
1293 >>> parser.parse_args('-bad WOOD'.split())
1294 Namespace(bacon=None, badger='WOOD')
1295 >>> parser.parse_args('-ba BA'.split())
1296 usage: PROG [-h] [-bacon BACON] [-badger BADGER]
1297 PROG: error: ambiguous option: -ba could match -badger, -bacon
1298
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001299An error is produced for arguments that could produce more than one options.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001300
1301
1302Beyond ``sys.argv``
1303^^^^^^^^^^^^^^^^^^^
1304
1305Sometimes it may be useful to have an ArgumentParser parse args other than those
1306of :data:`sys.argv`. This can be accomplished by passing a list of strings to
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001307``parse_args``. This is useful for testing at the interactive prompt::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001308
1309 >>> parser = argparse.ArgumentParser()
1310 >>> parser.add_argument(
Fred Drakec7eb7892011-03-03 05:29:59 +00001311 ... 'integers', metavar='int', type=int, choices=range(10),
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001312 ... nargs='+', help='an integer in the range 0..9')
1313 >>> parser.add_argument(
1314 ... '--sum', dest='accumulate', action='store_const', const=sum,
1315 ... default=max, help='sum the integers (default: find the max)')
1316 >>> parser.parse_args(['1', '2', '3', '4'])
1317 Namespace(accumulate=<built-in function max>, integers=[1, 2, 3, 4])
1318 >>> parser.parse_args('1 2 3 4 --sum'.split())
1319 Namespace(accumulate=<built-in function sum>, integers=[1, 2, 3, 4])
1320
1321
Steven Bethardd8f2d502011-03-26 19:50:06 +01001322The Namespace object
1323^^^^^^^^^^^^^^^^^^^^
1324
1325By default, :meth:`parse_args` will return a new object of type :class:`Namespace`
1326where the necessary attributes have been set. This class is deliberately simple,
1327just an :class:`object` subclass with a readable string representation. If you
1328prefer to have dict-like view of the attributes, you can use the standard Python
1329idiom via :func:`vars`::
1330
1331 >>> parser = argparse.ArgumentParser()
1332 >>> parser.add_argument('--foo')
1333 >>> args = parser.parse_args(['--foo', 'BAR'])
1334 >>> vars(args)
1335 {'foo': 'BAR'}
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001336
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001337It may also be useful to have an :class:`ArgumentParser` assign attributes to an
Steven Bethardd8f2d502011-03-26 19:50:06 +01001338already existing object, rather than a new :class:`Namespace` object. This can
1339be achieved by specifying the ``namespace=`` keyword argument::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001340
Éric Araujo28053fb2010-11-22 03:09:19 +00001341 >>> class C:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001342 ... pass
1343 ...
1344 >>> c = C()
1345 >>> parser = argparse.ArgumentParser()
1346 >>> parser.add_argument('--foo')
1347 >>> parser.parse_args(args=['--foo', 'BAR'], namespace=c)
1348 >>> c.foo
1349 'BAR'
1350
1351
1352Other utilities
1353---------------
1354
1355Sub-commands
1356^^^^^^^^^^^^
1357
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001358.. method:: ArgumentParser.add_subparsers()
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001359
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001360 Many programs split up their functionality into a number of sub-commands,
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001361 for example, the ``svn`` program can invoke sub-commands like ``svn
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001362 checkout``, ``svn update``, and ``svn commit``. Splitting up functionality
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001363 this way can be a particularly good idea when a program performs several
1364 different functions which require different kinds of command-line arguments.
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001365 :class:`ArgumentParser` supports the creation of such sub-commands with the
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001366 :meth:`add_subparsers` method. The :meth:`add_subparsers` method is normally
1367 called with no arguments and returns an special action object. This object
1368 has a single method, ``add_parser``, which takes a command name and any
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001369 :class:`ArgumentParser` constructor arguments, and returns an
1370 :class:`ArgumentParser` object that can be modified as usual.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001371
1372 Some example usage::
1373
1374 >>> # create the top-level parser
1375 >>> parser = argparse.ArgumentParser(prog='PROG')
1376 >>> parser.add_argument('--foo', action='store_true', help='foo help')
1377 >>> subparsers = parser.add_subparsers(help='sub-command help')
1378 >>>
1379 >>> # create the parser for the "a" command
1380 >>> parser_a = subparsers.add_parser('a', help='a help')
1381 >>> parser_a.add_argument('bar', type=int, help='bar help')
1382 >>>
1383 >>> # create the parser for the "b" command
1384 >>> parser_b = subparsers.add_parser('b', help='b help')
1385 >>> parser_b.add_argument('--baz', choices='XYZ', help='baz help')
1386 >>>
1387 >>> # parse some arg lists
1388 >>> parser.parse_args(['a', '12'])
1389 Namespace(bar=12, foo=False)
1390 >>> parser.parse_args(['--foo', 'b', '--baz', 'Z'])
1391 Namespace(baz='Z', foo=True)
1392
1393 Note that the object returned by :meth:`parse_args` will only contain
1394 attributes for the main parser and the subparser that was selected by the
1395 command line (and not any other subparsers). So in the example above, when
1396 the ``"a"`` command is specified, only the ``foo`` and ``bar`` attributes are
1397 present, and when the ``"b"`` command is specified, only the ``foo`` and
1398 ``baz`` attributes are present.
1399
1400 Similarly, when a help message is requested from a subparser, only the help
1401 for that particular parser will be printed. The help message will not
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001402 include parent parser or sibling parser messages. (A help message for each
1403 subparser command, however, can be given by supplying the ``help=`` argument
1404 to ``add_parser`` as above.)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001405
1406 ::
1407
1408 >>> parser.parse_args(['--help'])
1409 usage: PROG [-h] [--foo] {a,b} ...
1410
1411 positional arguments:
1412 {a,b} sub-command help
1413 a a help
1414 b b help
1415
1416 optional arguments:
1417 -h, --help show this help message and exit
1418 --foo foo help
1419
1420 >>> parser.parse_args(['a', '--help'])
1421 usage: PROG a [-h] bar
1422
1423 positional arguments:
1424 bar bar help
1425
1426 optional arguments:
1427 -h, --help show this help message and exit
1428
1429 >>> parser.parse_args(['b', '--help'])
1430 usage: PROG b [-h] [--baz {X,Y,Z}]
1431
1432 optional arguments:
1433 -h, --help show this help message and exit
1434 --baz {X,Y,Z} baz help
1435
1436 The :meth:`add_subparsers` method also supports ``title`` and ``description``
1437 keyword arguments. When either is present, the subparser's commands will
1438 appear in their own group in the help output. For example::
1439
1440 >>> parser = argparse.ArgumentParser()
1441 >>> subparsers = parser.add_subparsers(title='subcommands',
1442 ... description='valid subcommands',
1443 ... help='additional help')
1444 >>> subparsers.add_parser('foo')
1445 >>> subparsers.add_parser('bar')
1446 >>> parser.parse_args(['-h'])
1447 usage: [-h] {foo,bar} ...
1448
1449 optional arguments:
1450 -h, --help show this help message and exit
1451
1452 subcommands:
1453 valid subcommands
1454
1455 {foo,bar} additional help
1456
Steven Bethardfd311a72010-12-18 11:19:23 +00001457 Furthermore, ``add_parser`` supports an additional ``aliases`` argument,
1458 which allows multiple strings to refer to the same subparser. This example,
1459 like ``svn``, aliases ``co`` as a shorthand for ``checkout``::
1460
1461 >>> parser = argparse.ArgumentParser()
1462 >>> subparsers = parser.add_subparsers()
1463 >>> checkout = subparsers.add_parser('checkout', aliases=['co'])
1464 >>> checkout.add_argument('foo')
1465 >>> parser.parse_args(['co', 'bar'])
1466 Namespace(foo='bar')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001467
1468 One particularly effective way of handling sub-commands is to combine the use
1469 of the :meth:`add_subparsers` method with calls to :meth:`set_defaults` so
1470 that each subparser knows which Python function it should execute. For
1471 example::
1472
1473 >>> # sub-command functions
1474 >>> def foo(args):
Benjamin Petersonb2deb112010-03-03 02:09:18 +00001475 ... print(args.x * args.y)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001476 ...
1477 >>> def bar(args):
Benjamin Petersonb2deb112010-03-03 02:09:18 +00001478 ... print('((%s))' % args.z)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001479 ...
1480 >>> # create the top-level parser
1481 >>> parser = argparse.ArgumentParser()
1482 >>> subparsers = parser.add_subparsers()
1483 >>>
1484 >>> # create the parser for the "foo" command
1485 >>> parser_foo = subparsers.add_parser('foo')
1486 >>> parser_foo.add_argument('-x', type=int, default=1)
1487 >>> parser_foo.add_argument('y', type=float)
1488 >>> parser_foo.set_defaults(func=foo)
1489 >>>
1490 >>> # create the parser for the "bar" command
1491 >>> parser_bar = subparsers.add_parser('bar')
1492 >>> parser_bar.add_argument('z')
1493 >>> parser_bar.set_defaults(func=bar)
1494 >>>
1495 >>> # parse the args and call whatever function was selected
1496 >>> args = parser.parse_args('foo 1 -x 2'.split())
1497 >>> args.func(args)
1498 2.0
1499 >>>
1500 >>> # parse the args and call whatever function was selected
1501 >>> args = parser.parse_args('bar XYZYX'.split())
1502 >>> args.func(args)
1503 ((XYZYX))
1504
Steven Bethardfd311a72010-12-18 11:19:23 +00001505 This way, you can let :meth:`parse_args` do the job of calling the
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001506 appropriate function after argument parsing is complete. Associating
1507 functions with actions like this is typically the easiest way to handle the
1508 different actions for each of your subparsers. However, if it is necessary
1509 to check the name of the subparser that was invoked, the ``dest`` keyword
1510 argument to the :meth:`add_subparsers` call will work::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001511
1512 >>> parser = argparse.ArgumentParser()
1513 >>> subparsers = parser.add_subparsers(dest='subparser_name')
1514 >>> subparser1 = subparsers.add_parser('1')
1515 >>> subparser1.add_argument('-x')
1516 >>> subparser2 = subparsers.add_parser('2')
1517 >>> subparser2.add_argument('y')
1518 >>> parser.parse_args(['2', 'frobble'])
1519 Namespace(subparser_name='2', y='frobble')
1520
1521
1522FileType objects
1523^^^^^^^^^^^^^^^^
1524
1525.. class:: FileType(mode='r', bufsize=None)
1526
1527 The :class:`FileType` factory creates objects that can be passed to the type
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001528 argument of :meth:`ArgumentParser.add_argument`. Arguments that have
1529 :class:`FileType` objects as their type will open command-line args as files
1530 with the requested modes and buffer sizes:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001531
1532 >>> parser = argparse.ArgumentParser()
1533 >>> parser.add_argument('--output', type=argparse.FileType('wb', 0))
1534 >>> parser.parse_args(['--output', 'out'])
Georg Brandl04536b02011-01-09 09:31:01 +00001535 Namespace(output=<_io.BufferedWriter name='out'>)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001536
1537 FileType objects understand the pseudo-argument ``'-'`` and automatically
1538 convert this into ``sys.stdin`` for readable :class:`FileType` objects and
1539 ``sys.stdout`` for writable :class:`FileType` objects:
1540
1541 >>> parser = argparse.ArgumentParser()
1542 >>> parser.add_argument('infile', type=argparse.FileType('r'))
1543 >>> parser.parse_args(['-'])
Georg Brandl04536b02011-01-09 09:31:01 +00001544 Namespace(infile=<_io.TextIOWrapper name='<stdin>' encoding='UTF-8'>)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001545
1546
1547Argument groups
1548^^^^^^^^^^^^^^^
1549
Georg Brandle0bf91d2010-10-17 10:34:28 +00001550.. method:: ArgumentParser.add_argument_group(title=None, description=None)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001551
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001552 By default, :class:`ArgumentParser` groups command-line arguments into
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001553 "positional arguments" and "optional arguments" when displaying help
1554 messages. When there is a better conceptual grouping of arguments than this
1555 default one, appropriate groups can be created using the
1556 :meth:`add_argument_group` method::
1557
1558 >>> parser = argparse.ArgumentParser(prog='PROG', add_help=False)
1559 >>> group = parser.add_argument_group('group')
1560 >>> group.add_argument('--foo', help='foo help')
1561 >>> group.add_argument('bar', help='bar help')
1562 >>> parser.print_help()
1563 usage: PROG [--foo FOO] bar
1564
1565 group:
1566 bar bar help
1567 --foo FOO foo help
1568
1569 The :meth:`add_argument_group` method returns an argument group object which
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001570 has an :meth:`~ArgumentParser.add_argument` method just like a regular
1571 :class:`ArgumentParser`. When an argument is added to the group, the parser
1572 treats it just like a normal argument, but displays the argument in a
1573 separate group for help messages. The :meth:`add_argument_group` method
Georg Brandle0bf91d2010-10-17 10:34:28 +00001574 accepts *title* and *description* arguments which can be used to
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001575 customize this display::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001576
1577 >>> parser = argparse.ArgumentParser(prog='PROG', add_help=False)
1578 >>> group1 = parser.add_argument_group('group1', 'group1 description')
1579 >>> group1.add_argument('foo', help='foo help')
1580 >>> group2 = parser.add_argument_group('group2', 'group2 description')
1581 >>> group2.add_argument('--bar', help='bar help')
1582 >>> parser.print_help()
1583 usage: PROG [--bar BAR] foo
1584
1585 group1:
1586 group1 description
1587
1588 foo foo help
1589
1590 group2:
1591 group2 description
1592
1593 --bar BAR bar help
1594
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001595 Note that any arguments not your user defined groups will end up back in the
1596 usual "positional arguments" and "optional arguments" sections.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001597
1598
1599Mutual exclusion
1600^^^^^^^^^^^^^^^^
1601
Georg Brandle0bf91d2010-10-17 10:34:28 +00001602.. method:: add_mutually_exclusive_group(required=False)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001603
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001604 Create a mutually exclusive group. argparse will make sure that only one of
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001605 the arguments in the mutually exclusive group was present on the command
1606 line::
1607
1608 >>> parser = argparse.ArgumentParser(prog='PROG')
1609 >>> group = parser.add_mutually_exclusive_group()
1610 >>> group.add_argument('--foo', action='store_true')
1611 >>> group.add_argument('--bar', action='store_false')
1612 >>> parser.parse_args(['--foo'])
1613 Namespace(bar=True, foo=True)
1614 >>> parser.parse_args(['--bar'])
1615 Namespace(bar=False, foo=False)
1616 >>> parser.parse_args(['--foo', '--bar'])
1617 usage: PROG [-h] [--foo | --bar]
1618 PROG: error: argument --bar: not allowed with argument --foo
1619
Georg Brandle0bf91d2010-10-17 10:34:28 +00001620 The :meth:`add_mutually_exclusive_group` method also accepts a *required*
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001621 argument, to indicate that at least one of the mutually exclusive arguments
1622 is required::
1623
1624 >>> parser = argparse.ArgumentParser(prog='PROG')
1625 >>> group = parser.add_mutually_exclusive_group(required=True)
1626 >>> group.add_argument('--foo', action='store_true')
1627 >>> group.add_argument('--bar', action='store_false')
1628 >>> parser.parse_args([])
1629 usage: PROG [-h] (--foo | --bar)
1630 PROG: error: one of the arguments --foo --bar is required
1631
1632 Note that currently mutually exclusive argument groups do not support the
Georg Brandle0bf91d2010-10-17 10:34:28 +00001633 *title* and *description* arguments of :meth:`add_argument_group`.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001634
1635
1636Parser defaults
1637^^^^^^^^^^^^^^^
1638
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001639.. method:: ArgumentParser.set_defaults(**kwargs)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001640
1641 Most of the time, the attributes of the object returned by :meth:`parse_args`
1642 will be fully determined by inspecting the command-line args and the argument
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001643 actions. :meth:`ArgumentParser.set_defaults` allows some additional
Georg Brandl1d827ff2011-04-16 16:44:54 +02001644 attributes that are determined without any inspection of the command line to
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001645 be added::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001646
1647 >>> parser = argparse.ArgumentParser()
1648 >>> parser.add_argument('foo', type=int)
1649 >>> parser.set_defaults(bar=42, baz='badger')
1650 >>> parser.parse_args(['736'])
1651 Namespace(bar=42, baz='badger', foo=736)
1652
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001653 Note that parser-level defaults always override argument-level defaults::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001654
1655 >>> parser = argparse.ArgumentParser()
1656 >>> parser.add_argument('--foo', default='bar')
1657 >>> parser.set_defaults(foo='spam')
1658 >>> parser.parse_args([])
1659 Namespace(foo='spam')
1660
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001661 Parser-level defaults can be particularly useful when working with multiple
1662 parsers. See the :meth:`~ArgumentParser.add_subparsers` method for an
1663 example of this type.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001664
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001665.. method:: ArgumentParser.get_default(dest)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001666
1667 Get the default value for a namespace attribute, as set by either
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001668 :meth:`~ArgumentParser.add_argument` or by
1669 :meth:`~ArgumentParser.set_defaults`::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001670
1671 >>> parser = argparse.ArgumentParser()
1672 >>> parser.add_argument('--foo', default='badger')
1673 >>> parser.get_default('foo')
1674 'badger'
1675
1676
1677Printing help
1678^^^^^^^^^^^^^
1679
1680In most typical applications, :meth:`parse_args` will take care of formatting
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001681and printing any usage or error messages. However, several formatting methods
1682are available:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001683
Georg Brandle0bf91d2010-10-17 10:34:28 +00001684.. method:: ArgumentParser.print_usage(file=None)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001685
1686 Print a brief description of how the :class:`ArgumentParser` should be
R. David Murray32e17712010-12-18 16:39:06 +00001687 invoked on the command line. If *file* is ``None``, :data:`sys.stdout` is
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001688 assumed.
1689
Georg Brandle0bf91d2010-10-17 10:34:28 +00001690.. method:: ArgumentParser.print_help(file=None)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001691
1692 Print a help message, including the program usage and information about the
Georg Brandle0bf91d2010-10-17 10:34:28 +00001693 arguments registered with the :class:`ArgumentParser`. If *file* is
R. David Murray32e17712010-12-18 16:39:06 +00001694 ``None``, :data:`sys.stdout` is assumed.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001695
1696There are also variants of these methods that simply return a string instead of
1697printing it:
1698
Georg Brandle0bf91d2010-10-17 10:34:28 +00001699.. method:: ArgumentParser.format_usage()
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001700
1701 Return a string containing a brief description of how the
1702 :class:`ArgumentParser` should be invoked on the command line.
1703
Georg Brandle0bf91d2010-10-17 10:34:28 +00001704.. method:: ArgumentParser.format_help()
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001705
1706 Return a string containing a help message, including the program usage and
1707 information about the arguments registered with the :class:`ArgumentParser`.
1708
1709
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001710Partial parsing
1711^^^^^^^^^^^^^^^
1712
Georg Brandle0bf91d2010-10-17 10:34:28 +00001713.. method:: ArgumentParser.parse_known_args(args=None, namespace=None)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001714
Georg Brandl1d827ff2011-04-16 16:44:54 +02001715Sometimes a script may only parse a few of the command-line arguments, passing
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001716the remaining arguments on to another script or program. In these cases, the
1717:meth:`parse_known_args` method can be useful. It works much like
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001718:meth:`~ArgumentParser.parse_args` except that it does not produce an error when
1719extra arguments are present. Instead, it returns a two item tuple containing
1720the populated namespace and the list of remaining argument strings.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001721
1722::
1723
1724 >>> parser = argparse.ArgumentParser()
1725 >>> parser.add_argument('--foo', action='store_true')
1726 >>> parser.add_argument('bar')
1727 >>> parser.parse_known_args(['--foo', '--badger', 'BAR', 'spam'])
1728 (Namespace(bar='BAR', foo=True), ['--badger', 'spam'])
1729
1730
1731Customizing file parsing
1732^^^^^^^^^^^^^^^^^^^^^^^^
1733
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001734.. method:: ArgumentParser.convert_arg_line_to_args(arg_line)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001735
Georg Brandle0bf91d2010-10-17 10:34:28 +00001736 Arguments that are read from a file (see the *fromfile_prefix_chars*
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001737 keyword argument to the :class:`ArgumentParser` constructor) are read one
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001738 argument per line. :meth:`convert_arg_line_to_args` can be overriden for
1739 fancier reading.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001740
Georg Brandle0bf91d2010-10-17 10:34:28 +00001741 This method takes a single argument *arg_line* which is a string read from
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001742 the argument file. It returns a list of arguments parsed from this string.
1743 The method is called once per line read from the argument file, in order.
1744
1745 A useful override of this method is one that treats each space-separated word
1746 as an argument::
1747
1748 def convert_arg_line_to_args(self, arg_line):
1749 for arg in arg_line.split():
1750 if not arg.strip():
1751 continue
1752 yield arg
1753
1754
Georg Brandl93754922010-10-17 10:28:04 +00001755Exiting methods
1756^^^^^^^^^^^^^^^
1757
1758.. method:: ArgumentParser.exit(status=0, message=None)
1759
1760 This method terminates the program, exiting with the specified *status*
1761 and, if given, it prints a *message* before that.
1762
1763.. method:: ArgumentParser.error(message)
1764
1765 This method prints a usage message including the *message* to the
1766 standard output and terminates the program with a status code of 2.
1767
Raymond Hettinger677e10a2010-12-07 06:45:30 +00001768.. _upgrading-optparse-code:
Georg Brandl93754922010-10-17 10:28:04 +00001769
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001770Upgrading optparse code
1771-----------------------
1772
1773Originally, the argparse module had attempted to maintain compatibility with
1774optparse. However, optparse was difficult to extend transparently, particularly
1775with the changes required to support the new ``nargs=`` specifiers and better
Georg Brandl386bc6d2010-04-25 10:19:53 +00001776usage messages. When most everything in optparse had either been copy-pasted
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001777over or monkey-patched, it no longer seemed practical to try to maintain the
1778backwards compatibility.
1779
1780A partial upgrade path from optparse to argparse:
1781
Georg Brandlc9007082011-01-09 09:04:08 +00001782* Replace all ``add_option()`` calls with :meth:`ArgumentParser.add_argument`
1783 calls.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001784
1785* Replace ``options, args = parser.parse_args()`` with ``args =
Georg Brandlc9007082011-01-09 09:04:08 +00001786 parser.parse_args()`` and add additional :meth:`ArgumentParser.add_argument`
1787 calls for the positional arguments.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001788
1789* Replace callback actions and the ``callback_*`` keyword arguments with
1790 ``type`` or ``action`` arguments.
1791
1792* Replace string names for ``type`` keyword arguments with the corresponding
1793 type objects (e.g. int, float, complex, etc).
1794
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001795* Replace :class:`optparse.Values` with :class:`Namespace` and
1796 :exc:`optparse.OptionError` and :exc:`optparse.OptionValueError` with
1797 :exc:`ArgumentError`.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001798
1799* Replace strings with implicit arguments such as ``%default`` or ``%prog`` with
Ezio Melotticca4ef82011-04-21 15:26:46 +03001800 the standard Python syntax to use dictionaries to format strings, that is,
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001801 ``%(default)s`` and ``%(prog)s``.
Steven Bethard59710962010-05-24 03:21:08 +00001802
1803* Replace the OptionParser constructor ``version`` argument with a call to
1804 ``parser.add_argument('--version', action='version', version='<the version>')``