@@ -25,29 +25,6 @@ will figure out how to parse those out of :data:`sys.argv`. The :mod:`argparse`
2525module also automatically generates help and usage messages. The module
2626will also issue errors when users give the program invalid arguments.
2727
28- Quick Links for ArgumentParser
29- ---------------------------------------
30- ========================= =========================================================================================================== ==================================================================================
31- Name Description Values
32- ========================= =========================================================================================================== ==================================================================================
33- prog _ The name of the program Defaults to ``os.path.basename(sys.argv[0]) ``
34- usage _ The string describing the program usage
35- description _ A brief description of what the program does
36- epilog _ Additional description of the program after the argument help
37- parents _ A list of :class: `ArgumentParser ` objects whose arguments should also be included
38- formatter_class _ A class for customizing the help output ``argparse.HelpFormatter ``
39- prefix_chars _ The set of characters that prefix optional arguments Defaults to ``'-' ``
40- fromfile_prefix_chars _ The set of characters that prefix files to read additional arguments from Defaults to ``None `` (meaning arguments will never be treated as file references)
41- argument_default _ The global default value for arguments
42- allow_abbrev _ Allows long options to be abbreviated if the abbreviation is unambiguous ``True `` or ``False `` (default: ``True ``)
43- conflict_handler _ The strategy for resolving conflicting optionals
44- add_help _ Add a ``-h/--help `` option to the parser ``True `` or ``False `` (default: ``True ``)
45- exit_on_error _ Determines whether or not to exit with error info when an error occurs ``True `` or ``False `` (default: ``True ``)
46- ========================= =========================================================================================================== ==================================================================================
47-
48- Core Functionality
49- ------------------
50-
5128The :mod: `argparse ` module's support for command-line interfaces is built
5229around an instance of :class: `argparse.ArgumentParser `. It is a container for
5330argument specifications and has options that apply to the parser as whole::
@@ -73,133 +50,6 @@ the extracted data in a :class:`argparse.Namespace` object::
7350 print(args.filename, args.count, args.verbose)
7451
7552
76- Quick Links for add_argument()
77- ------------------------------
78-
79- ============================ =========================================================== ==========================================================================================================================
80- Name Description Values
81- ============================ =========================================================== ==========================================================================================================================
82- action _ Specify how an argument should be handled ``'store' ``, ``'store_const' ``, ``'store_true' ``, ``'append' ``, ``'append_const' ``, ``'count' ``, ``'help' ``, ``'version' ``
83- choices _ Limit values to a specific set of choices ``['foo', 'bar'] ``, ``range(1, 10) ``, or :class: `~collections.abc.Container ` instance
84- const _ Store a constant value
85- default _ Default value used when an argument is not provided Defaults to ``None ``
86- dest _ Specify the attribute name used in the result namespace
87- help _ Help message for an argument
88- metavar _ Alternate display name for the argument as shown in help
89- nargs _ Number of times the argument can be used :class: `int `, ``'?' ``, ``'*' ``, or ``'+' ``
90- required _ Indicate whether an argument is required or optional ``True `` or ``False ``
91- :ref: `type <argparse-type >` Automatically convert an argument to the given type :class: `int `, :class: `float `, ``argparse.FileType('w') ``, or callable function
92- ============================ =========================================================== ==========================================================================================================================
93-
94-
95- Example
96- -------
97-
98- The following code is a Python program that takes a list of integers and
99- produces either the sum or the max::
100-
101- import argparse
102-
103- parser = argparse.ArgumentParser(description='Process some integers.')
104- parser.add_argument('integers', metavar='N', type=int, nargs='+',
105- help='an integer for the accumulator')
106- parser.add_argument('--sum', dest='accumulate', action='store_const',
107- const=sum, default=max,
108- help='sum the integers (default: find the max)')
109-
110- args = parser.parse_args()
111- print(args.accumulate(args.integers))
112-
113- Assuming the above Python code is saved into a file called ``prog.py ``, it can
114- be run at the command line and it provides useful help messages:
115-
116- .. code-block :: shell-session
117-
118- $ python prog.py -h
119- usage: prog.py [-h] [--sum] N [N ...]
120-
121- Process some integers.
122-
123- positional arguments:
124- N an integer for the accumulator
125-
126- options:
127- -h, --help show this help message and exit
128- --sum sum the integers (default: find the max)
129-
130- When run with the appropriate arguments, it prints either the sum or the max of
131- the command-line integers:
132-
133- .. code-block :: shell-session
134-
135- $ python prog.py 1 2 3 4
136- 4
137-
138- $ python prog.py 1 2 3 4 --sum
139- 10
140-
141- If invalid arguments are passed in, an error will be displayed:
142-
143- .. code-block :: shell-session
144-
145- $ python prog.py a b c
146- usage: prog.py [-h] [--sum] N [N ...]
147- prog.py: error: argument N: invalid int value: 'a'
148-
149- The following sections walk you through this example.
150-
151-
152- Creating a parser
153- ^^^^^^^^^^^^^^^^^
154-
155- The first step in using the :mod: `argparse ` is creating an
156- :class: `ArgumentParser ` object::
157-
158- >>> parser = argparse.ArgumentParser(description='Process some integers.')
159-
160- The :class: `ArgumentParser ` object will hold all the information necessary to
161- parse the command line into Python data types.
162-
163-
164- Adding arguments
165- ^^^^^^^^^^^^^^^^
166-
167- Filling an :class: `ArgumentParser ` with information about program arguments is
168- done by making calls to the :meth: `~ArgumentParser.add_argument ` method.
169- Generally, these calls tell the :class: `ArgumentParser ` how to take the strings
170- on the command line and turn them into objects. This information is stored and
171- used when :meth: `~ArgumentParser.parse_args ` is called. For example::
172-
173- >>> parser.add_argument('integers', metavar='N', type=int, nargs='+',
174- ... help='an integer for the accumulator')
175- >>> parser.add_argument('--sum', dest='accumulate', action='store_const',
176- ... const=sum, default=max,
177- ... help='sum the integers (default: find the max)')
178-
179- Later, calling :meth: `~ArgumentParser.parse_args ` will return an object with
180- two attributes, ``integers `` and ``accumulate ``. The ``integers `` attribute
181- will be a list of one or more integers, and the ``accumulate `` attribute will be
182- either the :func: `sum ` function, if ``--sum `` was specified at the command line,
183- or the :func: `max ` function if it was not.
184-
185-
186- Parsing arguments
187- ^^^^^^^^^^^^^^^^^
188-
189- :class: `ArgumentParser ` parses arguments through the
190- :meth: `~ArgumentParser.parse_args ` method. This will inspect the command line,
191- convert each argument to the appropriate type and then invoke the appropriate action.
192- In most cases, this means a simple :class: `Namespace ` object will be built up from
193- attributes parsed out of the command line::
194-
195- >>> parser.parse_args(['--sum', '7', '-1', '42'])
196- Namespace(accumulate=<built-in function sum>, integers=[7, -1, 42])
197-
198- In a script, :meth: `~ArgumentParser.parse_args ` will typically be called with no
199- arguments, and the :class: `ArgumentParser ` will automatically determine the
200- command-line arguments from :data: `sys.argv `.
201-
202-
20353ArgumentParser objects
20454----------------------
20555
@@ -272,35 +122,9 @@ By default, :class:`ArgumentParser` objects use the base name
272122(see :func: `os.path.basename `) of ``sys.argv[0] `` to determine
273123how to display the name of the program in help messages. This default is almost
274124always desirable because it will make the help messages match the name that was
275- used to invoke the program on the command line. For example, consider a file
276- named ``myprogram.py `` with the following code::
277-
278- import argparse
279- parser = argparse.ArgumentParser()
280- parser.add_argument('--foo', help='foo help')
281- args = parser.parse_args()
282-
283- The help for this program will display ``myprogram.py `` as the program name
284- (regardless of where the program was invoked from):
285-
286- .. code-block :: shell-session
287-
288- $ python myprogram.py --help
289- usage: myprogram.py [-h] [--foo FOO]
290-
291- options:
292- -h, --help show this help message and exit
293- --foo FOO foo help
294- $ cd ..
295- $ python subdir/myprogram.py --help
296- usage: myprogram.py [-h] [--foo FOO]
297-
298- options:
299- -h, --help show this help message and exit
300- --foo FOO foo help
301-
302- To change this default behavior, another value can be supplied using the
303- ``prog= `` argument to :class: `ArgumentParser `::
125+ used to invoke the program on the command line. However, to change this default
126+ behavior, another value can be supplied using the ``prog= `` argument to
127+ :class: `ArgumentParser `::
304128
305129 >>> parser = argparse.ArgumentParser(prog='myprogram')
306130 >>> parser.print_help()
@@ -329,22 +153,8 @@ usage
329153^^^^^
330154
331155By default, :class: `ArgumentParser ` calculates the usage message from the
332- arguments it contains::
333-
334- >>> parser = argparse.ArgumentParser(prog='PROG')
335- >>> parser.add_argument('--foo', nargs='?', help='foo help')
336- >>> parser.add_argument('bar', nargs='+', help='bar help')
337- >>> parser.print_help()
338- usage: PROG [-h] [--foo [FOO]] bar [bar ...]
339-
340- positional arguments:
341- bar bar help
342-
343- options:
344- -h, --help show this help message and exit
345- --foo [FOO] foo help
346-
347- The default message can be overridden with the ``usage= `` keyword argument::
156+ arguments it contains. The default message can be overridden with the
157+ ``usage= `` keyword argument::
348158
349159 >>> parser = argparse.ArgumentParser(prog='PROG', usage='%(prog)s [options]')
350160 >>> parser.add_argument('--foo', nargs='?', help='foo help')
@@ -372,16 +182,7 @@ Most calls to the :class:`ArgumentParser` constructor will use the
372182``description= `` keyword argument. This argument gives a brief description of
373183what the program does and how it works. In help messages, the description is
374184displayed between the command-line usage string and the help messages for the
375- various arguments::
376-
377- >>> parser = argparse.ArgumentParser(description='A foo that bars')
378- >>> parser.print_help()
379- usage: argparse.py [-h]
380-
381- A foo that bars
382-
383- options:
384- -h, --help show this help message and exit
185+ various arguments.
385186
386187By default, the description will be line-wrapped so that it fits within the
387188given space. To change this behavior, see the formatter_class _ argument.
@@ -692,25 +493,8 @@ add_help
692493^^^^^^^^
693494
694495By default, ArgumentParser objects add an option which simply displays
695- the parser's help message. For example, consider a file named
696- ``myprogram.py `` containing the following code::
697-
698- import argparse
699- parser = argparse.ArgumentParser()
700- parser.add_argument('--foo', help='foo help')
701- args = parser.parse_args()
702-
703- If ``-h `` or ``--help `` is supplied at the command line, the ArgumentParser
704- help will be printed:
705-
706- .. code-block :: shell-session
707-
708- $ python myprogram.py --help
709- usage: myprogram.py [-h] [--foo FOO]
710-
711- options:
712- -h, --help show this help message and exit
713- --foo FOO foo help
496+ the parser's help message. If ``-h `` or ``--help `` is supplied at the command
497+ line, the ArgumentParser help will be printed.
714498
715499Occasionally, it may be useful to disable the addition of this help option.
716500This can be achieved by passing ``False `` as the ``add_help= `` argument to
0 commit comments