1:mod:`argparse` --- Parser for command-line options, arguments and sub-commands
2===============================================================================
3
4.. module:: argparse
5   :synopsis: Command-line option and argument parsing library.
6.. moduleauthor:: Steven Bethard <[email protected]>
7.. sectionauthor:: Steven Bethard <[email protected]>
8
9.. versionadded:: 2.7
10
11**Source code:** :source:`Lib/argparse.py`
12
13--------------
14
15.. sidebar:: Tutorial
16
17   This page contains the API reference information. For a more gentle
18   introduction to Python command-line parsing, have a look at the
19   :ref:`argparse tutorial <argparse-tutorial>`.
20
21The :mod:`argparse` module makes it easy to write user-friendly command-line
22interfaces. The program defines what arguments it requires, and :mod:`argparse`
23will figure out how to parse those out of :data:`sys.argv`.  The :mod:`argparse`
24module also automatically generates help and usage messages and issues errors
25when users give the program invalid arguments.
26
27
28Example
29-------
30
31The following code is a Python program that takes a list of integers and
32produces either the sum or the max::
33
34   import argparse
35
36   parser = argparse.ArgumentParser(description='Process some integers.')
37   parser.add_argument('integers', metavar='N', type=int, nargs='+',
38                       help='an integer for the accumulator')
39   parser.add_argument('--sum', dest='accumulate', action='store_const',
40                       const=sum, default=max,
41                       help='sum the integers (default: find the max)')
42
43   args = parser.parse_args()
44   print args.accumulate(args.integers)
45
46Assuming the Python code above is saved into a file called ``prog.py``, it can
47be run at the command line and provides useful help messages:
48
49.. code-block:: shell-session
50
51   $ python prog.py -h
52   usage: prog.py [-h] [--sum] N [N ...]
53
54   Process some integers.
55
56   positional arguments:
57    N           an integer for the accumulator
58
59   optional arguments:
60    -h, --help  show this help message and exit
61    --sum       sum the integers (default: find the max)
62
63When run with the appropriate arguments, it prints either the sum or the max of
64the command-line integers:
65
66.. code-block:: shell-session
67
68   $ python prog.py 1 2 3 4
69   4
70
71   $ python prog.py 1 2 3 4 --sum
72   10
73
74If invalid arguments are passed in, it will issue an error:
75
76.. code-block:: shell-session
77
78   $ python prog.py a b c
79   usage: prog.py [-h] [--sum] N [N ...]
80   prog.py: error: argument N: invalid int value: 'a'
81
82The following sections walk you through this example.
83
84
85Creating a parser
86^^^^^^^^^^^^^^^^^
87
88The first step in using the :mod:`argparse` is creating an
89:class:`ArgumentParser` object::
90
91   >>> parser = argparse.ArgumentParser(description='Process some integers.')
92
93The :class:`ArgumentParser` object will hold all the information necessary to
94parse the command line into Python data types.
95
96
97Adding arguments
98^^^^^^^^^^^^^^^^
99
100Filling an :class:`ArgumentParser` with information about program arguments is
101done by making calls to the :meth:`~ArgumentParser.add_argument` method.
102Generally, these calls tell the :class:`ArgumentParser` how to take the strings
103on the command line and turn them into objects.  This information is stored and
104used when :meth:`~ArgumentParser.parse_args` is called. For example::
105
106   >>> parser.add_argument('integers', metavar='N', type=int, nargs='+',
107   ...                     help='an integer for the accumulator')
108   >>> parser.add_argument('--sum', dest='accumulate', action='store_const',
109   ...                     const=sum, default=max,
110   ...                     help='sum the integers (default: find the max)')
111
112Later, calling :meth:`~ArgumentParser.parse_args` will return an object with
113two attributes, ``integers`` and ``accumulate``.  The ``integers`` attribute
114will be a list of one or more ints, and the ``accumulate`` attribute will be
115either the :func:`sum` function, if ``--sum`` was specified at the command line,
116or the :func:`max` function if it was not.
117
118
119Parsing arguments
120^^^^^^^^^^^^^^^^^
121
122:class:`ArgumentParser` parses arguments through the
123:meth:`~ArgumentParser.parse_args` method.  This will inspect the command line,
124convert each argument to the appropriate type and then invoke the appropriate action.
125In most cases, this means a simple :class:`Namespace` object will be built up from
126attributes parsed out of the command line::
127
128   >>> parser.parse_args(['--sum', '7', '-1', '42'])
129   Namespace(accumulate=<built-in function sum>, integers=[7, -1, 42])
130
131In a script, :meth:`~ArgumentParser.parse_args` will typically be called with no
132arguments, and the :class:`ArgumentParser` will automatically determine the
133command-line arguments from :data:`sys.argv`.
134
135
136ArgumentParser objects
137----------------------
138
139.. class:: ArgumentParser(prog=None, usage=None, description=None, \
140                          epilog=None, parents=[], \
141                          formatter_class=argparse.HelpFormatter, \
142                          prefix_chars='-', fromfile_prefix_chars=None, \
143                          argument_default=None, conflict_handler='error', \
144                          add_help=True)
145
146   Create a new :class:`ArgumentParser` object. All parameters should be passed
147   as keyword arguments. Each parameter has its own more detailed description
148   below, but in short they are:
149
150   * prog_ - The name of the program (default: ``sys.argv[0]``)
151
152   * usage_ - The string describing the program usage (default: generated from
153     arguments added to parser)
154
155   * description_ - Text to display before the argument help (default: none)
156
157   * epilog_ - Text to display after the argument help (default: none)
158
159   * parents_ - A list of :class:`ArgumentParser` objects whose arguments should
160     also be included
161
162   * formatter_class_ - A class for customizing the help output
163
164   * prefix_chars_ - The set of characters that prefix optional arguments
165     (default: '-')
166
167   * fromfile_prefix_chars_ - The set of characters that prefix files from
168     which additional arguments should be read (default: ``None``)
169
170   * argument_default_ - The global default value for arguments
171     (default: ``None``)
172
173   * conflict_handler_ - The strategy for resolving conflicting optionals
174     (usually unnecessary)
175
176   * add_help_ - Add a ``-h/--help`` option to the parser (default: ``True``)
177
178The following sections describe how each of these are used.
179
180
181prog
182^^^^
183
184By default, :class:`ArgumentParser` objects use ``sys.argv[0]`` to determine
185how to display the name of the program in help messages.  This default is almost
186always desirable because it will make the help messages match how the program was
187invoked on the command line.  For example, consider a file named
188``myprogram.py`` with the following code::
189
190   import argparse
191   parser = argparse.ArgumentParser()
192   parser.add_argument('--foo', help='foo help')
193   args = parser.parse_args()
194
195The help for this program will display ``myprogram.py`` as the program name
196(regardless of where the program was invoked from):
197
198.. code-block:: shell-session
199
200   $ python myprogram.py --help
201   usage: myprogram.py [-h] [--foo FOO]
202
203   optional arguments:
204    -h, --help  show this help message and exit
205    --foo FOO   foo help
206   $ cd ..
207   $ python subdir/myprogram.py --help
208   usage: myprogram.py [-h] [--foo FOO]
209
210   optional arguments:
211    -h, --help  show this help message and exit
212    --foo FOO   foo help
213
214To change this default behavior, another value can be supplied using the
215``prog=`` argument to :class:`ArgumentParser`::
216
217   >>> parser = argparse.ArgumentParser(prog='myprogram')
218   >>> parser.print_help()
219   usage: myprogram [-h]
220
221   optional arguments:
222    -h, --help  show this help message and exit
223
224Note that the program name, whether determined from ``sys.argv[0]`` or from the
225``prog=`` argument, is available to help messages using the ``%(prog)s`` format
226specifier.
227
228::
229
230   >>> parser = argparse.ArgumentParser(prog='myprogram')
231   >>> parser.add_argument('--foo', help='foo of the %(prog)s program')
232   >>> parser.print_help()
233   usage: myprogram [-h] [--foo FOO]
234
235   optional arguments:
236    -h, --help  show this help message and exit
237    --foo FOO   foo of the myprogram program
238
239
240usage
241^^^^^
242
243By default, :class:`ArgumentParser` calculates the usage message from the
244arguments it contains::
245
246   >>> parser = argparse.ArgumentParser(prog='PROG')
247   >>> parser.add_argument('--foo', nargs='?', help='foo help')
248   >>> parser.add_argument('bar', nargs='+', help='bar help')
249   >>> parser.print_help()
250   usage: PROG [-h] [--foo [FOO]] bar [bar ...]
251
252   positional arguments:
253    bar          bar help
254
255   optional arguments:
256    -h, --help   show this help message and exit
257    --foo [FOO]  foo help
258
259The default message can be overridden with the ``usage=`` keyword argument::
260
261   >>> parser = argparse.ArgumentParser(prog='PROG', usage='%(prog)s [options]')
262   >>> parser.add_argument('--foo', nargs='?', help='foo help')
263   >>> parser.add_argument('bar', nargs='+', help='bar help')
264   >>> parser.print_help()
265   usage: PROG [options]
266
267   positional arguments:
268    bar          bar help
269
270   optional arguments:
271    -h, --help   show this help message and exit
272    --foo [FOO]  foo help
273
274The ``%(prog)s`` format specifier is available to fill in the program name in
275your usage messages.
276
277
278description
279^^^^^^^^^^^
280
281Most calls to the :class:`ArgumentParser` constructor will use the
282``description=`` keyword argument.  This argument gives a brief description of
283what the program does and how it works.  In help messages, the description is
284displayed between the command-line usage string and the help messages for the
285various arguments::
286
287   >>> parser = argparse.ArgumentParser(description='A foo that bars')
288   >>> parser.print_help()
289   usage: argparse.py [-h]
290
291   A foo that bars
292
293   optional arguments:
294    -h, --help  show this help message and exit
295
296By default, the description will be line-wrapped so that it fits within the
297given space.  To change this behavior, see the formatter_class_ argument.
298
299
300epilog
301^^^^^^
302
303Some programs like to display additional description of the program after the
304description of the arguments.  Such text can be specified using the ``epilog=``
305argument to :class:`ArgumentParser`::
306
307   >>> parser = argparse.ArgumentParser(
308   ...     description='A foo that bars',
309   ...     epilog="And that's how you'd foo a bar")
310   >>> parser.print_help()
311   usage: argparse.py [-h]
312
313   A foo that bars
314
315   optional arguments:
316    -h, --help  show this help message and exit
317
318   And that's how you'd foo a bar
319
320As with the description_ argument, the ``epilog=`` text is by default
321line-wrapped, but this behavior can be adjusted with the formatter_class_
322argument to :class:`ArgumentParser`.
323
324
325parents
326^^^^^^^
327
328Sometimes, several parsers share a common set of arguments. Rather than
329repeating the definitions of these arguments, a single parser with all the
330shared arguments and passed to ``parents=`` argument to :class:`ArgumentParser`
331can be used.  The ``parents=`` argument takes a list of :class:`ArgumentParser`
332objects, collects all the positional and optional actions from them, and adds
333these actions to the :class:`ArgumentParser` object being constructed::
334
335   >>> parent_parser = argparse.ArgumentParser(add_help=False)
336   >>> parent_parser.add_argument('--parent', type=int)
337
338   >>> foo_parser = argparse.ArgumentParser(parents=[parent_parser])
339   >>> foo_parser.add_argument('foo')
340   >>> foo_parser.parse_args(['--parent', '2', 'XXX'])
341   Namespace(foo='XXX', parent=2)
342
343   >>> bar_parser = argparse.ArgumentParser(parents=[parent_parser])
344   >>> bar_parser.add_argument('--bar')
345   >>> bar_parser.parse_args(['--bar', 'YYY'])
346   Namespace(bar='YYY', parent=None)
347
348Note that most parent parsers will specify ``add_help=False``.  Otherwise, the
349:class:`ArgumentParser` will see two ``-h/--help`` options (one in the parent
350and one in the child) and raise an error.
351
352.. note::
353   You must fully initialize the parsers before passing them via ``parents=``.
354   If you change the parent parsers after the child parser, those changes will
355   not be reflected in the child.
356
357
358formatter_class
359^^^^^^^^^^^^^^^
360
361:class:`ArgumentParser` objects allow the help formatting to be customized by
362specifying an alternate formatting class.  Currently, there are three such
363classes:
364
365.. class:: RawDescriptionHelpFormatter
366           RawTextHelpFormatter
367           ArgumentDefaultsHelpFormatter
368
369The first two allow more control over how textual descriptions are displayed,
370while the last automatically adds information about argument default values.
371
372By default, :class:`ArgumentParser` objects line-wrap the description_ and
373epilog_ texts in command-line help messages::
374
375   >>> parser = argparse.ArgumentParser(
376   ...     prog='PROG',
377   ...     description='''this description
378   ...         was indented weird
379   ...             but that is okay''',
380   ...     epilog='''
381   ...             likewise for this epilog whose whitespace will
382   ...         be cleaned up and whose words will be wrapped
383   ...         across a couple lines''')
384   >>> parser.print_help()
385   usage: PROG [-h]
386
387   this description was indented weird but that is okay
388
389   optional arguments:
390    -h, --help  show this help message and exit
391
392   likewise for this epilog whose whitespace will be cleaned up and whose words
393   will be wrapped across a couple lines
394
395Passing :class:`RawDescriptionHelpFormatter` as ``formatter_class=``
396indicates that description_ and epilog_ are already correctly formatted and
397should not be line-wrapped::
398
399   >>> parser = argparse.ArgumentParser(
400   ...     prog='PROG',
401   ...     formatter_class=argparse.RawDescriptionHelpFormatter,
402   ...     description=textwrap.dedent('''\
403   ...         Please do not mess up this text!
404   ...         --------------------------------
405   ...             I have indented it
406   ...             exactly the way
407   ...             I want it
408   ...         '''))
409   >>> parser.print_help()
410   usage: PROG [-h]
411
412   Please do not mess up this text!
413   --------------------------------
414      I have indented it
415      exactly the way
416      I want it
417
418   optional arguments:
419    -h, --help  show this help message and exit
420
421:class:`RawTextHelpFormatter` maintains whitespace for all sorts of help text,
422including argument descriptions. However, multiple new lines are replaced with
423one. If you wish to preserve multiple blank lines, add spaces between the
424newlines.
425
426The other formatter class available, :class:`ArgumentDefaultsHelpFormatter`,
427will add information about the default value of each of the arguments::
428
429   >>> parser = argparse.ArgumentParser(
430   ...     prog='PROG',
431   ...     formatter_class=argparse.ArgumentDefaultsHelpFormatter)
432   >>> parser.add_argument('--foo', type=int, default=42, help='FOO!')
433   >>> parser.add_argument('bar', nargs='*', default=[1, 2, 3], help='BAR!')
434   >>> parser.print_help()
435   usage: PROG [-h] [--foo FOO] [bar [bar ...]]
436
437   positional arguments:
438    bar         BAR! (default: [1, 2, 3])
439
440   optional arguments:
441    -h, --help  show this help message and exit
442    --foo FOO   FOO! (default: 42)
443
444
445prefix_chars
446^^^^^^^^^^^^
447
448Most command-line options will use ``-`` as the prefix, e.g. ``-f/--foo``.
449Parsers that need to support different or additional prefix
450characters, e.g. for options
451like ``+f`` or ``/foo``, may specify them using the ``prefix_chars=`` argument
452to the ArgumentParser constructor::
453
454   >>> parser = argparse.ArgumentParser(prog='PROG', prefix_chars='-+')
455   >>> parser.add_argument('+f')
456   >>> parser.add_argument('++bar')
457   >>> parser.parse_args('+f X ++bar Y'.split())
458   Namespace(bar='Y', f='X')
459
460The ``prefix_chars=`` argument defaults to ``'-'``. Supplying a set of
461characters that does not include ``-`` will cause ``-f/--foo`` options to be
462disallowed.
463
464
465fromfile_prefix_chars
466^^^^^^^^^^^^^^^^^^^^^
467
468Sometimes, for example when dealing with a particularly long argument lists, it
469may make sense to keep the list of arguments in a file rather than typing it out
470at the command line.  If the ``fromfile_prefix_chars=`` argument is given to the
471:class:`ArgumentParser` constructor, then arguments that start with any of the
472specified characters will be treated as files, and will be replaced by the
473arguments they contain.  For example::
474
475   >>> with open('args.txt', 'w') as fp:
476   ...     fp.write('-f\nbar')
477   >>> parser = argparse.ArgumentParser(fromfile_prefix_chars='@')
478   >>> parser.add_argument('-f')
479   >>> parser.parse_args(['-f', 'foo', '@args.txt'])
480   Namespace(f='bar')
481
482Arguments read from a file must by default be one per line (but see also
483:meth:`~ArgumentParser.convert_arg_line_to_args`) and are treated as if they
484were in the same place as the original file referencing argument on the command
485line.  So in the example above, the expression ``['-f', 'foo', '@args.txt']``
486is considered equivalent to the expression ``['-f', 'foo', '-f', 'bar']``.
487
488The ``fromfile_prefix_chars=`` argument defaults to ``None``, meaning that
489arguments will never be treated as file references.
490
491
492argument_default
493^^^^^^^^^^^^^^^^
494
495Generally, argument defaults are specified either by passing a default to
496:meth:`~ArgumentParser.add_argument` or by calling the
497:meth:`~ArgumentParser.set_defaults` methods with a specific set of name-value
498pairs.  Sometimes however, it may be useful to specify a single parser-wide
499default for arguments.  This can be accomplished by passing the
500``argument_default=`` keyword argument to :class:`ArgumentParser`.  For example,
501to globally suppress attribute creation on :meth:`~ArgumentParser.parse_args`
502calls, we supply ``argument_default=SUPPRESS``::
503
504   >>> parser = argparse.ArgumentParser(argument_default=argparse.SUPPRESS)
505   >>> parser.add_argument('--foo')
506   >>> parser.add_argument('bar', nargs='?')
507   >>> parser.parse_args(['--foo', '1', 'BAR'])
508   Namespace(bar='BAR', foo='1')
509   >>> parser.parse_args([])
510   Namespace()
511
512
513conflict_handler
514^^^^^^^^^^^^^^^^
515
516:class:`ArgumentParser` objects do not allow two actions with the same option
517string.  By default, :class:`ArgumentParser` objects raise an exception if an
518attempt is made to create an argument with an option string that is already in
519use::
520
521   >>> parser = argparse.ArgumentParser(prog='PROG')
522   >>> parser.add_argument('-f', '--foo', help='old foo help')
523   >>> parser.add_argument('--foo', help='new foo help')
524   Traceback (most recent call last):
525    ..
526   ArgumentError: argument --foo: conflicting option string(s): --foo
527
528Sometimes (e.g. when using parents_) it may be useful to simply override any
529older arguments with the same option string.  To get this behavior, the value
530``'resolve'`` can be supplied to the ``conflict_handler=`` argument of
531:class:`ArgumentParser`::
532
533   >>> parser = argparse.ArgumentParser(prog='PROG', conflict_handler='resolve')
534   >>> parser.add_argument('-f', '--foo', help='old foo help')
535   >>> parser.add_argument('--foo', help='new foo help')
536   >>> parser.print_help()
537   usage: PROG [-h] [-f FOO] [--foo FOO]
538
539   optional arguments:
540    -h, --help  show this help message and exit
541    -f FOO      old foo help
542    --foo FOO   new foo help
543
544Note that :class:`ArgumentParser` objects only remove an action if all of its
545option strings are overridden.  So, in the example above, the old ``-f/--foo``
546action is retained as the ``-f`` action, because only the ``--foo`` option
547string was overridden.
548
549
550add_help
551^^^^^^^^
552
553By default, ArgumentParser objects add an option which simply displays
554the parser's help message. For example, consider a file named
555``myprogram.py`` containing the following code::
556
557   import argparse
558   parser = argparse.ArgumentParser()
559   parser.add_argument('--foo', help='foo help')
560   args = parser.parse_args()
561
562If ``-h`` or ``--help`` is supplied at the command line, the ArgumentParser
563help will be printed:
564
565.. code-block:: shell-session
566
567   $ python myprogram.py --help
568   usage: myprogram.py [-h] [--foo FOO]
569
570   optional arguments:
571    -h, --help  show this help message and exit
572    --foo FOO   foo help
573
574Occasionally, it may be useful to disable the addition of this help option.
575This can be achieved by passing ``False`` as the ``add_help=`` argument to
576:class:`ArgumentParser`::
577
578   >>> parser = argparse.ArgumentParser(prog='PROG', add_help=False)
579   >>> parser.add_argument('--foo', help='foo help')
580   >>> parser.print_help()
581   usage: PROG [--foo FOO]
582
583   optional arguments:
584    --foo FOO  foo help
585
586The help option is typically ``-h/--help``. The exception to this is
587if the ``prefix_chars=`` is specified and does not include ``-``, in
588which case ``-h`` and ``--help`` are not valid options.  In
589this case, the first character in ``prefix_chars`` is used to prefix
590the help options::
591
592   >>> parser = argparse.ArgumentParser(prog='PROG', prefix_chars='+/')
593   >>> parser.print_help()
594   usage: PROG [+h]
595
596   optional arguments:
597     +h, ++help  show this help message and exit
598
599
600The add_argument() method
601-------------------------
602
603.. method:: ArgumentParser.add_argument(name or flags..., [action], [nargs], \
604                           [const], [default], [type], [choices], [required], \
605                           [help], [metavar], [dest])
606
607   Define how a single command-line argument should be parsed.  Each parameter
608   has its own more detailed description below, but in short they are:
609
610   * `name or flags`_ - Either a name or a list of option strings, e.g. ``foo``
611     or ``-f, --foo``.
612
613   * action_ - The basic type of action to be taken when this argument is
614     encountered at the command line.
615
616   * nargs_ - The number of command-line arguments that should be consumed.
617
618   * const_ - A constant value required by some action_ and nargs_ selections.
619
620   * default_ - The value produced if the argument is absent from the
621     command line.
622
623   * type_ - The type to which the command-line argument should be converted.
624
625   * choices_ - A container of the allowable values for the argument.
626
627   * required_ - Whether or not the command-line option may be omitted
628     (optionals only).
629
630   * help_ - A brief description of what the argument does.
631
632   * metavar_ - A name for the argument in usage messages.
633
634   * dest_ - The name of the attribute to be added to the object returned by
635     :meth:`parse_args`.
636
637The following sections describe how each of these are used.
638
639
640name or flags
641^^^^^^^^^^^^^
642
643The :meth:`~ArgumentParser.add_argument` method must know whether an optional
644argument, like ``-f`` or ``--foo``, or a positional argument, like a list of
645filenames, is expected.  The first arguments passed to
646:meth:`~ArgumentParser.add_argument` must therefore be either a series of
647flags, or a simple argument name.  For example, an optional argument could
648be created like::
649
650   >>> parser.add_argument('-f', '--foo')
651
652while a positional argument could be created like::
653
654   >>> parser.add_argument('bar')
655
656When :meth:`~ArgumentParser.parse_args` is called, optional arguments will be
657identified by the ``-`` prefix, and the remaining arguments will be assumed to
658be positional::
659
660   >>> parser = argparse.ArgumentParser(prog='PROG')
661   >>> parser.add_argument('-f', '--foo')
662   >>> parser.add_argument('bar')
663   >>> parser.parse_args(['BAR'])
664   Namespace(bar='BAR', foo=None)
665   >>> parser.parse_args(['BAR', '--foo', 'FOO'])
666   Namespace(bar='BAR', foo='FOO')
667   >>> parser.parse_args(['--foo', 'FOO'])
668   usage: PROG [-h] [-f FOO] bar
669   PROG: error: too few arguments
670
671
672action
673^^^^^^
674
675:class:`ArgumentParser` objects associate command-line arguments with actions.  These
676actions can do just about anything with the command-line arguments associated with
677them, though most actions simply add an attribute to the object returned by
678:meth:`~ArgumentParser.parse_args`.  The ``action`` keyword argument specifies
679how the command-line arguments should be handled. The supplied actions are:
680
681* ``'store'`` - This just stores the argument's value.  This is the default
682  action. For example::
683
684    >>> parser = argparse.ArgumentParser()
685    >>> parser.add_argument('--foo')
686    >>> parser.parse_args('--foo 1'.split())
687    Namespace(foo='1')
688
689* ``'store_const'`` - This stores the value specified by the const_ keyword
690  argument.  The ``'store_const'`` action is most commonly used with
691  optional arguments that specify some sort of flag.  For example::
692
693    >>> parser = argparse.ArgumentParser()
694    >>> parser.add_argument('--foo', action='store_const', const=42)
695    >>> parser.parse_args(['--foo'])
696    Namespace(foo=42)
697
698* ``'store_true'`` and ``'store_false'`` - These are special cases of
699  ``'store_const'`` using for storing the values ``True`` and ``False``
700  respectively.  In addition, they create default values of ``False`` and ``True``
701  respectively.  For example::
702
703    >>> parser = argparse.ArgumentParser()
704    >>> parser.add_argument('--foo', action='store_true')
705    >>> parser.add_argument('--bar', action='store_false')
706    >>> parser.add_argument('--baz', action='store_false')
707    >>> parser.parse_args('--foo --bar'.split())
708    Namespace(bar=False, baz=True, foo=True)
709
710* ``'append'`` - This stores a list, and appends each argument value to the
711  list.  This is useful to allow an option to be specified multiple times.
712  Example usage::
713
714    >>> parser = argparse.ArgumentParser()
715    >>> parser.add_argument('--foo', action='append')
716    >>> parser.parse_args('--foo 1 --foo 2'.split())
717    Namespace(foo=['1', '2'])
718
719* ``'append_const'`` - This stores a list, and appends the value specified by
720  the const_ keyword argument to the list.  (Note that the const_ keyword
721  argument defaults to ``None``.)  The ``'append_const'`` action is typically
722  useful when multiple arguments need to store constants to the same list. For
723  example::
724
725    >>> parser = argparse.ArgumentParser()
726    >>> parser.add_argument('--str', dest='types', action='append_const', const=str)
727    >>> parser.add_argument('--int', dest='types', action='append_const', const=int)
728    >>> parser.parse_args('--str --int'.split())
729    Namespace(types=[<type 'str'>, <type 'int'>])
730
731* ``'count'`` - This counts the number of times a keyword argument occurs. For
732  example, this is useful for increasing verbosity levels::
733
734    >>> parser = argparse.ArgumentParser()
735    >>> parser.add_argument('--verbose', '-v', action='count')
736    >>> parser.parse_args(['-vvv'])
737    Namespace(verbose=3)
738
739* ``'help'`` - This prints a complete help message for all the options in the
740  current parser and then exits. By default a help action is automatically
741  added to the parser. See :class:`ArgumentParser` for details of how the
742  output is created.
743
744* ``'version'`` - This expects a ``version=`` keyword argument in the
745  :meth:`~ArgumentParser.add_argument` call, and prints version information
746  and exits when invoked::
747
748    >>> import argparse
749    >>> parser = argparse.ArgumentParser(prog='PROG')
750    >>> parser.add_argument('--version', action='version', version='%(prog)s 2.0')
751    >>> parser.parse_args(['--version'])
752    PROG 2.0
753
754You may also specify an arbitrary action by passing an Action subclass or
755other object that implements the same interface.  The recommended way to do
756this is to extend :class:`Action`, overriding the ``__call__`` method
757and optionally the ``__init__`` method.
758
759An example of a custom action::
760
761   >>> class FooAction(argparse.Action):
762   ...     def __init__(self, option_strings, dest, nargs=None, **kwargs):
763   ...         if nargs is not None:
764   ...             raise ValueError("nargs not allowed")
765   ...         super(FooAction, self).__init__(option_strings, dest, **kwargs)
766   ...     def __call__(self, parser, namespace, values, option_string=None):
767   ...         print '%r %r %r' % (namespace, values, option_string)
768   ...         setattr(namespace, self.dest, values)
769   ...
770   >>> parser = argparse.ArgumentParser()
771   >>> parser.add_argument('--foo', action=FooAction)
772   >>> parser.add_argument('bar', action=FooAction)
773   >>> args = parser.parse_args('1 --foo 2'.split())
774   Namespace(bar=None, foo=None) '1' None
775   Namespace(bar='1', foo=None) '2' '--foo'
776   >>> args
777   Namespace(bar='1', foo='2')
778
779For more details, see :class:`Action`.
780
781nargs
782^^^^^
783
784ArgumentParser objects usually associate a single command-line argument with a
785single action to be taken.  The ``nargs`` keyword argument associates a
786different number of command-line arguments with a single action.  The supported
787values are:
788
789* ``N`` (an integer).  ``N`` arguments from the command line will be gathered
790  together into a list.  For example::
791
792     >>> parser = argparse.ArgumentParser()
793     >>> parser.add_argument('--foo', nargs=2)
794     >>> parser.add_argument('bar', nargs=1)
795     >>> parser.parse_args('c --foo a b'.split())
796     Namespace(bar=['c'], foo=['a', 'b'])
797
798  Note that ``nargs=1`` produces a list of one item.  This is different from
799  the default, in which the item is produced by itself.
800
801* ``'?'``. One argument will be consumed from the command line if possible, and
802  produced as a single item.  If no command-line argument is present, the value from
803  default_ will be produced.  Note that for optional arguments, there is an
804  additional case - the option string is present but not followed by a
805  command-line argument.  In this case the value from const_ will be produced.  Some
806  examples to illustrate this::
807
808     >>> parser = argparse.ArgumentParser()
809     >>> parser.add_argument('--foo', nargs='?', const='c', default='d')
810     >>> parser.add_argument('bar', nargs='?', default='d')
811     >>> parser.parse_args(['XX', '--foo', 'YY'])
812     Namespace(bar='XX', foo='YY')
813     >>> parser.parse_args(['XX', '--foo'])
814     Namespace(bar='XX', foo='c')
815     >>> parser.parse_args([])
816     Namespace(bar='d', foo='d')
817
818  One of the more common uses of ``nargs='?'`` is to allow optional input and
819  output files::
820
821     >>> parser = argparse.ArgumentParser()
822     >>> parser.add_argument('infile', nargs='?', type=argparse.FileType('r'),
823     ...                     default=sys.stdin)
824     >>> parser.add_argument('outfile', nargs='?', type=argparse.FileType('w'),
825     ...                     default=sys.stdout)
826     >>> parser.parse_args(['input.txt', 'output.txt'])
827     Namespace(infile=<open file 'input.txt', mode 'r' at 0x...>,
828               outfile=<open file 'output.txt', mode 'w' at 0x...>)
829     >>> parser.parse_args([])
830     Namespace(infile=<open file '<stdin>', mode 'r' at 0x...>,
831               outfile=<open file '<stdout>', mode 'w' at 0x...>)
832
833* ``'*'``.  All command-line arguments present are gathered into a list.  Note that
834  it generally doesn't make much sense to have more than one positional argument
835  with ``nargs='*'``, but multiple optional arguments with ``nargs='*'`` is
836  possible.  For example::
837
838     >>> parser = argparse.ArgumentParser()
839     >>> parser.add_argument('--foo', nargs='*')
840     >>> parser.add_argument('--bar', nargs='*')
841     >>> parser.add_argument('baz', nargs='*')
842     >>> parser.parse_args('a b --foo x y --bar 1 2'.split())
843     Namespace(bar=['1', '2'], baz=['a', 'b'], foo=['x', 'y'])
844
845* ``'+'``. Just like ``'*'``, all command-line args present are gathered into a
846  list.  Additionally, an error message will be generated if there wasn't at
847  least one command-line argument present.  For example::
848
849     >>> parser = argparse.ArgumentParser(prog='PROG')
850     >>> parser.add_argument('foo', nargs='+')
851     >>> parser.parse_args(['a', 'b'])
852     Namespace(foo=['a', 'b'])
853     >>> parser.parse_args([])
854     usage: PROG [-h] foo [foo ...]
855     PROG: error: too few arguments
856
857.. _`argparse.REMAINDER`:
858
859* ``argparse.REMAINDER``.  All the remaining command-line arguments are gathered
860  into a list.  This is commonly useful for command line utilities that dispatch
861  to other command line utilities::
862
863     >>> parser = argparse.ArgumentParser(prog='PROG')
864     >>> parser.add_argument('--foo')
865     >>> parser.add_argument('command')
866     >>> parser.add_argument('args', nargs=argparse.REMAINDER)
867     >>> print parser.parse_args('--foo B cmd --arg1 XX ZZ'.split())
868     Namespace(args=['--arg1', 'XX', 'ZZ'], command='cmd', foo='B')
869
870If the ``nargs`` keyword argument is not provided, the number of arguments consumed
871is determined by the action_.  Generally this means a single command-line argument
872will be consumed and a single item (not a list) will be produced.
873
874
875const
876^^^^^
877
878The ``const`` argument of :meth:`~ArgumentParser.add_argument` is used to hold
879constant values that are not read from the command line but are required for
880the various :class:`ArgumentParser` actions.  The two most common uses of it are:
881
882* When :meth:`~ArgumentParser.add_argument` is called with
883  ``action='store_const'`` or ``action='append_const'``.  These actions add the
884  ``const`` value to one of the attributes of the object returned by
885  :meth:`~ArgumentParser.parse_args`. See the action_ description for examples.
886
887* When :meth:`~ArgumentParser.add_argument` is called with option strings
888  (like ``-f`` or ``--foo``) and ``nargs='?'``.  This creates an optional
889  argument that can be followed by zero or one command-line arguments.
890  When parsing the command line, if the option string is encountered with no
891  command-line argument following it, the value of ``const`` will be assumed instead.
892  See the nargs_ description for examples.
893
894With the ``'store_const'`` and ``'append_const'`` actions, the ``const``
895keyword argument must be given.  For other actions, it defaults to ``None``.
896
897
898default
899^^^^^^^
900
901All optional arguments and some positional arguments may be omitted at the
902command line.  The ``default`` keyword argument of
903:meth:`~ArgumentParser.add_argument`, whose value defaults to ``None``,
904specifies what value should be used if the command-line argument is not present.
905For optional arguments, the ``default`` value is used when the option string
906was not present at the command line::
907
908   >>> parser = argparse.ArgumentParser()
909   >>> parser.add_argument('--foo', default=42)
910   >>> parser.parse_args(['--foo', '2'])
911   Namespace(foo='2')
912   >>> parser.parse_args([])
913   Namespace(foo=42)
914
915If the ``default`` value is a string, the parser parses the value as if it
916were a command-line argument.  In particular, the parser applies any type_
917conversion argument, if provided, before setting the attribute on the
918:class:`Namespace` return value.  Otherwise, the parser uses the value as is::
919
920   >>> parser = argparse.ArgumentParser()
921   >>> parser.add_argument('--length', default='10', type=int)
922   >>> parser.add_argument('--width', default=10.5, type=int)
923   >>> parser.parse_args()
924   Namespace(length=10, width=10.5)
925
926For positional arguments with nargs_ equal to ``?`` or ``*``, the ``default`` value
927is used when no command-line argument was present::
928
929   >>> parser = argparse.ArgumentParser()
930   >>> parser.add_argument('foo', nargs='?', default=42)
931   >>> parser.parse_args(['a'])
932   Namespace(foo='a')
933   >>> parser.parse_args([])
934   Namespace(foo=42)
935
936
937Providing ``default=argparse.SUPPRESS`` causes no attribute to be added if the
938command-line argument was not present.::
939
940   >>> parser = argparse.ArgumentParser()
941   >>> parser.add_argument('--foo', default=argparse.SUPPRESS)
942   >>> parser.parse_args([])
943   Namespace()
944   >>> parser.parse_args(['--foo', '1'])
945   Namespace(foo='1')
946
947
948type
949^^^^
950
951By default, :class:`ArgumentParser` objects read command-line arguments in as simple
952strings. However, quite often the command-line string should instead be
953interpreted as another type, like a :class:`float` or :class:`int`.  The
954``type`` keyword argument of :meth:`~ArgumentParser.add_argument` allows any
955necessary type-checking and type conversions to be performed.  Common built-in
956types and functions can be used directly as the value of the ``type`` argument::
957
958   >>> parser = argparse.ArgumentParser()
959   >>> parser.add_argument('foo', type=int)
960   >>> parser.add_argument('bar', type=file)
961   >>> parser.parse_args('2 temp.txt'.split())
962   Namespace(bar=<open file 'temp.txt', mode 'r' at 0x...>, foo=2)
963
964See the section on the default_ keyword argument for information on when the
965``type`` argument is applied to default arguments.
966
967To ease the use of various types of files, the argparse module provides the
968factory FileType which takes the ``mode=`` and ``bufsize=`` arguments of the
969``file`` object.  For example, ``FileType('w')`` can be used to create a
970writable file::
971
972   >>> parser = argparse.ArgumentParser()
973   >>> parser.add_argument('bar', type=argparse.FileType('w'))
974   >>> parser.parse_args(['out.txt'])
975   Namespace(bar=<open file 'out.txt', mode 'w' at 0x...>)
976
977``type=`` can take any callable that takes a single string argument and returns
978the converted value::
979
980   >>> def perfect_square(string):
981   ...     value = int(string)
982   ...     sqrt = math.sqrt(value)
983   ...     if sqrt != int(sqrt):
984   ...         msg = "%r is not a perfect square" % string
985   ...         raise argparse.ArgumentTypeError(msg)
986   ...     return value
987   ...
988   >>> parser = argparse.ArgumentParser(prog='PROG')
989   >>> parser.add_argument('foo', type=perfect_square)
990   >>> parser.parse_args(['9'])
991   Namespace(foo=9)
992   >>> parser.parse_args(['7'])
993   usage: PROG [-h] foo
994   PROG: error: argument foo: '7' is not a perfect square
995
996The choices_ keyword argument may be more convenient for type checkers that
997simply check against a range of values::
998
999   >>> parser = argparse.ArgumentParser(prog='PROG')
1000   >>> parser.add_argument('foo', type=int, choices=xrange(5, 10))
1001   >>> parser.parse_args(['7'])
1002   Namespace(foo=7)
1003   >>> parser.parse_args(['11'])
1004   usage: PROG [-h] {5,6,7,8,9}
1005   PROG: error: argument foo: invalid choice: 11 (choose from 5, 6, 7, 8, 9)
1006
1007See the choices_ section for more details.
1008
1009
1010choices
1011^^^^^^^
1012
1013Some command-line arguments should be selected from a restricted set of values.
1014These can be handled by passing a container object as the *choices* keyword
1015argument to :meth:`~ArgumentParser.add_argument`.  When the command line is
1016parsed, argument values will be checked, and an error message will be displayed
1017if the argument was not one of the acceptable values::
1018
1019   >>> parser = argparse.ArgumentParser(prog='game.py')
1020   >>> parser.add_argument('move', choices=['rock', 'paper', 'scissors'])
1021   >>> parser.parse_args(['rock'])
1022   Namespace(move='rock')
1023   >>> parser.parse_args(['fire'])
1024   usage: game.py [-h] {rock,paper,scissors}
1025   game.py: error: argument move: invalid choice: 'fire' (choose from 'rock',
1026   'paper', 'scissors')
1027
1028Note that inclusion in the *choices* container is checked after any type_
1029conversions have been performed, so the type of the objects in the *choices*
1030container should match the type_ specified::
1031
1032   >>> parser = argparse.ArgumentParser(prog='doors.py')
1033   >>> parser.add_argument('door', type=int, choices=range(1, 4))
1034   >>> print(parser.parse_args(['3']))
1035   Namespace(door=3)
1036   >>> parser.parse_args(['4'])
1037   usage: doors.py [-h] {1,2,3}
1038   doors.py: error: argument door: invalid choice: 4 (choose from 1, 2, 3)
1039
1040Any object that supports the ``in`` operator can be passed as the *choices*
1041value, so :class:`dict` objects, :class:`set` objects, custom containers,
1042etc. are all supported.
1043
1044
1045required
1046^^^^^^^^
1047
1048In general, the :mod:`argparse` module assumes that flags like ``-f`` and ``--bar``
1049indicate *optional* arguments, which can always be omitted at the command line.
1050To make an option *required*, ``True`` can be specified for the ``required=``
1051keyword argument to :meth:`~ArgumentParser.add_argument`::
1052
1053   >>> parser = argparse.ArgumentParser()
1054   >>> parser.add_argument('--foo', required=True)
1055   >>> parser.parse_args(['--foo', 'BAR'])
1056   Namespace(foo='BAR')
1057   >>> parser.parse_args([])
1058   usage: argparse.py [-h] [--foo FOO]
1059   argparse.py: error: option --foo is required
1060
1061As the example shows, if an option is marked as ``required``,
1062:meth:`~ArgumentParser.parse_args` will report an error if that option is not
1063present at the command line.
1064
1065.. note::
1066
1067    Required options are generally considered bad form because users expect
1068    *options* to be *optional*, and thus they should be avoided when possible.
1069
1070
1071help
1072^^^^
1073
1074The ``help`` value is a string containing a brief description of the argument.
1075When a user requests help (usually by using ``-h`` or ``--help`` at the
1076command line), these ``help`` descriptions will be displayed with each
1077argument::
1078
1079   >>> parser = argparse.ArgumentParser(prog='frobble')
1080   >>> parser.add_argument('--foo', action='store_true',
1081   ...                     help='foo the bars before frobbling')
1082   >>> parser.add_argument('bar', nargs='+',
1083   ...                     help='one of the bars to be frobbled')
1084   >>> parser.parse_args(['-h'])
1085   usage: frobble [-h] [--foo] bar [bar ...]
1086
1087   positional arguments:
1088    bar     one of the bars to be frobbled
1089
1090   optional arguments:
1091    -h, --help  show this help message and exit
1092    --foo   foo the bars before frobbling
1093
1094The ``help`` strings can include various format specifiers to avoid repetition
1095of things like the program name or the argument default_.  The available
1096specifiers include the program name, ``%(prog)s`` and most keyword arguments to
1097:meth:`~ArgumentParser.add_argument`, e.g. ``%(default)s``, ``%(type)s``, etc.::
1098
1099   >>> parser = argparse.ArgumentParser(prog='frobble')
1100   >>> parser.add_argument('bar', nargs='?', type=int, default=42,
1101   ...                     help='the bar to %(prog)s (default: %(default)s)')
1102   >>> parser.print_help()
1103   usage: frobble [-h] [bar]
1104
1105   positional arguments:
1106    bar     the bar to frobble (default: 42)
1107
1108   optional arguments:
1109    -h, --help  show this help message and exit
1110
1111:mod:`argparse` supports silencing the help entry for certain options, by
1112setting the ``help`` value to ``argparse.SUPPRESS``::
1113
1114   >>> parser = argparse.ArgumentParser(prog='frobble')
1115   >>> parser.add_argument('--foo', help=argparse.SUPPRESS)
1116   >>> parser.print_help()
1117   usage: frobble [-h]
1118
1119   optional arguments:
1120     -h, --help  show this help message and exit
1121
1122
1123metavar
1124^^^^^^^
1125
1126When :class:`ArgumentParser` generates help messages, it needs some way to refer
1127to each expected argument.  By default, ArgumentParser objects use the dest_
1128value as the "name" of each object.  By default, for positional argument
1129actions, the dest_ value is used directly, and for optional argument actions,
1130the dest_ value is uppercased.  So, a single positional argument with
1131``dest='bar'`` will be referred to as ``bar``. A single
1132optional argument ``--foo`` that should be followed by a single command-line argument
1133will be referred to as ``FOO``.  An example::
1134
1135   >>> parser = argparse.ArgumentParser()
1136   >>> parser.add_argument('--foo')
1137   >>> parser.add_argument('bar')
1138   >>> parser.parse_args('X --foo Y'.split())
1139   Namespace(bar='X', foo='Y')
1140   >>> parser.print_help()
1141   usage:  [-h] [--foo FOO] bar
1142
1143   positional arguments:
1144    bar
1145
1146   optional arguments:
1147    -h, --help  show this help message and exit
1148    --foo FOO
1149
1150An alternative name can be specified with ``metavar``::
1151
1152   >>> parser = argparse.ArgumentParser()
1153   >>> parser.add_argument('--foo', metavar='YYY')
1154   >>> parser.add_argument('bar', metavar='XXX')
1155   >>> parser.parse_args('X --foo Y'.split())
1156   Namespace(bar='X', foo='Y')
1157   >>> parser.print_help()
1158   usage:  [-h] [--foo YYY] XXX
1159
1160   positional arguments:
1161    XXX
1162
1163   optional arguments:
1164    -h, --help  show this help message and exit
1165    --foo YYY
1166
1167Note that ``metavar`` only changes the *displayed* name - the name of the
1168attribute on the :meth:`~ArgumentParser.parse_args` object is still determined
1169by the dest_ value.
1170
1171Different values of ``nargs`` may cause the metavar to be used multiple times.
1172Providing a tuple to ``metavar`` specifies a different display for each of the
1173arguments::
1174
1175   >>> parser = argparse.ArgumentParser(prog='PROG')
1176   >>> parser.add_argument('-x', nargs=2)
1177   >>> parser.add_argument('--foo', nargs=2, metavar=('bar', 'baz'))
1178   >>> parser.print_help()
1179   usage: PROG [-h] [-x X X] [--foo bar baz]
1180
1181   optional arguments:
1182    -h, --help     show this help message and exit
1183    -x X X
1184    --foo bar baz
1185
1186
1187dest
1188^^^^
1189
1190Most :class:`ArgumentParser` actions add some value as an attribute of the
1191object returned by :meth:`~ArgumentParser.parse_args`.  The name of this
1192attribute is determined by the ``dest`` keyword argument of
1193:meth:`~ArgumentParser.add_argument`.  For positional argument actions,
1194``dest`` is normally supplied as the first argument to
1195:meth:`~ArgumentParser.add_argument`::
1196
1197   >>> parser = argparse.ArgumentParser()
1198   >>> parser.add_argument('bar')
1199   >>> parser.parse_args(['XXX'])
1200   Namespace(bar='XXX')
1201
1202For optional argument actions, the value of ``dest`` is normally inferred from
1203the option strings.  :class:`ArgumentParser` generates the value of ``dest`` by
1204taking the first long option string and stripping away the initial ``--``
1205string.  If no long option strings were supplied, ``dest`` will be derived from
1206the first short option string by stripping the initial ``-`` character.  Any
1207internal ``-`` characters will be converted to ``_`` characters to make sure
1208the string is a valid attribute name.  The examples below illustrate this
1209behavior::
1210
1211   >>> parser = argparse.ArgumentParser()
1212   >>> parser.add_argument('-f', '--foo-bar', '--foo')
1213   >>> parser.add_argument('-x', '-y')
1214   >>> parser.parse_args('-f 1 -x 2'.split())
1215   Namespace(foo_bar='1', x='2')
1216   >>> parser.parse_args('--foo 1 -y 2'.split())
1217   Namespace(foo_bar='1', x='2')
1218
1219``dest`` allows a custom attribute name to be provided::
1220
1221   >>> parser = argparse.ArgumentParser()
1222   >>> parser.add_argument('--foo', dest='bar')
1223   >>> parser.parse_args('--foo XXX'.split())
1224   Namespace(bar='XXX')
1225
1226Action classes
1227^^^^^^^^^^^^^^
1228
1229Action classes implement the Action API, a callable which returns a callable
1230which processes arguments from the command-line. Any object which follows this
1231API may be passed as the ``action`` parameter to :meth:`add_argument`.
1232
1233.. class:: Action(option_strings, dest, nargs=None, const=None, default=None, \
1234                  type=None, choices=None, required=False, help=None, \
1235                  metavar=None)
1236
1237Action objects are used by an ArgumentParser to represent the information needed
1238to parse a single argument from one or more strings from the command line. The
1239Action class must accept the two positional arguments plus any keyword arguments
1240passed to :meth:`ArgumentParser.add_argument` except for the ``action`` itself.
1241
1242Instances of Action (or return value of any callable to the ``action``
1243parameter) should have attributes "dest", "option_strings", "default", "type",
1244"required", "help", etc. defined. The easiest way to ensure these attributes
1245are defined is to call ``Action.__init__``.
1246
1247Action instances should be callable, so subclasses must override the
1248``__call__`` method, which should accept four parameters:
1249
1250* ``parser`` - The ArgumentParser object which contains this action.
1251
1252* ``namespace`` - The :class:`Namespace` object that will be returned by
1253  :meth:`~ArgumentParser.parse_args`.  Most actions add an attribute to this
1254  object using :func:`setattr`.
1255
1256* ``values`` - The associated command-line arguments, with any type conversions
1257  applied.  Type conversions are specified with the type_ keyword argument to
1258  :meth:`~ArgumentParser.add_argument`.
1259
1260* ``option_string`` - The option string that was used to invoke this action.
1261  The ``option_string`` argument is optional, and will be absent if the action
1262  is associated with a positional argument.
1263
1264The ``__call__`` method may perform arbitrary actions, but will typically set
1265attributes on the ``namespace`` based on ``dest`` and ``values``.
1266
1267
1268The parse_args() method
1269-----------------------
1270
1271.. method:: ArgumentParser.parse_args(args=None, namespace=None)
1272
1273   Convert argument strings to objects and assign them as attributes of the
1274   namespace.  Return the populated namespace.
1275
1276   Previous calls to :meth:`add_argument` determine exactly what objects are
1277   created and how they are assigned. See the documentation for
1278   :meth:`add_argument` for details.
1279
1280   * args_ - List of strings to parse.  The default is taken from
1281     :data:`sys.argv`.
1282
1283   * namespace_ - An object to take the attributes.  The default is a new empty
1284     :class:`Namespace` object.
1285
1286
1287Option value syntax
1288^^^^^^^^^^^^^^^^^^^
1289
1290The :meth:`~ArgumentParser.parse_args` method supports several ways of
1291specifying the value of an option (if it takes one).  In the simplest case, the
1292option and its value are passed as two separate arguments::
1293
1294   >>> parser = argparse.ArgumentParser(prog='PROG')
1295   >>> parser.add_argument('-x')
1296   >>> parser.add_argument('--foo')
1297   >>> parser.parse_args(['-x', 'X'])
1298   Namespace(foo=None, x='X')
1299   >>> parser.parse_args(['--foo', 'FOO'])
1300   Namespace(foo='FOO', x=None)
1301
1302For long options (options with names longer than a single character), the option
1303and value can also be passed as a single command-line argument, using ``=`` to
1304separate them::
1305
1306   >>> parser.parse_args(['--foo=FOO'])
1307   Namespace(foo='FOO', x=None)
1308
1309For short options (options only one character long), the option and its value
1310can be concatenated::
1311
1312   >>> parser.parse_args(['-xX'])
1313   Namespace(foo=None, x='X')
1314
1315Several short options can be joined together, using only a single ``-`` prefix,
1316as long as only the last option (or none of them) requires a value::
1317
1318   >>> parser = argparse.ArgumentParser(prog='PROG')
1319   >>> parser.add_argument('-x', action='store_true')
1320   >>> parser.add_argument('-y', action='store_true')
1321   >>> parser.add_argument('-z')
1322   >>> parser.parse_args(['-xyzZ'])
1323   Namespace(x=True, y=True, z='Z')
1324
1325
1326Invalid arguments
1327^^^^^^^^^^^^^^^^^
1328
1329While parsing the command line, :meth:`~ArgumentParser.parse_args` checks for a
1330variety of errors, including ambiguous options, invalid types, invalid options,
1331wrong number of positional arguments, etc.  When it encounters such an error,
1332it exits and prints the error along with a usage message::
1333
1334   >>> parser = argparse.ArgumentParser(prog='PROG')
1335   >>> parser.add_argument('--foo', type=int)
1336   >>> parser.add_argument('bar', nargs='?')
1337
1338   >>> # invalid type
1339   >>> parser.parse_args(['--foo', 'spam'])
1340   usage: PROG [-h] [--foo FOO] [bar]
1341   PROG: error: argument --foo: invalid int value: 'spam'
1342
1343   >>> # invalid option
1344   >>> parser.parse_args(['--bar'])
1345   usage: PROG [-h] [--foo FOO] [bar]
1346   PROG: error: no such option: --bar
1347
1348   >>> # wrong number of arguments
1349   >>> parser.parse_args(['spam', 'badger'])
1350   usage: PROG [-h] [--foo FOO] [bar]
1351   PROG: error: extra arguments found: badger
1352
1353
1354Arguments containing ``-``
1355^^^^^^^^^^^^^^^^^^^^^^^^^^
1356
1357The :meth:`~ArgumentParser.parse_args` method attempts to give errors whenever
1358the user has clearly made a mistake, but some situations are inherently
1359ambiguous.  For example, the command-line argument ``-1`` could either be an
1360attempt to specify an option or an attempt to provide a positional argument.
1361The :meth:`~ArgumentParser.parse_args` method is cautious here: positional
1362arguments may only begin with ``-`` if they look like negative numbers and
1363there are no options in the parser that look like negative numbers::
1364
1365   >>> parser = argparse.ArgumentParser(prog='PROG')
1366   >>> parser.add_argument('-x')
1367   >>> parser.add_argument('foo', nargs='?')
1368
1369   >>> # no negative number options, so -1 is a positional argument
1370   >>> parser.parse_args(['-x', '-1'])
1371   Namespace(foo=None, x='-1')
1372
1373   >>> # no negative number options, so -1 and -5 are positional arguments
1374   >>> parser.parse_args(['-x', '-1', '-5'])
1375   Namespace(foo='-5', x='-1')
1376
1377   >>> parser = argparse.ArgumentParser(prog='PROG')
1378   >>> parser.add_argument('-1', dest='one')
1379   >>> parser.add_argument('foo', nargs='?')
1380
1381   >>> # negative number options present, so -1 is an option
1382   >>> parser.parse_args(['-1', 'X'])
1383   Namespace(foo=None, one='X')
1384
1385   >>> # negative number options present, so -2 is an option
1386   >>> parser.parse_args(['-2'])
1387   usage: PROG [-h] [-1 ONE] [foo]
1388   PROG: error: no such option: -2
1389
1390   >>> # negative number options present, so both -1s are options
1391   >>> parser.parse_args(['-1', '-1'])
1392   usage: PROG [-h] [-1 ONE] [foo]
1393   PROG: error: argument -1: expected one argument
1394
1395If you have positional arguments that must begin with ``-`` and don't look
1396like negative numbers, you can insert the pseudo-argument ``'--'`` which tells
1397:meth:`~ArgumentParser.parse_args` that everything after that is a positional
1398argument::
1399
1400   >>> parser.parse_args(['--', '-f'])
1401   Namespace(foo='-f', one=None)
1402
1403.. _prefix-matching:
1404
1405Argument abbreviations (prefix matching)
1406^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1407
1408The :meth:`~ArgumentParser.parse_args` method allows long options to be
1409abbreviated to a prefix, if the abbreviation is unambiguous (the prefix matches
1410a unique option)::
1411
1412   >>> parser = argparse.ArgumentParser(prog='PROG')
1413   >>> parser.add_argument('-bacon')
1414   >>> parser.add_argument('-badger')
1415   >>> parser.parse_args('-bac MMM'.split())
1416   Namespace(bacon='MMM', badger=None)
1417   >>> parser.parse_args('-bad WOOD'.split())
1418   Namespace(bacon=None, badger='WOOD')
1419   >>> parser.parse_args('-ba BA'.split())
1420   usage: PROG [-h] [-bacon BACON] [-badger BADGER]
1421   PROG: error: ambiguous option: -ba could match -badger, -bacon
1422
1423An error is produced for arguments that could produce more than one options.
1424
1425.. _args:
1426
1427Beyond ``sys.argv``
1428^^^^^^^^^^^^^^^^^^^
1429
1430Sometimes it may be useful to have an ArgumentParser parse arguments other than those
1431of :data:`sys.argv`.  This can be accomplished by passing a list of strings to
1432:meth:`~ArgumentParser.parse_args`.  This is useful for testing at the
1433interactive prompt::
1434
1435   >>> parser = argparse.ArgumentParser()
1436   >>> parser.add_argument(
1437   ...     'integers', metavar='int', type=int, choices=xrange(10),
1438   ...     nargs='+', help='an integer in the range 0..9')
1439   >>> parser.add_argument(
1440   ...     '--sum', dest='accumulate', action='store_const', const=sum,
1441   ...     default=max, help='sum the integers (default: find the max)')
1442   >>> parser.parse_args(['1', '2', '3', '4'])
1443   Namespace(accumulate=<built-in function max>, integers=[1, 2, 3, 4])
1444   >>> parser.parse_args(['1', '2', '3', '4', '--sum'])
1445   Namespace(accumulate=<built-in function sum>, integers=[1, 2, 3, 4])
1446
1447.. _namespace:
1448
1449The Namespace object
1450^^^^^^^^^^^^^^^^^^^^
1451
1452.. class:: Namespace
1453
1454   Simple class used by default by :meth:`~ArgumentParser.parse_args` to create
1455   an object holding attributes and return it.
1456
1457This class is deliberately simple, just an :class:`object` subclass with a
1458readable string representation. If you prefer to have dict-like view of the
1459attributes, you can use the standard Python idiom, :func:`vars`::
1460
1461   >>> parser = argparse.ArgumentParser()
1462   >>> parser.add_argument('--foo')
1463   >>> args = parser.parse_args(['--foo', 'BAR'])
1464   >>> vars(args)
1465   {'foo': 'BAR'}
1466
1467It may also be useful to have an :class:`ArgumentParser` assign attributes to an
1468already existing object, rather than a new :class:`Namespace` object.  This can
1469be achieved by specifying the ``namespace=`` keyword argument::
1470
1471   >>> class C(object):
1472   ...     pass
1473   ...
1474   >>> c = C()
1475   >>> parser = argparse.ArgumentParser()
1476   >>> parser.add_argument('--foo')
1477   >>> parser.parse_args(args=['--foo', 'BAR'], namespace=c)
1478   >>> c.foo
1479   'BAR'
1480
1481
1482Other utilities
1483---------------
1484
1485Sub-commands
1486^^^^^^^^^^^^
1487
1488.. method:: ArgumentParser.add_subparsers([title], [description], [prog], \
1489                                          [parser_class], [action], \
1490                                          [option_string], [dest], [help], \
1491                                          [metavar])
1492
1493   Many programs split up their functionality into a number of sub-commands,
1494   for example, the ``svn`` program can invoke sub-commands like ``svn
1495   checkout``, ``svn update``, and ``svn commit``.  Splitting up functionality
1496   this way can be a particularly good idea when a program performs several
1497   different functions which require different kinds of command-line arguments.
1498   :class:`ArgumentParser` supports the creation of such sub-commands with the
1499   :meth:`add_subparsers` method.  The :meth:`add_subparsers` method is normally
1500   called with no arguments and returns a special action object.  This object
1501   has a single method, :meth:`~ArgumentParser.add_parser`, which takes a
1502   command name and any :class:`ArgumentParser` constructor arguments, and
1503   returns an :class:`ArgumentParser` object that can be modified as usual.
1504
1505   Description of parameters:
1506
1507   * title - title for the sub-parser group in help output; by default
1508     "subcommands" if description is provided, otherwise uses title for
1509     positional arguments
1510
1511   * description - description for the sub-parser group in help output, by
1512     default ``None``
1513
1514   * prog - usage information that will be displayed with sub-command help,
1515     by default the name of the program and any positional arguments before the
1516     subparser argument
1517
1518   * parser_class - class which will be used to create sub-parser instances, by
1519     default the class of the current parser (e.g. ArgumentParser)
1520
1521   * action_ - the basic type of action to be taken when this argument is
1522     encountered at the command line
1523
1524   * dest_ - name of the attribute under which sub-command name will be
1525     stored; by default ``None`` and no value is stored
1526
1527   * help_ - help for sub-parser group in help output, by default ``None``
1528
1529   * metavar_ - string presenting available sub-commands in help; by default it
1530     is ``None`` and presents sub-commands in form {cmd1, cmd2, ..}
1531
1532   Some example usage::
1533
1534     >>> # create the top-level parser
1535     >>> parser = argparse.ArgumentParser(prog='PROG')
1536     >>> parser.add_argument('--foo', action='store_true', help='foo help')
1537     >>> subparsers = parser.add_subparsers(help='sub-command help')
1538     >>>
1539     >>> # create the parser for the "a" command
1540     >>> parser_a = subparsers.add_parser('a', help='a help')
1541     >>> parser_a.add_argument('bar', type=int, help='bar help')
1542     >>>
1543     >>> # create the parser for the "b" command
1544     >>> parser_b = subparsers.add_parser('b', help='b help')
1545     >>> parser_b.add_argument('--baz', choices='XYZ', help='baz help')
1546     >>>
1547     >>> # parse some argument lists
1548     >>> parser.parse_args(['a', '12'])
1549     Namespace(bar=12, foo=False)
1550     >>> parser.parse_args(['--foo', 'b', '--baz', 'Z'])
1551     Namespace(baz='Z', foo=True)
1552
1553   Note that the object returned by :meth:`parse_args` will only contain
1554   attributes for the main parser and the subparser that was selected by the
1555   command line (and not any other subparsers).  So in the example above, when
1556   the ``a`` command is specified, only the ``foo`` and ``bar`` attributes are
1557   present, and when the ``b`` command is specified, only the ``foo`` and
1558   ``baz`` attributes are present.
1559
1560   Similarly, when a help message is requested from a subparser, only the help
1561   for that particular parser will be printed.  The help message will not
1562   include parent parser or sibling parser messages.  (A help message for each
1563   subparser command, however, can be given by supplying the ``help=`` argument
1564   to :meth:`add_parser` as above.)
1565
1566   ::
1567
1568     >>> parser.parse_args(['--help'])
1569     usage: PROG [-h] [--foo] {a,b} ...
1570
1571     positional arguments:
1572       {a,b}   sub-command help
1573         a     a help
1574         b     b help
1575
1576     optional arguments:
1577       -h, --help  show this help message and exit
1578       --foo   foo help
1579
1580     >>> parser.parse_args(['a', '--help'])
1581     usage: PROG a [-h] bar
1582
1583     positional arguments:
1584       bar     bar help
1585
1586     optional arguments:
1587       -h, --help  show this help message and exit
1588
1589     >>> parser.parse_args(['b', '--help'])
1590     usage: PROG b [-h] [--baz {X,Y,Z}]
1591
1592     optional arguments:
1593       -h, --help     show this help message and exit
1594       --baz {X,Y,Z}  baz help
1595
1596   The :meth:`add_subparsers` method also supports ``title`` and ``description``
1597   keyword arguments.  When either is present, the subparser's commands will
1598   appear in their own group in the help output.  For example::
1599
1600     >>> parser = argparse.ArgumentParser()
1601     >>> subparsers = parser.add_subparsers(title='subcommands',
1602     ...                                    description='valid subcommands',
1603     ...                                    help='additional help')
1604     >>> subparsers.add_parser('foo')
1605     >>> subparsers.add_parser('bar')
1606     >>> parser.parse_args(['-h'])
1607     usage:  [-h] {foo,bar} ...
1608
1609     optional arguments:
1610       -h, --help  show this help message and exit
1611
1612     subcommands:
1613       valid subcommands
1614
1615       {foo,bar}   additional help
1616
1617
1618   One particularly effective way of handling sub-commands is to combine the use
1619   of the :meth:`add_subparsers` method with calls to :meth:`set_defaults` so
1620   that each subparser knows which Python function it should execute.  For
1621   example::
1622
1623     >>> # sub-command functions
1624     >>> def foo(args):
1625     ...     print args.x * args.y
1626     ...
1627     >>> def bar(args):
1628     ...     print '((%s))' % args.z
1629     ...
1630     >>> # create the top-level parser
1631     >>> parser = argparse.ArgumentParser()
1632     >>> subparsers = parser.add_subparsers()
1633     >>>
1634     >>> # create the parser for the "foo" command
1635     >>> parser_foo = subparsers.add_parser('foo')
1636     >>> parser_foo.add_argument('-x', type=int, default=1)
1637     >>> parser_foo.add_argument('y', type=float)
1638     >>> parser_foo.set_defaults(func=foo)
1639     >>>
1640     >>> # create the parser for the "bar" command
1641     >>> parser_bar = subparsers.add_parser('bar')
1642     >>> parser_bar.add_argument('z')
1643     >>> parser_bar.set_defaults(func=bar)
1644     >>>
1645     >>> # parse the args and call whatever function was selected
1646     >>> args = parser.parse_args('foo 1 -x 2'.split())
1647     >>> args.func(args)
1648     2.0
1649     >>>
1650     >>> # parse the args and call whatever function was selected
1651     >>> args = parser.parse_args('bar XYZYX'.split())
1652     >>> args.func(args)
1653     ((XYZYX))
1654
1655   This way, you can let :meth:`parse_args` do the job of calling the
1656   appropriate function after argument parsing is complete.  Associating
1657   functions with actions like this is typically the easiest way to handle the
1658   different actions for each of your subparsers.  However, if it is necessary
1659   to check the name of the subparser that was invoked, the ``dest`` keyword
1660   argument to the :meth:`add_subparsers` call will work::
1661
1662     >>> parser = argparse.ArgumentParser()
1663     >>> subparsers = parser.add_subparsers(dest='subparser_name')
1664     >>> subparser1 = subparsers.add_parser('1')
1665     >>> subparser1.add_argument('-x')
1666     >>> subparser2 = subparsers.add_parser('2')
1667     >>> subparser2.add_argument('y')
1668     >>> parser.parse_args(['2', 'frobble'])
1669     Namespace(subparser_name='2', y='frobble')
1670
1671
1672FileType objects
1673^^^^^^^^^^^^^^^^
1674
1675.. class:: FileType(mode='r', bufsize=None)
1676
1677   The :class:`FileType` factory creates objects that can be passed to the type
1678   argument of :meth:`ArgumentParser.add_argument`.  Arguments that have
1679   :class:`FileType` objects as their type will open command-line arguments as files
1680   with the requested modes and buffer sizes::
1681
1682      >>> parser = argparse.ArgumentParser()
1683      >>> parser.add_argument('--output', type=argparse.FileType('wb', 0))
1684      >>> parser.parse_args(['--output', 'out'])
1685      Namespace(output=<open file 'out', mode 'wb' at 0x...>)
1686
1687   FileType objects understand the pseudo-argument ``'-'`` and automatically
1688   convert this into ``sys.stdin`` for readable :class:`FileType` objects and
1689   ``sys.stdout`` for writable :class:`FileType` objects::
1690
1691      >>> parser = argparse.ArgumentParser()
1692      >>> parser.add_argument('infile', type=argparse.FileType('r'))
1693      >>> parser.parse_args(['-'])
1694      Namespace(infile=<open file '<stdin>', mode 'r' at 0x...>)
1695
1696
1697Argument groups
1698^^^^^^^^^^^^^^^
1699
1700.. method:: ArgumentParser.add_argument_group(title=None, description=None)
1701
1702   By default, :class:`ArgumentParser` groups command-line arguments into
1703   "positional arguments" and "optional arguments" when displaying help
1704   messages. When there is a better conceptual grouping of arguments than this
1705   default one, appropriate groups can be created using the
1706   :meth:`add_argument_group` method::
1707
1708     >>> parser = argparse.ArgumentParser(prog='PROG', add_help=False)
1709     >>> group = parser.add_argument_group('group')
1710     >>> group.add_argument('--foo', help='foo help')
1711     >>> group.add_argument('bar', help='bar help')
1712     >>> parser.print_help()
1713     usage: PROG [--foo FOO] bar
1714
1715     group:
1716       bar    bar help
1717       --foo FOO  foo help
1718
1719   The :meth:`add_argument_group` method returns an argument group object which
1720   has an :meth:`~ArgumentParser.add_argument` method just like a regular
1721   :class:`ArgumentParser`.  When an argument is added to the group, the parser
1722   treats it just like a normal argument, but displays the argument in a
1723   separate group for help messages.  The :meth:`add_argument_group` method
1724   accepts *title* and *description* arguments which can be used to
1725   customize this display::
1726
1727     >>> parser = argparse.ArgumentParser(prog='PROG', add_help=False)
1728     >>> group1 = parser.add_argument_group('group1', 'group1 description')
1729     >>> group1.add_argument('foo', help='foo help')
1730     >>> group2 = parser.add_argument_group('group2', 'group2 description')
1731     >>> group2.add_argument('--bar', help='bar help')
1732     >>> parser.print_help()
1733     usage: PROG [--bar BAR] foo
1734
1735     group1:
1736       group1 description
1737
1738       foo    foo help
1739
1740     group2:
1741       group2 description
1742
1743       --bar BAR  bar help
1744
1745   Note that any arguments not in your user-defined groups will end up back
1746   in the usual "positional arguments" and "optional arguments" sections.
1747
1748
1749Mutual exclusion
1750^^^^^^^^^^^^^^^^
1751
1752.. method:: ArgumentParser.add_mutually_exclusive_group(required=False)
1753
1754   Create a mutually exclusive group. :mod:`argparse` will make sure that only
1755   one of the arguments in the mutually exclusive group was present on the
1756   command line::
1757
1758     >>> parser = argparse.ArgumentParser(prog='PROG')
1759     >>> group = parser.add_mutually_exclusive_group()
1760     >>> group.add_argument('--foo', action='store_true')
1761     >>> group.add_argument('--bar', action='store_false')
1762     >>> parser.parse_args(['--foo'])
1763     Namespace(bar=True, foo=True)
1764     >>> parser.parse_args(['--bar'])
1765     Namespace(bar=False, foo=False)
1766     >>> parser.parse_args(['--foo', '--bar'])
1767     usage: PROG [-h] [--foo | --bar]
1768     PROG: error: argument --bar: not allowed with argument --foo
1769
1770   The :meth:`add_mutually_exclusive_group` method also accepts a *required*
1771   argument, to indicate that at least one of the mutually exclusive arguments
1772   is required::
1773
1774     >>> parser = argparse.ArgumentParser(prog='PROG')
1775     >>> group = parser.add_mutually_exclusive_group(required=True)
1776     >>> group.add_argument('--foo', action='store_true')
1777     >>> group.add_argument('--bar', action='store_false')
1778     >>> parser.parse_args([])
1779     usage: PROG [-h] (--foo | --bar)
1780     PROG: error: one of the arguments --foo --bar is required
1781
1782   Note that currently mutually exclusive argument groups do not support the
1783   *title* and *description* arguments of
1784   :meth:`~ArgumentParser.add_argument_group`.
1785
1786
1787Parser defaults
1788^^^^^^^^^^^^^^^
1789
1790.. method:: ArgumentParser.set_defaults(**kwargs)
1791
1792   Most of the time, the attributes of the object returned by :meth:`parse_args`
1793   will be fully determined by inspecting the command-line arguments and the argument
1794   actions.  :meth:`set_defaults` allows some additional
1795   attributes that are determined without any inspection of the command line to
1796   be added::
1797
1798     >>> parser = argparse.ArgumentParser()
1799     >>> parser.add_argument('foo', type=int)
1800     >>> parser.set_defaults(bar=42, baz='badger')
1801     >>> parser.parse_args(['736'])
1802     Namespace(bar=42, baz='badger', foo=736)
1803
1804   Note that parser-level defaults always override argument-level defaults::
1805
1806     >>> parser = argparse.ArgumentParser()
1807     >>> parser.add_argument('--foo', default='bar')
1808     >>> parser.set_defaults(foo='spam')
1809     >>> parser.parse_args([])
1810     Namespace(foo='spam')
1811
1812   Parser-level defaults can be particularly useful when working with multiple
1813   parsers.  See the :meth:`~ArgumentParser.add_subparsers` method for an
1814   example of this type.
1815
1816.. method:: ArgumentParser.get_default(dest)
1817
1818   Get the default value for a namespace attribute, as set by either
1819   :meth:`~ArgumentParser.add_argument` or by
1820   :meth:`~ArgumentParser.set_defaults`::
1821
1822     >>> parser = argparse.ArgumentParser()
1823     >>> parser.add_argument('--foo', default='badger')
1824     >>> parser.get_default('foo')
1825     'badger'
1826
1827
1828Printing help
1829^^^^^^^^^^^^^
1830
1831In most typical applications, :meth:`~ArgumentParser.parse_args` will take
1832care of formatting and printing any usage or error messages.  However, several
1833formatting methods are available:
1834
1835.. method:: ArgumentParser.print_usage(file=None)
1836
1837   Print a brief description of how the :class:`ArgumentParser` should be
1838   invoked on the command line.  If *file* is ``None``, :data:`sys.stdout` is
1839   assumed.
1840
1841.. method:: ArgumentParser.print_help(file=None)
1842
1843   Print a help message, including the program usage and information about the
1844   arguments registered with the :class:`ArgumentParser`.  If *file* is
1845   ``None``, :data:`sys.stdout` is assumed.
1846
1847There are also variants of these methods that simply return a string instead of
1848printing it:
1849
1850.. method:: ArgumentParser.format_usage()
1851
1852   Return a string containing a brief description of how the
1853   :class:`ArgumentParser` should be invoked on the command line.
1854
1855.. method:: ArgumentParser.format_help()
1856
1857   Return a string containing a help message, including the program usage and
1858   information about the arguments registered with the :class:`ArgumentParser`.
1859
1860
1861Partial parsing
1862^^^^^^^^^^^^^^^
1863
1864.. method:: ArgumentParser.parse_known_args(args=None, namespace=None)
1865
1866Sometimes a script may only parse a few of the command-line arguments, passing
1867the remaining arguments on to another script or program. In these cases, the
1868:meth:`~ArgumentParser.parse_known_args` method can be useful.  It works much like
1869:meth:`~ArgumentParser.parse_args` except that it does not produce an error when
1870extra arguments are present.  Instead, it returns a two item tuple containing
1871the populated namespace and the list of remaining argument strings.
1872
1873::
1874
1875   >>> parser = argparse.ArgumentParser()
1876   >>> parser.add_argument('--foo', action='store_true')
1877   >>> parser.add_argument('bar')
1878   >>> parser.parse_known_args(['--foo', '--badger', 'BAR', 'spam'])
1879   (Namespace(bar='BAR', foo=True), ['--badger', 'spam'])
1880
1881.. warning::
1882   :ref:`Prefix matching <prefix-matching>` rules apply to
1883   :meth:`parse_known_args`. The parser may consume an option even if it's just
1884   a prefix of one of its known options, instead of leaving it in the remaining
1885   arguments list.
1886
1887
1888Customizing file parsing
1889^^^^^^^^^^^^^^^^^^^^^^^^
1890
1891.. method:: ArgumentParser.convert_arg_line_to_args(arg_line)
1892
1893   Arguments that are read from a file (see the *fromfile_prefix_chars*
1894   keyword argument to the :class:`ArgumentParser` constructor) are read one
1895   argument per line. :meth:`convert_arg_line_to_args` can be overridden for
1896   fancier reading.
1897
1898   This method takes a single argument *arg_line* which is a string read from
1899   the argument file.  It returns a list of arguments parsed from this string.
1900   The method is called once per line read from the argument file, in order.
1901
1902   A useful override of this method is one that treats each space-separated word
1903   as an argument::
1904
1905    def convert_arg_line_to_args(self, arg_line):
1906        return arg_line.split()
1907
1908
1909Exiting methods
1910^^^^^^^^^^^^^^^
1911
1912.. method:: ArgumentParser.exit(status=0, message=None)
1913
1914   This method terminates the program, exiting with the specified *status*
1915   and, if given, it prints a *message* before that.
1916
1917.. method:: ArgumentParser.error(message)
1918
1919   This method prints a usage message including the *message* to the
1920   standard error and terminates the program with a status code of 2.
1921
1922
1923.. _argparse-from-optparse:
1924
1925Upgrading optparse code
1926-----------------------
1927
1928Originally, the :mod:`argparse` module had attempted to maintain compatibility
1929with :mod:`optparse`.  However, :mod:`optparse` was difficult to extend
1930transparently, particularly with the changes required to support the new
1931``nargs=`` specifiers and better usage messages.  When most everything in
1932:mod:`optparse` had either been copy-pasted over or monkey-patched, it no
1933longer seemed practical to try to maintain the backwards compatibility.
1934
1935The :mod:`argparse` module improves on the standard library :mod:`optparse`
1936module in a number of ways including:
1937
1938* Handling positional arguments.
1939* Supporting sub-commands.
1940* Allowing alternative option prefixes like ``+`` and ``/``.
1941* Handling zero-or-more and one-or-more style arguments.
1942* Producing more informative usage messages.
1943* Providing a much simpler interface for custom ``type`` and ``action``.
1944
1945A partial upgrade path from :mod:`optparse` to :mod:`argparse`:
1946
1947* Replace all :meth:`optparse.OptionParser.add_option` calls with
1948  :meth:`ArgumentParser.add_argument` calls.
1949
1950* Replace ``(options, args) = parser.parse_args()`` with ``args =
1951  parser.parse_args()`` and add additional :meth:`ArgumentParser.add_argument`
1952  calls for the positional arguments. Keep in mind that what was previously
1953  called ``options``, now in the :mod:`argparse` context is called ``args``.
1954
1955* Replace :meth:`optparse.OptionParser.disable_interspersed_args`
1956  by setting ``nargs`` of a positional argument to `argparse.REMAINDER`_, or
1957  use :meth:`~ArgumentParser.parse_known_args` to collect unparsed argument
1958  strings in a separate list.
1959
1960* Replace callback actions and the ``callback_*`` keyword arguments with
1961  ``type`` or ``action`` arguments.
1962
1963* Replace string names for ``type`` keyword arguments with the corresponding
1964  type objects (e.g. int, float, complex, etc).
1965
1966* Replace :class:`optparse.Values` with :class:`Namespace` and
1967  :exc:`optparse.OptionError` and :exc:`optparse.OptionValueError` with
1968  :exc:`ArgumentError`.
1969
1970* Replace strings with implicit arguments such as ``%default`` or ``%prog`` with
1971  the standard Python syntax to use dictionaries to format strings, that is,
1972  ``%(default)s`` and ``%(prog)s``.
1973
1974* Replace the OptionParser constructor ``version`` argument with a call to
1975  ``parser.add_argument('--version', action='version', version='<the version>')``.
1976