diff options
| author | Craig Jennings <c@cjennings.net> | 2024-04-07 13:41:34 -0500 |
|---|---|---|
| committer | Craig Jennings <c@cjennings.net> | 2024-04-07 13:41:34 -0500 |
| commit | 754bbf7a25a8dda49b5d08ef0d0443bbf5af0e36 (patch) | |
| tree | f1190704f78f04a2b0b4c977d20fe96a828377f1 /devdocs/python~3.12/library%2Fargparse.html | |
new repository
Diffstat (limited to 'devdocs/python~3.12/library%2Fargparse.html')
| -rw-r--r-- | devdocs/python~3.12/library%2Fargparse.html | 990 |
1 files changed, 990 insertions, 0 deletions
diff --git a/devdocs/python~3.12/library%2Fargparse.html b/devdocs/python~3.12/library%2Fargparse.html new file mode 100644 index 00000000..f490f9ea --- /dev/null +++ b/devdocs/python~3.12/library%2Fargparse.html @@ -0,0 +1,990 @@ + <span id="argparse-parser-for-command-line-options-arguments-and-sub-commands"></span><h1>argparse — Parser for command-line options, arguments and sub-commands</h1> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.2.</span></p> </div> <p><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/3.12/Lib/argparse.py">Lib/argparse.py</a></p> <aside class="sidebar"> <p class="sidebar-title">Tutorial</p> <p>This page contains the API reference information. For a more gentle introduction to Python command-line parsing, have a look at the <a class="reference internal" href="../howto/argparse#argparse-tutorial"><span class="std std-ref">argparse tutorial</span></a>.</p> </aside> <p>The <a class="reference internal" href="#module-argparse" title="argparse: Command-line option and argument parsing library."><code>argparse</code></a> module makes it easy to write user-friendly command-line interfaces. The program defines what arguments it requires, and <a class="reference internal" href="#module-argparse" title="argparse: Command-line option and argument parsing library."><code>argparse</code></a> will figure out how to parse those out of <a class="reference internal" href="sys#sys.argv" title="sys.argv"><code>sys.argv</code></a>. The <a class="reference internal" href="#module-argparse" title="argparse: Command-line option and argument parsing library."><code>argparse</code></a> module also automatically generates help and usage messages. The module will also issue errors when users give the program invalid arguments.</p> <section id="core-functionality"> <h2>Core Functionality</h2> <p>The <a class="reference internal" href="#module-argparse" title="argparse: Command-line option and argument parsing library."><code>argparse</code></a> module’s support for command-line interfaces is built around an instance of <a class="reference internal" href="#argparse.ArgumentParser" title="argparse.ArgumentParser"><code>argparse.ArgumentParser</code></a>. It is a container for argument specifications and has options that apply to the parser as whole:</p> <pre data-language="python">parser = argparse.ArgumentParser( + prog='ProgramName', + description='What the program does', + epilog='Text at the bottom of help') +</pre> <p>The <a class="reference internal" href="#argparse.ArgumentParser.add_argument" title="argparse.ArgumentParser.add_argument"><code>ArgumentParser.add_argument()</code></a> method attaches individual argument specifications to the parser. It supports positional arguments, options that accept values, and on/off flags:</p> <pre data-language="python">parser.add_argument('filename') # positional argument +parser.add_argument('-c', '--count') # option that takes a value +parser.add_argument('-v', '--verbose', + action='store_true') # on/off flag +</pre> <p>The <a class="reference internal" href="#argparse.ArgumentParser.parse_args" title="argparse.ArgumentParser.parse_args"><code>ArgumentParser.parse_args()</code></a> method runs the parser and places the extracted data in a <a class="reference internal" href="#argparse.Namespace" title="argparse.Namespace"><code>argparse.Namespace</code></a> object:</p> <pre data-language="python">args = parser.parse_args() +print(args.filename, args.count, args.verbose) +</pre> </section> <section id="quick-links-for-add-argument"> <h2>Quick Links for add_argument()</h2> <table class="docutils align-default"> <thead> <tr> +<th class="head"><p>Name</p></th> <th class="head"><p>Description</p></th> <th class="head"><p>Values</p></th> </tr> </thead> <tr> +<td><p><a class="reference internal" href="#action">action</a></p></td> <td><p>Specify how an argument should be handled</p></td> <td><p><code>'store'</code>, <code>'store_const'</code>, <code>'store_true'</code>, <code>'append'</code>, <code>'append_const'</code>, <code>'count'</code>, <code>'help'</code>, <code>'version'</code></p></td> </tr> <tr> +<td><p><a class="reference internal" href="#choices">choices</a></p></td> <td><p>Limit values to a specific set of choices</p></td> <td><p><code>['foo', 'bar']</code>, <code>range(1, 10)</code>, or <a class="reference internal" href="collections.abc#collections.abc.Container" title="collections.abc.Container"><code>Container</code></a> instance</p></td> </tr> <tr> +<td><p><a class="reference internal" href="#const">const</a></p></td> <td><p>Store a constant value</p></td> <td></td> </tr> <tr> +<td><p><a class="reference internal" href="#default">default</a></p></td> <td><p>Default value used when an argument is not provided</p></td> <td><p>Defaults to <code>None</code></p></td> </tr> <tr> +<td><p><a class="reference internal" href="#dest">dest</a></p></td> <td><p>Specify the attribute name used in the result namespace</p></td> <td></td> </tr> <tr> +<td><p><a class="reference internal" href="#help">help</a></p></td> <td><p>Help message for an argument</p></td> <td></td> </tr> <tr> +<td><p><a class="reference internal" href="#metavar">metavar</a></p></td> <td><p>Alternate display name for the argument as shown in help</p></td> <td></td> </tr> <tr> +<td><p><a class="reference internal" href="#nargs">nargs</a></p></td> <td><p>Number of times the argument can be used</p></td> <td><p><a class="reference internal" href="functions#int" title="int"><code>int</code></a>, <code>'?'</code>, <code>'*'</code>, or <code>'+'</code></p></td> </tr> <tr> +<td><p><a class="reference internal" href="#required">required</a></p></td> <td><p>Indicate whether an argument is required or optional</p></td> <td><p><code>True</code> or <code>False</code></p></td> </tr> <tr> +<td><p><a class="reference internal" href="#argparse-type"><span class="std std-ref">type</span></a></p></td> <td><p>Automatically convert an argument to the given type</p></td> <td><p><a class="reference internal" href="functions#int" title="int"><code>int</code></a>, <a class="reference internal" href="functions#float" title="float"><code>float</code></a>, <code>argparse.FileType('w')</code>, or callable function</p></td> </tr> </table> </section> <section id="example"> <h2>Example</h2> <p>The following code is a Python program that takes a list of integers and produces either the sum or the max:</p> <pre data-language="python">import argparse + +parser = argparse.ArgumentParser(description='Process some integers.') +parser.add_argument('integers', metavar='N', type=int, nargs='+', + help='an integer for the accumulator') +parser.add_argument('--sum', dest='accumulate', action='store_const', + const=sum, default=max, + help='sum the integers (default: find the max)') + +args = parser.parse_args() +print(args.accumulate(args.integers)) +</pre> <p>Assuming the above Python code is saved into a file called <code>prog.py</code>, it can be run at the command line and it provides useful help messages:</p> <pre data-language="shell">$ python prog.py -h +usage: prog.py [-h] [--sum] N [N ...] + +Process some integers. + +positional arguments: + N an integer for the accumulator + +options: + -h, --help show this help message and exit + --sum sum the integers (default: find the max) +</pre> <p>When run with the appropriate arguments, it prints either the sum or the max of the command-line integers:</p> <pre data-language="shell">$ python prog.py 1 2 3 4 +4 + +$ python prog.py 1 2 3 4 --sum +10 +</pre> <p>If invalid arguments are passed in, an error will be displayed:</p> <pre data-language="shell">$ python prog.py a b c +usage: prog.py [-h] [--sum] N [N ...] +prog.py: error: argument N: invalid int value: 'a' +</pre> <p>The following sections walk you through this example.</p> <section id="creating-a-parser"> <h3>Creating a parser</h3> <p>The first step in using the <a class="reference internal" href="#module-argparse" title="argparse: Command-line option and argument parsing library."><code>argparse</code></a> is creating an <a class="reference internal" href="#argparse.ArgumentParser" title="argparse.ArgumentParser"><code>ArgumentParser</code></a> object:</p> <pre data-language="python">>>> parser = argparse.ArgumentParser(description='Process some integers.') +</pre> <p>The <a class="reference internal" href="#argparse.ArgumentParser" title="argparse.ArgumentParser"><code>ArgumentParser</code></a> object will hold all the information necessary to parse the command line into Python data types.</p> </section> <section id="adding-arguments"> <h3>Adding arguments</h3> <p>Filling an <a class="reference internal" href="#argparse.ArgumentParser" title="argparse.ArgumentParser"><code>ArgumentParser</code></a> with information about program arguments is done by making calls to the <a class="reference internal" href="#argparse.ArgumentParser.add_argument" title="argparse.ArgumentParser.add_argument"><code>add_argument()</code></a> method. Generally, these calls tell the <a class="reference internal" href="#argparse.ArgumentParser" title="argparse.ArgumentParser"><code>ArgumentParser</code></a> how to take the strings on the command line and turn them into objects. This information is stored and used when <a class="reference internal" href="#argparse.ArgumentParser.parse_args" title="argparse.ArgumentParser.parse_args"><code>parse_args()</code></a> is called. For example:</p> <pre data-language="python">>>> parser.add_argument('integers', metavar='N', type=int, nargs='+', +... help='an integer for the accumulator') +>>> parser.add_argument('--sum', dest='accumulate', action='store_const', +... const=sum, default=max, +... help='sum the integers (default: find the max)') +</pre> <p>Later, calling <a class="reference internal" href="#argparse.ArgumentParser.parse_args" title="argparse.ArgumentParser.parse_args"><code>parse_args()</code></a> will return an object with two attributes, <code>integers</code> and <code>accumulate</code>. The <code>integers</code> attribute will be a list of one or more integers, and the <code>accumulate</code> attribute will be either the <a class="reference internal" href="functions#sum" title="sum"><code>sum()</code></a> function, if <code>--sum</code> was specified at the command line, or the <a class="reference internal" href="functions#max" title="max"><code>max()</code></a> function if it was not.</p> </section> <section id="parsing-arguments"> <h3>Parsing arguments</h3> <p><a class="reference internal" href="#argparse.ArgumentParser" title="argparse.ArgumentParser"><code>ArgumentParser</code></a> parses arguments through the <a class="reference internal" href="#argparse.ArgumentParser.parse_args" title="argparse.ArgumentParser.parse_args"><code>parse_args()</code></a> method. This will inspect the command line, convert each argument to the appropriate type and then invoke the appropriate action. In most cases, this means a simple <a class="reference internal" href="#argparse.Namespace" title="argparse.Namespace"><code>Namespace</code></a> object will be built up from attributes parsed out of the command line:</p> <pre data-language="python">>>> parser.parse_args(['--sum', '7', '-1', '42']) +Namespace(accumulate=<built-in function sum>, integers=[7, -1, 42]) +</pre> <p>In a script, <a class="reference internal" href="#argparse.ArgumentParser.parse_args" title="argparse.ArgumentParser.parse_args"><code>parse_args()</code></a> will typically be called with no arguments, and the <a class="reference internal" href="#argparse.ArgumentParser" title="argparse.ArgumentParser"><code>ArgumentParser</code></a> will automatically determine the command-line arguments from <a class="reference internal" href="sys#sys.argv" title="sys.argv"><code>sys.argv</code></a>.</p> </section> </section> <section id="argumentparser-objects"> <h2>ArgumentParser objects</h2> <dl class="py class"> <dt class="sig sig-object py" id="argparse.ArgumentParser"> +<code>class argparse.ArgumentParser(prog=None, usage=None, description=None, epilog=None, parents=[], formatter_class=argparse.HelpFormatter, prefix_chars='-', fromfile_prefix_chars=None, argument_default=None, conflict_handler='error', add_help=True, allow_abbrev=True, exit_on_error=True)</code> </dt> <dd> +<p>Create a new <a class="reference internal" href="#argparse.ArgumentParser" title="argparse.ArgumentParser"><code>ArgumentParser</code></a> object. All parameters should be passed as keyword arguments. Each parameter has its own more detailed description below, but in short they are:</p> <ul class="simple"> <li> +<a class="reference internal" href="#prog">prog</a> - The name of the program (default: <code>os.path.basename(sys.argv[0])</code>)</li> <li> +<a class="reference internal" href="#usage">usage</a> - The string describing the program usage (default: generated from arguments added to parser)</li> <li> +<a class="reference internal" href="#description">description</a> - Text to display before the argument help (by default, no text)</li> <li> +<a class="reference internal" href="#epilog">epilog</a> - Text to display after the argument help (by default, no text)</li> <li> +<a class="reference internal" href="#parents">parents</a> - A list of <a class="reference internal" href="#argparse.ArgumentParser" title="argparse.ArgumentParser"><code>ArgumentParser</code></a> objects whose arguments should also be included</li> <li> +<a class="reference internal" href="#formatter-class">formatter_class</a> - A class for customizing the help output</li> <li> +<a class="reference internal" href="#prefix-chars">prefix_chars</a> - The set of characters that prefix optional arguments (default: ‘-‘)</li> <li> +<a class="reference internal" href="#fromfile-prefix-chars">fromfile_prefix_chars</a> - The set of characters that prefix files from which additional arguments should be read (default: <code>None</code>)</li> <li> +<a class="reference internal" href="#argument-default">argument_default</a> - The global default value for arguments (default: <code>None</code>)</li> <li> +<a class="reference internal" href="#conflict-handler">conflict_handler</a> - The strategy for resolving conflicting optionals (usually unnecessary)</li> <li> +<a class="reference internal" href="#add-help">add_help</a> - Add a <code>-h/--help</code> option to the parser (default: <code>True</code>)</li> <li> +<a class="reference internal" href="#allow-abbrev">allow_abbrev</a> - Allows long options to be abbreviated if the abbreviation is unambiguous. (default: <code>True</code>)</li> <li> +<a class="reference internal" href="#exit-on-error">exit_on_error</a> - Determines whether or not ArgumentParser exits with error info when an error occurs. (default: <code>True</code>)</li> </ul> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.5: </span><em>allow_abbrev</em> parameter was added.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.8: </span>In previous versions, <em>allow_abbrev</em> also disabled grouping of short flags such as <code>-vv</code> to mean <code>-v -v</code>.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.9: </span><em>exit_on_error</em> parameter was added.</p> </div> </dd> +</dl> <p>The following sections describe how each of these are used.</p> <section id="prog"> <span id="id1"></span><h3>prog</h3> <p>By default, <a class="reference internal" href="#argparse.ArgumentParser" title="argparse.ArgumentParser"><code>ArgumentParser</code></a> objects use <code>sys.argv[0]</code> to determine how to display the name of the program in help messages. This default is almost always desirable because it will make the help messages match how the program was invoked on the command line. For example, consider a file named <code>myprogram.py</code> with the following code:</p> <pre data-language="python">import argparse +parser = argparse.ArgumentParser() +parser.add_argument('--foo', help='foo help') +args = parser.parse_args() +</pre> <p>The help for this program will display <code>myprogram.py</code> as the program name (regardless of where the program was invoked from):</p> <pre data-language="shell">$ python myprogram.py --help +usage: myprogram.py [-h] [--foo FOO] + +options: + -h, --help show this help message and exit + --foo FOO foo help +$ cd .. +$ python subdir/myprogram.py --help +usage: myprogram.py [-h] [--foo FOO] + +options: + -h, --help show this help message and exit + --foo FOO foo help +</pre> <p>To change this default behavior, another value can be supplied using the <code>prog=</code> argument to <a class="reference internal" href="#argparse.ArgumentParser" title="argparse.ArgumentParser"><code>ArgumentParser</code></a>:</p> <pre data-language="python">>>> parser = argparse.ArgumentParser(prog='myprogram') +>>> parser.print_help() +usage: myprogram [-h] + +options: + -h, --help show this help message and exit +</pre> <p>Note that the program name, whether determined from <code>sys.argv[0]</code> or from the <code>prog=</code> argument, is available to help messages using the <code>%(prog)s</code> format specifier.</p> <pre data-language="python">>>> parser = argparse.ArgumentParser(prog='myprogram') +>>> parser.add_argument('--foo', help='foo of the %(prog)s program') +>>> parser.print_help() +usage: myprogram [-h] [--foo FOO] + +options: + -h, --help show this help message and exit + --foo FOO foo of the myprogram program +</pre> </section> <section id="usage"> <h3>usage</h3> <p>By default, <a class="reference internal" href="#argparse.ArgumentParser" title="argparse.ArgumentParser"><code>ArgumentParser</code></a> calculates the usage message from the arguments it contains:</p> <pre data-language="python">>>> parser = argparse.ArgumentParser(prog='PROG') +>>> parser.add_argument('--foo', nargs='?', help='foo help') +>>> parser.add_argument('bar', nargs='+', help='bar help') +>>> parser.print_help() +usage: PROG [-h] [--foo [FOO]] bar [bar ...] + +positional arguments: + bar bar help + +options: + -h, --help show this help message and exit + --foo [FOO] foo help +</pre> <p>The default message can be overridden with the <code>usage=</code> keyword argument:</p> <pre data-language="python">>>> parser = argparse.ArgumentParser(prog='PROG', usage='%(prog)s [options]') +>>> parser.add_argument('--foo', nargs='?', help='foo help') +>>> parser.add_argument('bar', nargs='+', help='bar help') +>>> parser.print_help() +usage: PROG [options] + +positional arguments: + bar bar help + +options: + -h, --help show this help message and exit + --foo [FOO] foo help +</pre> <p>The <code>%(prog)s</code> format specifier is available to fill in the program name in your usage messages.</p> </section> <section id="description"> <span id="id2"></span><h3>description</h3> <p>Most calls to the <a class="reference internal" href="#argparse.ArgumentParser" title="argparse.ArgumentParser"><code>ArgumentParser</code></a> constructor will use the <code>description=</code> keyword argument. This argument gives a brief description of what the program does and how it works. In help messages, the description is displayed between the command-line usage string and the help messages for the various arguments:</p> <pre data-language="python">>>> parser = argparse.ArgumentParser(description='A foo that bars') +>>> parser.print_help() +usage: argparse.py [-h] + +A foo that bars + +options: + -h, --help show this help message and exit +</pre> <p>By default, the description will be line-wrapped so that it fits within the given space. To change this behavior, see the <a class="reference internal" href="#formatter-class">formatter_class</a> argument.</p> </section> <section id="epilog"> <h3>epilog</h3> <p>Some programs like to display additional description of the program after the description of the arguments. Such text can be specified using the <code>epilog=</code> argument to <a class="reference internal" href="#argparse.ArgumentParser" title="argparse.ArgumentParser"><code>ArgumentParser</code></a>:</p> <pre data-language="python">>>> parser = argparse.ArgumentParser( +... description='A foo that bars', +... epilog="And that's how you'd foo a bar") +>>> parser.print_help() +usage: argparse.py [-h] + +A foo that bars + +options: + -h, --help show this help message and exit + +And that's how you'd foo a bar +</pre> <p>As with the <a class="reference internal" href="#description">description</a> argument, the <code>epilog=</code> text is by default line-wrapped, but this behavior can be adjusted with the <a class="reference internal" href="#formatter-class">formatter_class</a> argument to <a class="reference internal" href="#argparse.ArgumentParser" title="argparse.ArgumentParser"><code>ArgumentParser</code></a>.</p> </section> <section id="parents"> <h3>parents</h3> <p>Sometimes, several parsers share a common set of arguments. Rather than repeating the definitions of these arguments, a single parser with all the shared arguments and passed to <code>parents=</code> argument to <a class="reference internal" href="#argparse.ArgumentParser" title="argparse.ArgumentParser"><code>ArgumentParser</code></a> can be used. The <code>parents=</code> argument takes a list of <a class="reference internal" href="#argparse.ArgumentParser" title="argparse.ArgumentParser"><code>ArgumentParser</code></a> objects, collects all the positional and optional actions from them, and adds these actions to the <a class="reference internal" href="#argparse.ArgumentParser" title="argparse.ArgumentParser"><code>ArgumentParser</code></a> object being constructed:</p> <pre data-language="python">>>> parent_parser = argparse.ArgumentParser(add_help=False) +>>> parent_parser.add_argument('--parent', type=int) + +>>> foo_parser = argparse.ArgumentParser(parents=[parent_parser]) +>>> foo_parser.add_argument('foo') +>>> foo_parser.parse_args(['--parent', '2', 'XXX']) +Namespace(foo='XXX', parent=2) + +>>> bar_parser = argparse.ArgumentParser(parents=[parent_parser]) +>>> bar_parser.add_argument('--bar') +>>> bar_parser.parse_args(['--bar', 'YYY']) +Namespace(bar='YYY', parent=None) +</pre> <p>Note that most parent parsers will specify <code>add_help=False</code>. Otherwise, the <a class="reference internal" href="#argparse.ArgumentParser" title="argparse.ArgumentParser"><code>ArgumentParser</code></a> will see two <code>-h/--help</code> options (one in the parent and one in the child) and raise an error.</p> <div class="admonition note"> <p class="admonition-title">Note</p> <p>You must fully initialize the parsers before passing them via <code>parents=</code>. If you change the parent parsers after the child parser, those changes will not be reflected in the child.</p> </div> </section> <section id="formatter-class"> <span id="id3"></span><h3>formatter_class</h3> <p><a class="reference internal" href="#argparse.ArgumentParser" title="argparse.ArgumentParser"><code>ArgumentParser</code></a> objects allow the help formatting to be customized by specifying an alternate formatting class. Currently, there are four such classes:</p> <dl class="py class"> <dt class="sig sig-object py" id="argparse.RawDescriptionHelpFormatter"> +<code>class argparse.RawDescriptionHelpFormatter</code> </dt> <dt class="sig sig-object py" id="argparse.RawTextHelpFormatter"> +<code>class argparse.RawTextHelpFormatter</code> </dt> <dt class="sig sig-object py" id="argparse.ArgumentDefaultsHelpFormatter"> +<code>class argparse.ArgumentDefaultsHelpFormatter</code> </dt> <dt class="sig sig-object py" id="argparse.MetavarTypeHelpFormatter"> +<code>class argparse.MetavarTypeHelpFormatter</code> </dt> <dd></dd> +</dl> <p><a class="reference internal" href="#argparse.RawDescriptionHelpFormatter" title="argparse.RawDescriptionHelpFormatter"><code>RawDescriptionHelpFormatter</code></a> and <a class="reference internal" href="#argparse.RawTextHelpFormatter" title="argparse.RawTextHelpFormatter"><code>RawTextHelpFormatter</code></a> give more control over how textual descriptions are displayed. By default, <a class="reference internal" href="#argparse.ArgumentParser" title="argparse.ArgumentParser"><code>ArgumentParser</code></a> objects line-wrap the <a class="reference internal" href="#description">description</a> and <a class="reference internal" href="#epilog">epilog</a> texts in command-line help messages:</p> <pre data-language="python">>>> parser = argparse.ArgumentParser( +... prog='PROG', +... description='''this description +... was indented weird +... but that is okay''', +... epilog=''' +... likewise for this epilog whose whitespace will +... be cleaned up and whose words will be wrapped +... across a couple lines''') +>>> parser.print_help() +usage: PROG [-h] + +this description was indented weird but that is okay + +options: + -h, --help show this help message and exit + +likewise for this epilog whose whitespace will be cleaned up and whose words +will be wrapped across a couple lines +</pre> <p>Passing <a class="reference internal" href="#argparse.RawDescriptionHelpFormatter" title="argparse.RawDescriptionHelpFormatter"><code>RawDescriptionHelpFormatter</code></a> as <code>formatter_class=</code> indicates that <a class="reference internal" href="#description">description</a> and <a class="reference internal" href="#epilog">epilog</a> are already correctly formatted and should not be line-wrapped:</p> <pre data-language="python">>>> parser = argparse.ArgumentParser( +... prog='PROG', +... formatter_class=argparse.RawDescriptionHelpFormatter, +... description=textwrap.dedent('''\ +... Please do not mess up this text! +... -------------------------------- +... I have indented it +... exactly the way +... I want it +... ''')) +>>> parser.print_help() +usage: PROG [-h] + +Please do not mess up this text! +-------------------------------- + I have indented it + exactly the way + I want it + +options: + -h, --help show this help message and exit +</pre> <p><a class="reference internal" href="#argparse.RawTextHelpFormatter" title="argparse.RawTextHelpFormatter"><code>RawTextHelpFormatter</code></a> maintains whitespace for all sorts of help text, including argument descriptions. However, multiple new lines are replaced with one. If you wish to preserve multiple blank lines, add spaces between the newlines.</p> <p><a class="reference internal" href="#argparse.ArgumentDefaultsHelpFormatter" title="argparse.ArgumentDefaultsHelpFormatter"><code>ArgumentDefaultsHelpFormatter</code></a> automatically adds information about default values to each of the argument help messages:</p> <pre data-language="python">>>> parser = argparse.ArgumentParser( +... prog='PROG', +... formatter_class=argparse.ArgumentDefaultsHelpFormatter) +>>> parser.add_argument('--foo', type=int, default=42, help='FOO!') +>>> parser.add_argument('bar', nargs='*', default=[1, 2, 3], help='BAR!') +>>> parser.print_help() +usage: PROG [-h] [--foo FOO] [bar ...] + +positional arguments: + bar BAR! (default: [1, 2, 3]) + +options: + -h, --help show this help message and exit + --foo FOO FOO! (default: 42) +</pre> <p><a class="reference internal" href="#argparse.MetavarTypeHelpFormatter" title="argparse.MetavarTypeHelpFormatter"><code>MetavarTypeHelpFormatter</code></a> uses the name of the <a class="reference internal" href="#type">type</a> argument for each argument as the display name for its values (rather than using the <a class="reference internal" href="#dest">dest</a> as the regular formatter does):</p> <pre data-language="python">>>> parser = argparse.ArgumentParser( +... prog='PROG', +... formatter_class=argparse.MetavarTypeHelpFormatter) +>>> parser.add_argument('--foo', type=int) +>>> parser.add_argument('bar', type=float) +>>> parser.print_help() +usage: PROG [-h] [--foo int] float + +positional arguments: + float + +options: + -h, --help show this help message and exit + --foo int +</pre> </section> <section id="prefix-chars"> <h3>prefix_chars</h3> <p>Most command-line options will use <code>-</code> as the prefix, e.g. <code>-f/--foo</code>. Parsers that need to support different or additional prefix characters, e.g. for options like <code>+f</code> or <code>/foo</code>, may specify them using the <code>prefix_chars=</code> argument to the ArgumentParser constructor:</p> <pre data-language="python">>>> parser = argparse.ArgumentParser(prog='PROG', prefix_chars='-+') +>>> parser.add_argument('+f') +>>> parser.add_argument('++bar') +>>> parser.parse_args('+f X ++bar Y'.split()) +Namespace(bar='Y', f='X') +</pre> <p>The <code>prefix_chars=</code> argument defaults to <code>'-'</code>. Supplying a set of characters that does not include <code>-</code> will cause <code>-f/--foo</code> options to be disallowed.</p> </section> <section id="fromfile-prefix-chars"> <h3>fromfile_prefix_chars</h3> <p>Sometimes, when dealing with a particularly long argument list, it may make sense to keep the list of arguments in a file rather than typing it out at the command line. If the <code>fromfile_prefix_chars=</code> argument is given to the <a class="reference internal" href="#argparse.ArgumentParser" title="argparse.ArgumentParser"><code>ArgumentParser</code></a> constructor, then arguments that start with any of the specified characters will be treated as files, and will be replaced by the arguments they contain. For example:</p> <pre data-language="python">>>> with open('args.txt', 'w', encoding=sys.getfilesystemencoding()) as fp: +... fp.write('-f\nbar') +... +>>> parser = argparse.ArgumentParser(fromfile_prefix_chars='@') +>>> parser.add_argument('-f') +>>> parser.parse_args(['-f', 'foo', '@args.txt']) +Namespace(f='bar') +</pre> <p>Arguments read from a file must by default be one per line (but see also <a class="reference internal" href="#argparse.ArgumentParser.convert_arg_line_to_args" title="argparse.ArgumentParser.convert_arg_line_to_args"><code>convert_arg_line_to_args()</code></a>) and are treated as if they were in the same place as the original file referencing argument on the command line. So in the example above, the expression <code>['-f', 'foo', '@args.txt']</code> is considered equivalent to the expression <code>['-f', 'foo', '-f', 'bar']</code>.</p> <p><a class="reference internal" href="#argparse.ArgumentParser" title="argparse.ArgumentParser"><code>ArgumentParser</code></a> uses <a class="reference internal" href="../glossary#term-filesystem-encoding-and-error-handler"><span class="xref std std-term">filesystem encoding and error handler</span></a> to read the file containing arguments.</p> <p>The <code>fromfile_prefix_chars=</code> argument defaults to <code>None</code>, meaning that arguments will never be treated as file references.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.12: </span><a class="reference internal" href="#argparse.ArgumentParser" title="argparse.ArgumentParser"><code>ArgumentParser</code></a> changed encoding and errors to read arguments files from default (e.g. <a class="reference internal" href="locale#locale.getpreferredencoding" title="locale.getpreferredencoding"><code>locale.getpreferredencoding(False)</code></a> and <code>"strict"</code>) to <a class="reference internal" href="../glossary#term-filesystem-encoding-and-error-handler"><span class="xref std std-term">filesystem encoding and error handler</span></a>. Arguments file should be encoded in UTF-8 instead of ANSI Codepage on Windows.</p> </div> </section> <section id="argument-default"> <h3>argument_default</h3> <p>Generally, argument defaults are specified either by passing a default to <a class="reference internal" href="#argparse.ArgumentParser.add_argument" title="argparse.ArgumentParser.add_argument"><code>add_argument()</code></a> or by calling the <a class="reference internal" href="#argparse.ArgumentParser.set_defaults" title="argparse.ArgumentParser.set_defaults"><code>set_defaults()</code></a> methods with a specific set of name-value pairs. Sometimes however, it may be useful to specify a single parser-wide default for arguments. This can be accomplished by passing the <code>argument_default=</code> keyword argument to <a class="reference internal" href="#argparse.ArgumentParser" title="argparse.ArgumentParser"><code>ArgumentParser</code></a>. For example, to globally suppress attribute creation on <a class="reference internal" href="#argparse.ArgumentParser.parse_args" title="argparse.ArgumentParser.parse_args"><code>parse_args()</code></a> calls, we supply <code>argument_default=SUPPRESS</code>:</p> <pre data-language="python">>>> parser = argparse.ArgumentParser(argument_default=argparse.SUPPRESS) +>>> parser.add_argument('--foo') +>>> parser.add_argument('bar', nargs='?') +>>> parser.parse_args(['--foo', '1', 'BAR']) +Namespace(bar='BAR', foo='1') +>>> parser.parse_args([]) +Namespace() +</pre> </section> <section id="allow-abbrev"> <span id="id4"></span><h3>allow_abbrev</h3> <p>Normally, when you pass an argument list to the <a class="reference internal" href="#argparse.ArgumentParser.parse_args" title="argparse.ArgumentParser.parse_args"><code>parse_args()</code></a> method of an <a class="reference internal" href="#argparse.ArgumentParser" title="argparse.ArgumentParser"><code>ArgumentParser</code></a>, it <a class="reference internal" href="#prefix-matching"><span class="std std-ref">recognizes abbreviations</span></a> of long options.</p> <p>This feature can be disabled by setting <code>allow_abbrev</code> to <code>False</code>:</p> <pre data-language="python">>>> parser = argparse.ArgumentParser(prog='PROG', allow_abbrev=False) +>>> parser.add_argument('--foobar', action='store_true') +>>> parser.add_argument('--foonley', action='store_false') +>>> parser.parse_args(['--foon']) +usage: PROG [-h] [--foobar] [--foonley] +PROG: error: unrecognized arguments: --foon +</pre> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.5.</span></p> </div> </section> <section id="conflict-handler"> <h3>conflict_handler</h3> <p><a class="reference internal" href="#argparse.ArgumentParser" title="argparse.ArgumentParser"><code>ArgumentParser</code></a> objects do not allow two actions with the same option string. By default, <a class="reference internal" href="#argparse.ArgumentParser" title="argparse.ArgumentParser"><code>ArgumentParser</code></a> objects raise an exception if an attempt is made to create an argument with an option string that is already in use:</p> <pre data-language="python">>>> parser = argparse.ArgumentParser(prog='PROG') +>>> parser.add_argument('-f', '--foo', help='old foo help') +>>> parser.add_argument('--foo', help='new foo help') +Traceback (most recent call last): + .. +ArgumentError: argument --foo: conflicting option string(s): --foo +</pre> <p>Sometimes (e.g. when using <a class="reference internal" href="#parents">parents</a>) it may be useful to simply override any older arguments with the same option string. To get this behavior, the value <code>'resolve'</code> can be supplied to the <code>conflict_handler=</code> argument of <a class="reference internal" href="#argparse.ArgumentParser" title="argparse.ArgumentParser"><code>ArgumentParser</code></a>:</p> <pre data-language="python">>>> parser = argparse.ArgumentParser(prog='PROG', conflict_handler='resolve') +>>> parser.add_argument('-f', '--foo', help='old foo help') +>>> parser.add_argument('--foo', help='new foo help') +>>> parser.print_help() +usage: PROG [-h] [-f FOO] [--foo FOO] + +options: + -h, --help show this help message and exit + -f FOO old foo help + --foo FOO new foo help +</pre> <p>Note that <a class="reference internal" href="#argparse.ArgumentParser" title="argparse.ArgumentParser"><code>ArgumentParser</code></a> objects only remove an action if all of its option strings are overridden. So, in the example above, the old <code>-f/--foo</code> action is retained as the <code>-f</code> action, because only the <code>--foo</code> option string was overridden.</p> </section> <section id="add-help"> <h3>add_help</h3> <p>By default, ArgumentParser objects add an option which simply displays the parser’s help message. For example, consider a file named <code>myprogram.py</code> containing the following code:</p> <pre data-language="python">import argparse +parser = argparse.ArgumentParser() +parser.add_argument('--foo', help='foo help') +args = parser.parse_args() +</pre> <p>If <code>-h</code> or <code>--help</code> is supplied at the command line, the ArgumentParser help will be printed:</p> <pre data-language="shell">$ python myprogram.py --help +usage: myprogram.py [-h] [--foo FOO] + +options: + -h, --help show this help message and exit + --foo FOO foo help +</pre> <p>Occasionally, it may be useful to disable the addition of this help option. This can be achieved by passing <code>False</code> as the <code>add_help=</code> argument to <a class="reference internal" href="#argparse.ArgumentParser" title="argparse.ArgumentParser"><code>ArgumentParser</code></a>:</p> <pre data-language="python">>>> parser = argparse.ArgumentParser(prog='PROG', add_help=False) +>>> parser.add_argument('--foo', help='foo help') +>>> parser.print_help() +usage: PROG [--foo FOO] + +options: + --foo FOO foo help +</pre> <p>The help option is typically <code>-h/--help</code>. The exception to this is if the <code>prefix_chars=</code> is specified and does not include <code>-</code>, in which case <code>-h</code> and <code>--help</code> are not valid options. In this case, the first character in <code>prefix_chars</code> is used to prefix the help options:</p> <pre data-language="python">>>> parser = argparse.ArgumentParser(prog='PROG', prefix_chars='+/') +>>> parser.print_help() +usage: PROG [+h] + +options: + +h, ++help show this help message and exit +</pre> </section> <section id="exit-on-error"> <h3>exit_on_error</h3> <p>Normally, when you pass an invalid argument list to the <a class="reference internal" href="#argparse.ArgumentParser.parse_args" title="argparse.ArgumentParser.parse_args"><code>parse_args()</code></a> method of an <a class="reference internal" href="#argparse.ArgumentParser" title="argparse.ArgumentParser"><code>ArgumentParser</code></a>, it will exit with error info.</p> <p>If the user would like to catch errors manually, the feature can be enabled by setting <code>exit_on_error</code> to <code>False</code>:</p> <pre data-language="python">>>> parser = argparse.ArgumentParser(exit_on_error=False) +>>> parser.add_argument('--integers', type=int) +_StoreAction(option_strings=['--integers'], dest='integers', nargs=None, const=None, default=None, type=<class 'int'>, choices=None, help=None, metavar=None) +>>> try: +... parser.parse_args('--integers a'.split()) +... except argparse.ArgumentError: +... print('Catching an argumentError') +... +Catching an argumentError +</pre> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.9.</span></p> </div> </section> </section> <section id="the-add-argument-method"> <h2>The add_argument() method</h2> <dl class="py method"> <dt class="sig sig-object py" id="argparse.ArgumentParser.add_argument"> +<code>ArgumentParser.add_argument(name or flags...[, action][, nargs][, const][, default][, type][, choices][, required][, help][, metavar][, dest])</code> </dt> <dd> +<p>Define how a single command-line argument should be parsed. Each parameter has its own more detailed description below, but in short they are:</p> <ul class="simple"> <li> +<a class="reference internal" href="#id5">name or flags</a> - Either a name or a list of option strings, e.g. <code>foo</code> or <code>-f, --foo</code>.</li> <li> +<a class="reference internal" href="#action">action</a> - The basic type of action to be taken when this argument is encountered at the command line.</li> <li> +<a class="reference internal" href="#nargs">nargs</a> - The number of command-line arguments that should be consumed.</li> <li> +<a class="reference internal" href="#const">const</a> - A constant value required by some <a class="reference internal" href="#action">action</a> and <a class="reference internal" href="#nargs">nargs</a> selections.</li> <li> +<a class="reference internal" href="#default">default</a> - The value produced if the argument is absent from the command line and if it is absent from the namespace object.</li> <li> +<a class="reference internal" href="#type">type</a> - The type to which the command-line argument should be converted.</li> <li> +<a class="reference internal" href="#choices">choices</a> - A sequence of the allowable values for the argument.</li> <li> +<a class="reference internal" href="#required">required</a> - Whether or not the command-line option may be omitted (optionals only).</li> <li> +<a class="reference internal" href="#help">help</a> - A brief description of what the argument does.</li> <li> +<a class="reference internal" href="#metavar">metavar</a> - A name for the argument in usage messages.</li> <li> +<a class="reference internal" href="#dest">dest</a> - The name of the attribute to be added to the object returned by <a class="reference internal" href="#argparse.ArgumentParser.parse_args" title="argparse.ArgumentParser.parse_args"><code>parse_args()</code></a>.</li> </ul> </dd> +</dl> <p>The following sections describe how each of these are used.</p> <section id="name-or-flags"> <span id="id5"></span><h3>name or flags</h3> <p>The <a class="reference internal" href="#argparse.ArgumentParser.add_argument" title="argparse.ArgumentParser.add_argument"><code>add_argument()</code></a> method must know whether an optional argument, like <code>-f</code> or <code>--foo</code>, or a positional argument, like a list of filenames, is expected. The first arguments passed to <a class="reference internal" href="#argparse.ArgumentParser.add_argument" title="argparse.ArgumentParser.add_argument"><code>add_argument()</code></a> must therefore be either a series of flags, or a simple argument name.</p> <p>For example, an optional argument could be created like:</p> <pre data-language="python">>>> parser.add_argument('-f', '--foo') +</pre> <p>while a positional argument could be created like:</p> <pre data-language="python">>>> parser.add_argument('bar') +</pre> <p>When <a class="reference internal" href="#argparse.ArgumentParser.parse_args" title="argparse.ArgumentParser.parse_args"><code>parse_args()</code></a> is called, optional arguments will be identified by the <code>-</code> prefix, and the remaining arguments will be assumed to be positional:</p> <pre data-language="python">>>> parser = argparse.ArgumentParser(prog='PROG') +>>> parser.add_argument('-f', '--foo') +>>> parser.add_argument('bar') +>>> parser.parse_args(['BAR']) +Namespace(bar='BAR', foo=None) +>>> parser.parse_args(['BAR', '--foo', 'FOO']) +Namespace(bar='BAR', foo='FOO') +>>> parser.parse_args(['--foo', 'FOO']) +usage: PROG [-h] [-f FOO] bar +PROG: error: the following arguments are required: bar +</pre> </section> <section id="action"> <span id="id6"></span><h3>action</h3> <p><a class="reference internal" href="#argparse.ArgumentParser" title="argparse.ArgumentParser"><code>ArgumentParser</code></a> objects associate command-line arguments with actions. These actions can do just about anything with the command-line arguments associated with them, though most actions simply add an attribute to the object returned by <a class="reference internal" href="#argparse.ArgumentParser.parse_args" title="argparse.ArgumentParser.parse_args"><code>parse_args()</code></a>. The <code>action</code> keyword argument specifies how the command-line arguments should be handled. The supplied actions are:</p> <ul> <li> +<p><code>'store'</code> - This just stores the argument’s value. This is the default action. For example:</p> <pre data-language="python">>>> parser = argparse.ArgumentParser() +>>> parser.add_argument('--foo') +>>> parser.parse_args('--foo 1'.split()) +Namespace(foo='1') +</pre> </li> <li> +<p><code>'store_const'</code> - This stores the value specified by the <a class="reference internal" href="#const">const</a> keyword argument; note that the <a class="reference internal" href="#const">const</a> keyword argument defaults to <code>None</code>. The <code>'store_const'</code> action is most commonly used with optional arguments that specify some sort of flag. For example:</p> <pre data-language="python">>>> parser = argparse.ArgumentParser() +>>> parser.add_argument('--foo', action='store_const', const=42) +>>> parser.parse_args(['--foo']) +Namespace(foo=42) +</pre> </li> <li> +<p><code>'store_true'</code> and <code>'store_false'</code> - These are special cases of <code>'store_const'</code> used for storing the values <code>True</code> and <code>False</code> respectively. In addition, they create default values of <code>False</code> and <code>True</code> respectively. For example:</p> <pre data-language="python">>>> parser = argparse.ArgumentParser() +>>> parser.add_argument('--foo', action='store_true') +>>> parser.add_argument('--bar', action='store_false') +>>> parser.add_argument('--baz', action='store_false') +>>> parser.parse_args('--foo --bar'.split()) +Namespace(foo=True, bar=False, baz=True) +</pre> </li> <li> +<p><code>'append'</code> - This stores a list, and appends each argument value to the list. It is useful to allow an option to be specified multiple times. If the default value is non-empty, the default elements will be present in the parsed value for the option, with any values from the command line appended after those default values. Example usage:</p> <pre data-language="python">>>> parser = argparse.ArgumentParser() +>>> parser.add_argument('--foo', action='append') +>>> parser.parse_args('--foo 1 --foo 2'.split()) +Namespace(foo=['1', '2']) +</pre> </li> <li> +<p><code>'append_const'</code> - This stores a list, and appends the value specified by the <a class="reference internal" href="#const">const</a> keyword argument to the list; note that the <a class="reference internal" href="#const">const</a> keyword argument defaults to <code>None</code>. The <code>'append_const'</code> action is typically useful when multiple arguments need to store constants to the same list. For example:</p> <pre data-language="python">>>> parser = argparse.ArgumentParser() +>>> parser.add_argument('--str', dest='types', action='append_const', const=str) +>>> parser.add_argument('--int', dest='types', action='append_const', const=int) +>>> parser.parse_args('--str --int'.split()) +Namespace(types=[<class 'str'>, <class 'int'>]) +</pre> </li> <li> +<p><code>'count'</code> - This counts the number of times a keyword argument occurs. For example, this is useful for increasing verbosity levels:</p> <pre data-language="python">>>> parser = argparse.ArgumentParser() +>>> parser.add_argument('--verbose', '-v', action='count', default=0) +>>> parser.parse_args(['-vvv']) +Namespace(verbose=3) +</pre> <p>Note, the <em>default</em> will be <code>None</code> unless explicitly set to <em>0</em>.</p> </li> <li> +<code>'help'</code> - This prints a complete help message for all the options in the current parser and then exits. By default a help action is automatically added to the parser. See <a class="reference internal" href="#argparse.ArgumentParser" title="argparse.ArgumentParser"><code>ArgumentParser</code></a> for details of how the output is created.</li> <li> +<p><code>'version'</code> - This expects a <code>version=</code> keyword argument in the <a class="reference internal" href="#argparse.ArgumentParser.add_argument" title="argparse.ArgumentParser.add_argument"><code>add_argument()</code></a> call, and prints version information and exits when invoked:</p> <pre data-language="python">>>> import argparse +>>> parser = argparse.ArgumentParser(prog='PROG') +>>> parser.add_argument('--version', action='version', version='%(prog)s 2.0') +>>> parser.parse_args(['--version']) +PROG 2.0 +</pre> </li> <li> +<p><code>'extend'</code> - This stores a list, and extends each argument value to the list. Example usage:</p> <pre data-language="python">>>> parser = argparse.ArgumentParser() +>>> parser.add_argument("--foo", action="extend", nargs="+", type=str) +>>> parser.parse_args(["--foo", "f1", "--foo", "f2", "f3", "f4"]) +Namespace(foo=['f1', 'f2', 'f3', 'f4']) +</pre> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.8.</span></p> </div> </li> </ul> <p>You may also specify an arbitrary action by passing an Action subclass or other object that implements the same interface. The <code>BooleanOptionalAction</code> is available in <code>argparse</code> and adds support for boolean actions such as <code>--foo</code> and <code>--no-foo</code>:</p> <pre data-language="python">>>> import argparse +>>> parser = argparse.ArgumentParser() +>>> parser.add_argument('--foo', action=argparse.BooleanOptionalAction) +>>> parser.parse_args(['--no-foo']) +Namespace(foo=False) +</pre> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.9.</span></p> </div> <p>The recommended way to create a custom action is to extend <a class="reference internal" href="#argparse.Action" title="argparse.Action"><code>Action</code></a>, overriding the <code>__call__</code> method and optionally the <code>__init__</code> and <code>format_usage</code> methods.</p> <p>An example of a custom action:</p> <pre data-language="python">>>> class FooAction(argparse.Action): +... def __init__(self, option_strings, dest, nargs=None, **kwargs): +... if nargs is not None: +... raise ValueError("nargs not allowed") +... super().__init__(option_strings, dest, **kwargs) +... def __call__(self, parser, namespace, values, option_string=None): +... print('%r %r %r' % (namespace, values, option_string)) +... setattr(namespace, self.dest, values) +... +>>> parser = argparse.ArgumentParser() +>>> parser.add_argument('--foo', action=FooAction) +>>> parser.add_argument('bar', action=FooAction) +>>> args = parser.parse_args('1 --foo 2'.split()) +Namespace(bar=None, foo=None) '1' None +Namespace(bar='1', foo=None) '2' '--foo' +>>> args +Namespace(bar='1', foo='2') +</pre> <p>For more details, see <a class="reference internal" href="#argparse.Action" title="argparse.Action"><code>Action</code></a>.</p> </section> <section id="nargs"> <span id="id7"></span><h3>nargs</h3> <p>ArgumentParser objects usually associate a single command-line argument with a single action to be taken. The <code>nargs</code> keyword argument associates a different number of command-line arguments with a single action. See also <a class="reference internal" href="../howto/argparse#specifying-ambiguous-arguments"><span class="std std-ref">Specifying ambiguous arguments</span></a>. The supported values are:</p> <ul> <li> +<p><code>N</code> (an integer). <code>N</code> arguments from the command line will be gathered together into a list. For example:</p> <pre data-language="python">>>> parser = argparse.ArgumentParser() +>>> parser.add_argument('--foo', nargs=2) +>>> parser.add_argument('bar', nargs=1) +>>> parser.parse_args('c --foo a b'.split()) +Namespace(bar=['c'], foo=['a', 'b']) +</pre> <p>Note that <code>nargs=1</code> produces a list of one item. This is different from the default, in which the item is produced by itself.</p> </li> </ul> <ul id="index-0"> <li> +<p><code>'?'</code>. One argument will be consumed from the command line if possible, and produced as a single item. If no command-line argument is present, the value from <a class="reference internal" href="#default">default</a> will be produced. Note that for optional arguments, there is an additional case - the option string is present but not followed by a command-line argument. In this case the value from <a class="reference internal" href="#const">const</a> will be produced. Some examples to illustrate this:</p> <pre data-language="python">>>> parser = argparse.ArgumentParser() +>>> parser.add_argument('--foo', nargs='?', const='c', default='d') +>>> parser.add_argument('bar', nargs='?', default='d') +>>> parser.parse_args(['XX', '--foo', 'YY']) +Namespace(bar='XX', foo='YY') +>>> parser.parse_args(['XX', '--foo']) +Namespace(bar='XX', foo='c') +>>> parser.parse_args([]) +Namespace(bar='d', foo='d') +</pre> <p>One of the more common uses of <code>nargs='?'</code> is to allow optional input and output files:</p> <pre data-language="python">>>> parser = argparse.ArgumentParser() +>>> parser.add_argument('infile', nargs='?', type=argparse.FileType('r'), +... default=sys.stdin) +>>> parser.add_argument('outfile', nargs='?', type=argparse.FileType('w'), +... default=sys.stdout) +>>> parser.parse_args(['input.txt', 'output.txt']) +Namespace(infile=<_io.TextIOWrapper name='input.txt' encoding='UTF-8'>, + outfile=<_io.TextIOWrapper name='output.txt' encoding='UTF-8'>) +>>> parser.parse_args([]) +Namespace(infile=<_io.TextIOWrapper name='<stdin>' encoding='UTF-8'>, + outfile=<_io.TextIOWrapper name='<stdout>' encoding='UTF-8'>) +</pre> </li> </ul> <ul id="index-1"> <li> +<p><code>'*'</code>. All command-line arguments present are gathered into a list. Note that it generally doesn’t make much sense to have more than one positional argument with <code>nargs='*'</code>, but multiple optional arguments with <code>nargs='*'</code> is possible. For example:</p> <pre data-language="python">>>> parser = argparse.ArgumentParser() +>>> parser.add_argument('--foo', nargs='*') +>>> parser.add_argument('--bar', nargs='*') +>>> parser.add_argument('baz', nargs='*') +>>> parser.parse_args('a b --foo x y --bar 1 2'.split()) +Namespace(bar=['1', '2'], baz=['a', 'b'], foo=['x', 'y']) +</pre> </li> </ul> <ul id="index-2"> <li> +<p><code>'+'</code>. Just like <code>'*'</code>, all command-line args present are gathered into a list. Additionally, an error message will be generated if there wasn’t at least one command-line argument present. For example:</p> <pre data-language="python">>>> parser = argparse.ArgumentParser(prog='PROG') +>>> parser.add_argument('foo', nargs='+') +>>> parser.parse_args(['a', 'b']) +Namespace(foo=['a', 'b']) +>>> parser.parse_args([]) +usage: PROG [-h] foo [foo ...] +PROG: error: the following arguments are required: foo +</pre> </li> </ul> <p>If the <code>nargs</code> keyword argument is not provided, the number of arguments consumed is determined by the <a class="reference internal" href="#action">action</a>. Generally this means a single command-line argument will be consumed and a single item (not a list) will be produced.</p> </section> <section id="const"> <span id="id8"></span><h3>const</h3> <p>The <code>const</code> argument of <a class="reference internal" href="#argparse.ArgumentParser.add_argument" title="argparse.ArgumentParser.add_argument"><code>add_argument()</code></a> is used to hold constant values that are not read from the command line but are required for the various <a class="reference internal" href="#argparse.ArgumentParser" title="argparse.ArgumentParser"><code>ArgumentParser</code></a> actions. The two most common uses of it are:</p> <ul class="simple"> <li>When <a class="reference internal" href="#argparse.ArgumentParser.add_argument" title="argparse.ArgumentParser.add_argument"><code>add_argument()</code></a> is called with <code>action='store_const'</code> or <code>action='append_const'</code>. These actions add the <code>const</code> value to one of the attributes of the object returned by <a class="reference internal" href="#argparse.ArgumentParser.parse_args" title="argparse.ArgumentParser.parse_args"><code>parse_args()</code></a>. See the <a class="reference internal" href="#action">action</a> description for examples. If <code>const</code> is not provided to <a class="reference internal" href="#argparse.ArgumentParser.add_argument" title="argparse.ArgumentParser.add_argument"><code>add_argument()</code></a>, it will receive a default value of <code>None</code>.</li> <li>When <a class="reference internal" href="#argparse.ArgumentParser.add_argument" title="argparse.ArgumentParser.add_argument"><code>add_argument()</code></a> is called with option strings (like <code>-f</code> or <code>--foo</code>) and <code>nargs='?'</code>. This creates an optional argument that can be followed by zero or one command-line arguments. When parsing the command line, if the option string is encountered with no command-line argument following it, the value of <code>const</code> will be assumed to be <code>None</code> instead. See the <a class="reference internal" href="#nargs">nargs</a> description for examples.</li> </ul> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.11: </span><code>const=None</code> by default, including when <code>action='append_const'</code> or <code>action='store_const'</code>.</p> </div> </section> <section id="default"> <span id="id9"></span><h3>default</h3> <p>All optional arguments and some positional arguments may be omitted at the command line. The <code>default</code> keyword argument of <a class="reference internal" href="#argparse.ArgumentParser.add_argument" title="argparse.ArgumentParser.add_argument"><code>add_argument()</code></a>, whose value defaults to <code>None</code>, specifies what value should be used if the command-line argument is not present. For optional arguments, the <code>default</code> value is used when the option string was not present at the command line:</p> <pre data-language="python">>>> parser = argparse.ArgumentParser() +>>> parser.add_argument('--foo', default=42) +>>> parser.parse_args(['--foo', '2']) +Namespace(foo='2') +>>> parser.parse_args([]) +Namespace(foo=42) +</pre> <p>If the target namespace already has an attribute set, the action <em>default</em> will not over write it:</p> <pre data-language="python">>>> parser = argparse.ArgumentParser() +>>> parser.add_argument('--foo', default=42) +>>> parser.parse_args([], namespace=argparse.Namespace(foo=101)) +Namespace(foo=101) +</pre> <p>If the <code>default</code> value is a string, the parser parses the value as if it were a command-line argument. In particular, the parser applies any <a class="reference internal" href="#type">type</a> conversion argument, if provided, before setting the attribute on the <a class="reference internal" href="#argparse.Namespace" title="argparse.Namespace"><code>Namespace</code></a> return value. Otherwise, the parser uses the value as is:</p> <pre data-language="python">>>> parser = argparse.ArgumentParser() +>>> parser.add_argument('--length', default='10', type=int) +>>> parser.add_argument('--width', default=10.5, type=int) +>>> parser.parse_args() +Namespace(length=10, width=10.5) +</pre> <p>For positional arguments with <a class="reference internal" href="#nargs">nargs</a> equal to <code>?</code> or <code>*</code>, the <code>default</code> value is used when no command-line argument was present:</p> <pre data-language="python">>>> parser = argparse.ArgumentParser() +>>> parser.add_argument('foo', nargs='?', default=42) +>>> parser.parse_args(['a']) +Namespace(foo='a') +>>> parser.parse_args([]) +Namespace(foo=42) +</pre> <p>Providing <code>default=argparse.SUPPRESS</code> causes no attribute to be added if the command-line argument was not present:</p> <pre data-language="python">>>> parser = argparse.ArgumentParser() +>>> parser.add_argument('--foo', default=argparse.SUPPRESS) +>>> parser.parse_args([]) +Namespace() +>>> parser.parse_args(['--foo', '1']) +Namespace(foo='1') +</pre> </section> <section id="type"> <span id="argparse-type"></span><h3>type</h3> <p>By default, the parser reads command-line arguments in as simple strings. However, quite often the command-line string should instead be interpreted as another type, such as a <a class="reference internal" href="functions#float" title="float"><code>float</code></a> or <a class="reference internal" href="functions#int" title="int"><code>int</code></a>. The <code>type</code> keyword for <a class="reference internal" href="#argparse.ArgumentParser.add_argument" title="argparse.ArgumentParser.add_argument"><code>add_argument()</code></a> allows any necessary type-checking and type conversions to be performed.</p> <p>If the <a class="reference internal" href="#type">type</a> keyword is used with the <a class="reference internal" href="#default">default</a> keyword, the type converter is only applied if the default is a string.</p> <p>The argument to <code>type</code> can be any callable that accepts a single string. If the function raises <a class="reference internal" href="#argparse.ArgumentTypeError" title="argparse.ArgumentTypeError"><code>ArgumentTypeError</code></a>, <a class="reference internal" href="exceptions#TypeError" title="TypeError"><code>TypeError</code></a>, or <a class="reference internal" href="exceptions#ValueError" title="ValueError"><code>ValueError</code></a>, the exception is caught and a nicely formatted error message is displayed. No other exception types are handled.</p> <p>Common built-in types and functions can be used as type converters:</p> <pre data-language="python">import argparse +import pathlib + +parser = argparse.ArgumentParser() +parser.add_argument('count', type=int) +parser.add_argument('distance', type=float) +parser.add_argument('street', type=ascii) +parser.add_argument('code_point', type=ord) +parser.add_argument('source_file', type=open) +parser.add_argument('dest_file', type=argparse.FileType('w', encoding='latin-1')) +parser.add_argument('datapath', type=pathlib.Path) +</pre> <p>User defined functions can be used as well:</p> <pre data-language="pycon3">>>> def hyphenated(string): +... return '-'.join([word[:4] for word in string.casefold().split()]) +... +>>> parser = argparse.ArgumentParser() +>>> _ = parser.add_argument('short_title', type=hyphenated) +>>> parser.parse_args(['"The Tale of Two Cities"']) +Namespace(short_title='"the-tale-of-two-citi') +</pre> <p>The <a class="reference internal" href="functions#bool" title="bool"><code>bool()</code></a> function is not recommended as a type converter. All it does is convert empty strings to <code>False</code> and non-empty strings to <code>True</code>. This is usually not what is desired.</p> <p>In general, the <code>type</code> keyword is a convenience that should only be used for simple conversions that can only raise one of the three supported exceptions. Anything with more interesting error-handling or resource management should be done downstream after the arguments are parsed.</p> <p>For example, JSON or YAML conversions have complex error cases that require better reporting than can be given by the <code>type</code> keyword. A <a class="reference internal" href="json#json.JSONDecodeError" title="json.JSONDecodeError"><code>JSONDecodeError</code></a> would not be well formatted and a <a class="reference internal" href="exceptions#FileNotFoundError" title="FileNotFoundError"><code>FileNotFoundError</code></a> exception would not be handled at all.</p> <p>Even <a class="reference internal" href="#argparse.FileType" title="argparse.FileType"><code>FileType</code></a> has its limitations for use with the <code>type</code> keyword. If one argument uses <em>FileType</em> and then a subsequent argument fails, an error is reported but the file is not automatically closed. In this case, it would be better to wait until after the parser has run and then use the <a class="reference internal" href="../reference/compound_stmts#with"><code>with</code></a>-statement to manage the files.</p> <p>For type checkers that simply check against a fixed set of values, consider using the <a class="reference internal" href="#choices">choices</a> keyword instead.</p> </section> <section id="choices"> <span id="id10"></span><h3>choices</h3> <p>Some command-line arguments should be selected from a restricted set of values. These can be handled by passing a sequence object as the <em>choices</em> keyword argument to <a class="reference internal" href="#argparse.ArgumentParser.add_argument" title="argparse.ArgumentParser.add_argument"><code>add_argument()</code></a>. When the command line is parsed, argument values will be checked, and an error message will be displayed if the argument was not one of the acceptable values:</p> <pre data-language="python">>>> parser = argparse.ArgumentParser(prog='game.py') +>>> parser.add_argument('move', choices=['rock', 'paper', 'scissors']) +>>> parser.parse_args(['rock']) +Namespace(move='rock') +>>> parser.parse_args(['fire']) +usage: game.py [-h] {rock,paper,scissors} +game.py: error: argument move: invalid choice: 'fire' (choose from 'rock', +'paper', 'scissors') +</pre> <p>Note that inclusion in the <em>choices</em> sequence is checked after any <a class="reference internal" href="#type">type</a> conversions have been performed, so the type of the objects in the <em>choices</em> sequence should match the <a class="reference internal" href="#type">type</a> specified:</p> <pre data-language="python">>>> parser = argparse.ArgumentParser(prog='doors.py') +>>> parser.add_argument('door', type=int, choices=range(1, 4)) +>>> print(parser.parse_args(['3'])) +Namespace(door=3) +>>> parser.parse_args(['4']) +usage: doors.py [-h] {1,2,3} +doors.py: error: argument door: invalid choice: 4 (choose from 1, 2, 3) +</pre> <p>Any sequence can be passed as the <em>choices</em> value, so <a class="reference internal" href="stdtypes#list" title="list"><code>list</code></a> objects, <a class="reference internal" href="stdtypes#tuple" title="tuple"><code>tuple</code></a> objects, and custom sequences are all supported.</p> <p>Use of <a class="reference internal" href="enum#enum.Enum" title="enum.Enum"><code>enum.Enum</code></a> is not recommended because it is difficult to control its appearance in usage, help, and error messages.</p> <p>Formatted choices override the default <em>metavar</em> which is normally derived from <em>dest</em>. This is usually what you want because the user never sees the <em>dest</em> parameter. If this display isn’t desirable (perhaps because there are many choices), just specify an explicit <a class="reference internal" href="#metavar">metavar</a>.</p> </section> <section id="required"> <span id="id11"></span><h3>required</h3> <p>In general, the <a class="reference internal" href="#module-argparse" title="argparse: Command-line option and argument parsing library."><code>argparse</code></a> module assumes that flags like <code>-f</code> and <code>--bar</code> indicate <em>optional</em> arguments, which can always be omitted at the command line. To make an option <em>required</em>, <code>True</code> can be specified for the <code>required=</code> keyword argument to <a class="reference internal" href="#argparse.ArgumentParser.add_argument" title="argparse.ArgumentParser.add_argument"><code>add_argument()</code></a>:</p> <pre data-language="python">>>> parser = argparse.ArgumentParser() +>>> parser.add_argument('--foo', required=True) +>>> parser.parse_args(['--foo', 'BAR']) +Namespace(foo='BAR') +>>> parser.parse_args([]) +usage: [-h] --foo FOO +: error: the following arguments are required: --foo +</pre> <p>As the example shows, if an option is marked as <code>required</code>, <a class="reference internal" href="#argparse.ArgumentParser.parse_args" title="argparse.ArgumentParser.parse_args"><code>parse_args()</code></a> will report an error if that option is not present at the command line.</p> <div class="admonition note"> <p class="admonition-title">Note</p> <p>Required options are generally considered bad form because users expect <em>options</em> to be <em>optional</em>, and thus they should be avoided when possible.</p> </div> </section> <section id="help"> <span id="id12"></span><h3>help</h3> <p>The <code>help</code> value is a string containing a brief description of the argument. When a user requests help (usually by using <code>-h</code> or <code>--help</code> at the command line), these <code>help</code> descriptions will be displayed with each argument:</p> <pre data-language="python">>>> parser = argparse.ArgumentParser(prog='frobble') +>>> parser.add_argument('--foo', action='store_true', +... help='foo the bars before frobbling') +>>> parser.add_argument('bar', nargs='+', +... help='one of the bars to be frobbled') +>>> parser.parse_args(['-h']) +usage: frobble [-h] [--foo] bar [bar ...] + +positional arguments: + bar one of the bars to be frobbled + +options: + -h, --help show this help message and exit + --foo foo the bars before frobbling +</pre> <p>The <code>help</code> strings can include various format specifiers to avoid repetition of things like the program name or the argument <a class="reference internal" href="#default">default</a>. The available specifiers include the program name, <code>%(prog)s</code> and most keyword arguments to <a class="reference internal" href="#argparse.ArgumentParser.add_argument" title="argparse.ArgumentParser.add_argument"><code>add_argument()</code></a>, e.g. <code>%(default)s</code>, <code>%(type)s</code>, etc.:</p> <pre data-language="python">>>> parser = argparse.ArgumentParser(prog='frobble') +>>> parser.add_argument('bar', nargs='?', type=int, default=42, +... help='the bar to %(prog)s (default: %(default)s)') +>>> parser.print_help() +usage: frobble [-h] [bar] + +positional arguments: + bar the bar to frobble (default: 42) + +options: + -h, --help show this help message and exit +</pre> <p>As the help string supports %-formatting, if you want a literal <code>%</code> to appear in the help string, you must escape it as <code>%%</code>.</p> <p><a class="reference internal" href="#module-argparse" title="argparse: Command-line option and argument parsing library."><code>argparse</code></a> supports silencing the help entry for certain options, by setting the <code>help</code> value to <code>argparse.SUPPRESS</code>:</p> <pre data-language="python">>>> parser = argparse.ArgumentParser(prog='frobble') +>>> parser.add_argument('--foo', help=argparse.SUPPRESS) +>>> parser.print_help() +usage: frobble [-h] + +options: + -h, --help show this help message and exit +</pre> </section> <section id="metavar"> <span id="id13"></span><h3>metavar</h3> <p>When <a class="reference internal" href="#argparse.ArgumentParser" title="argparse.ArgumentParser"><code>ArgumentParser</code></a> generates help messages, it needs some way to refer to each expected argument. By default, ArgumentParser objects use the <a class="reference internal" href="#dest">dest</a> value as the “name” of each object. By default, for positional argument actions, the <a class="reference internal" href="#dest">dest</a> value is used directly, and for optional argument actions, the <a class="reference internal" href="#dest">dest</a> value is uppercased. So, a single positional argument with <code>dest='bar'</code> will be referred to as <code>bar</code>. A single optional argument <code>--foo</code> that should be followed by a single command-line argument will be referred to as <code>FOO</code>. An example:</p> <pre data-language="python">>>> parser = argparse.ArgumentParser() +>>> parser.add_argument('--foo') +>>> parser.add_argument('bar') +>>> parser.parse_args('X --foo Y'.split()) +Namespace(bar='X', foo='Y') +>>> parser.print_help() +usage: [-h] [--foo FOO] bar + +positional arguments: + bar + +options: + -h, --help show this help message and exit + --foo FOO +</pre> <p>An alternative name can be specified with <code>metavar</code>:</p> <pre data-language="python">>>> parser = argparse.ArgumentParser() +>>> parser.add_argument('--foo', metavar='YYY') +>>> parser.add_argument('bar', metavar='XXX') +>>> parser.parse_args('X --foo Y'.split()) +Namespace(bar='X', foo='Y') +>>> parser.print_help() +usage: [-h] [--foo YYY] XXX + +positional arguments: + XXX + +options: + -h, --help show this help message and exit + --foo YYY +</pre> <p>Note that <code>metavar</code> only changes the <em>displayed</em> name - the name of the attribute on the <a class="reference internal" href="#argparse.ArgumentParser.parse_args" title="argparse.ArgumentParser.parse_args"><code>parse_args()</code></a> object is still determined by the <a class="reference internal" href="#dest">dest</a> value.</p> <p>Different values of <code>nargs</code> may cause the metavar to be used multiple times. Providing a tuple to <code>metavar</code> specifies a different display for each of the arguments:</p> <pre data-language="python">>>> parser = argparse.ArgumentParser(prog='PROG') +>>> parser.add_argument('-x', nargs=2) +>>> parser.add_argument('--foo', nargs=2, metavar=('bar', 'baz')) +>>> parser.print_help() +usage: PROG [-h] [-x X X] [--foo bar baz] + +options: + -h, --help show this help message and exit + -x X X + --foo bar baz +</pre> </section> <section id="dest"> <span id="id14"></span><h3>dest</h3> <p>Most <a class="reference internal" href="#argparse.ArgumentParser" title="argparse.ArgumentParser"><code>ArgumentParser</code></a> actions add some value as an attribute of the object returned by <a class="reference internal" href="#argparse.ArgumentParser.parse_args" title="argparse.ArgumentParser.parse_args"><code>parse_args()</code></a>. The name of this attribute is determined by the <code>dest</code> keyword argument of <a class="reference internal" href="#argparse.ArgumentParser.add_argument" title="argparse.ArgumentParser.add_argument"><code>add_argument()</code></a>. For positional argument actions, <code>dest</code> is normally supplied as the first argument to <a class="reference internal" href="#argparse.ArgumentParser.add_argument" title="argparse.ArgumentParser.add_argument"><code>add_argument()</code></a>:</p> <pre data-language="python">>>> parser = argparse.ArgumentParser() +>>> parser.add_argument('bar') +>>> parser.parse_args(['XXX']) +Namespace(bar='XXX') +</pre> <p>For optional argument actions, the value of <code>dest</code> is normally inferred from the option strings. <a class="reference internal" href="#argparse.ArgumentParser" title="argparse.ArgumentParser"><code>ArgumentParser</code></a> generates the value of <code>dest</code> by taking the first long option string and stripping away the initial <code>--</code> string. If no long option strings were supplied, <code>dest</code> will be derived from the first short option string by stripping the initial <code>-</code> character. Any internal <code>-</code> characters will be converted to <code>_</code> characters to make sure the string is a valid attribute name. The examples below illustrate this behavior:</p> <pre data-language="python">>>> parser = argparse.ArgumentParser() +>>> parser.add_argument('-f', '--foo-bar', '--foo') +>>> parser.add_argument('-x', '-y') +>>> parser.parse_args('-f 1 -x 2'.split()) +Namespace(foo_bar='1', x='2') +>>> parser.parse_args('--foo 1 -y 2'.split()) +Namespace(foo_bar='1', x='2') +</pre> <p><code>dest</code> allows a custom attribute name to be provided:</p> <pre data-language="python">>>> parser = argparse.ArgumentParser() +>>> parser.add_argument('--foo', dest='bar') +>>> parser.parse_args('--foo XXX'.split()) +Namespace(bar='XXX') +</pre> </section> <section id="action-classes"> <h3>Action classes</h3> <p>Action classes implement the Action API, a callable which returns a callable which processes arguments from the command-line. Any object which follows this API may be passed as the <code>action</code> parameter to <a class="reference internal" href="#argparse.ArgumentParser.add_argument" title="argparse.ArgumentParser.add_argument"><code>add_argument()</code></a>.</p> <dl class="py class"> <dt class="sig sig-object py" id="argparse.Action"> +<code>class argparse.Action(option_strings, dest, nargs=None, const=None, default=None, type=None, choices=None, required=False, help=None, metavar=None)</code> </dt> <dd></dd> +</dl> <p>Action objects are used by an ArgumentParser to represent the information needed to parse a single argument from one or more strings from the command line. The Action class must accept the two positional arguments plus any keyword arguments passed to <a class="reference internal" href="#argparse.ArgumentParser.add_argument" title="argparse.ArgumentParser.add_argument"><code>ArgumentParser.add_argument()</code></a> except for the <code>action</code> itself.</p> <p>Instances of Action (or return value of any callable to the <code>action</code> parameter) should have attributes “dest”, “option_strings”, “default”, “type”, “required”, “help”, etc. defined. The easiest way to ensure these attributes are defined is to call <code>Action.__init__</code>.</p> <p>Action instances should be callable, so subclasses must override the <code>__call__</code> method, which should accept four parameters:</p> <ul class="simple"> <li> +<code>parser</code> - The ArgumentParser object which contains this action.</li> <li> +<code>namespace</code> - The <a class="reference internal" href="#argparse.Namespace" title="argparse.Namespace"><code>Namespace</code></a> object that will be returned by <a class="reference internal" href="#argparse.ArgumentParser.parse_args" title="argparse.ArgumentParser.parse_args"><code>parse_args()</code></a>. Most actions add an attribute to this object using <a class="reference internal" href="functions#setattr" title="setattr"><code>setattr()</code></a>.</li> <li> +<code>values</code> - The associated command-line arguments, with any type conversions applied. Type conversions are specified with the <a class="reference internal" href="#type">type</a> keyword argument to <a class="reference internal" href="#argparse.ArgumentParser.add_argument" title="argparse.ArgumentParser.add_argument"><code>add_argument()</code></a>.</li> <li> +<code>option_string</code> - The option string that was used to invoke this action. The <code>option_string</code> argument is optional, and will be absent if the action is associated with a positional argument.</li> </ul> <p>The <code>__call__</code> method may perform arbitrary actions, but will typically set attributes on the <code>namespace</code> based on <code>dest</code> and <code>values</code>.</p> <p>Action subclasses can define a <code>format_usage</code> method that takes no argument and return a string which will be used when printing the usage of the program. If such method is not provided, a sensible default will be used.</p> </section> </section> <section id="the-parse-args-method"> <h2>The parse_args() method</h2> <dl class="py method"> <dt class="sig sig-object py" id="argparse.ArgumentParser.parse_args"> +<code>ArgumentParser.parse_args(args=None, namespace=None)</code> </dt> <dd> +<p>Convert argument strings to objects and assign them as attributes of the namespace. Return the populated namespace.</p> <p>Previous calls to <a class="reference internal" href="#argparse.ArgumentParser.add_argument" title="argparse.ArgumentParser.add_argument"><code>add_argument()</code></a> determine exactly what objects are created and how they are assigned. See the documentation for <a class="reference internal" href="#argparse.ArgumentParser.add_argument" title="argparse.ArgumentParser.add_argument"><code>add_argument()</code></a> for details.</p> <ul class="simple"> <li> +<a class="reference internal" href="#args">args</a> - List of strings to parse. The default is taken from <a class="reference internal" href="sys#sys.argv" title="sys.argv"><code>sys.argv</code></a>.</li> <li> +<a class="reference internal" href="#namespace">namespace</a> - An object to take the attributes. The default is a new empty <a class="reference internal" href="#argparse.Namespace" title="argparse.Namespace"><code>Namespace</code></a> object.</li> </ul> </dd> +</dl> <section id="option-value-syntax"> <h3>Option value syntax</h3> <p>The <a class="reference internal" href="#argparse.ArgumentParser.parse_args" title="argparse.ArgumentParser.parse_args"><code>parse_args()</code></a> method supports several ways of specifying the value of an option (if it takes one). In the simplest case, the option and its value are passed as two separate arguments:</p> <pre data-language="python">>>> parser = argparse.ArgumentParser(prog='PROG') +>>> parser.add_argument('-x') +>>> parser.add_argument('--foo') +>>> parser.parse_args(['-x', 'X']) +Namespace(foo=None, x='X') +>>> parser.parse_args(['--foo', 'FOO']) +Namespace(foo='FOO', x=None) +</pre> <p>For long options (options with names longer than a single character), the option and value can also be passed as a single command-line argument, using <code>=</code> to separate them:</p> <pre data-language="python">>>> parser.parse_args(['--foo=FOO']) +Namespace(foo='FOO', x=None) +</pre> <p>For short options (options only one character long), the option and its value can be concatenated:</p> <pre data-language="python">>>> parser.parse_args(['-xX']) +Namespace(foo=None, x='X') +</pre> <p>Several short options can be joined together, using only a single <code>-</code> prefix, as long as only the last option (or none of them) requires a value:</p> <pre data-language="python">>>> parser = argparse.ArgumentParser(prog='PROG') +>>> parser.add_argument('-x', action='store_true') +>>> parser.add_argument('-y', action='store_true') +>>> parser.add_argument('-z') +>>> parser.parse_args(['-xyzZ']) +Namespace(x=True, y=True, z='Z') +</pre> </section> <section id="invalid-arguments"> <h3>Invalid arguments</h3> <p>While parsing the command line, <a class="reference internal" href="#argparse.ArgumentParser.parse_args" title="argparse.ArgumentParser.parse_args"><code>parse_args()</code></a> checks for a variety of errors, including ambiguous options, invalid types, invalid options, wrong number of positional arguments, etc. When it encounters such an error, it exits and prints the error along with a usage message:</p> <pre data-language="python">>>> parser = argparse.ArgumentParser(prog='PROG') +>>> parser.add_argument('--foo', type=int) +>>> parser.add_argument('bar', nargs='?') + +>>> # invalid type +>>> parser.parse_args(['--foo', 'spam']) +usage: PROG [-h] [--foo FOO] [bar] +PROG: error: argument --foo: invalid int value: 'spam' + +>>> # invalid option +>>> parser.parse_args(['--bar']) +usage: PROG [-h] [--foo FOO] [bar] +PROG: error: no such option: --bar + +>>> # wrong number of arguments +>>> parser.parse_args(['spam', 'badger']) +usage: PROG [-h] [--foo FOO] [bar] +PROG: error: extra arguments found: badger +</pre> </section> <section id="arguments-containing"> <h3>Arguments containing <code>-</code> +</h3> <p>The <a class="reference internal" href="#argparse.ArgumentParser.parse_args" title="argparse.ArgumentParser.parse_args"><code>parse_args()</code></a> method attempts to give errors whenever the user has clearly made a mistake, but some situations are inherently ambiguous. For example, the command-line argument <code>-1</code> could either be an attempt to specify an option or an attempt to provide a positional argument. The <a class="reference internal" href="#argparse.ArgumentParser.parse_args" title="argparse.ArgumentParser.parse_args"><code>parse_args()</code></a> method is cautious here: positional arguments may only begin with <code>-</code> if they look like negative numbers and there are no options in the parser that look like negative numbers:</p> <pre data-language="python">>>> parser = argparse.ArgumentParser(prog='PROG') +>>> parser.add_argument('-x') +>>> parser.add_argument('foo', nargs='?') + +>>> # no negative number options, so -1 is a positional argument +>>> parser.parse_args(['-x', '-1']) +Namespace(foo=None, x='-1') + +>>> # no negative number options, so -1 and -5 are positional arguments +>>> parser.parse_args(['-x', '-1', '-5']) +Namespace(foo='-5', x='-1') + +>>> parser = argparse.ArgumentParser(prog='PROG') +>>> parser.add_argument('-1', dest='one') +>>> parser.add_argument('foo', nargs='?') + +>>> # negative number options present, so -1 is an option +>>> parser.parse_args(['-1', 'X']) +Namespace(foo=None, one='X') + +>>> # negative number options present, so -2 is an option +>>> parser.parse_args(['-2']) +usage: PROG [-h] [-1 ONE] [foo] +PROG: error: no such option: -2 + +>>> # negative number options present, so both -1s are options +>>> parser.parse_args(['-1', '-1']) +usage: PROG [-h] [-1 ONE] [foo] +PROG: error: argument -1: expected one argument +</pre> <p>If you have positional arguments that must begin with <code>-</code> and don’t look like negative numbers, you can insert the pseudo-argument <code>'--'</code> which tells <a class="reference internal" href="#argparse.ArgumentParser.parse_args" title="argparse.ArgumentParser.parse_args"><code>parse_args()</code></a> that everything after that is a positional argument:</p> <pre data-language="python">>>> parser.parse_args(['--', '-f']) +Namespace(foo='-f', one=None) +</pre> <p>See also <a class="reference internal" href="../howto/argparse#specifying-ambiguous-arguments"><span class="std std-ref">the argparse howto on ambiguous arguments</span></a> for more details.</p> </section> <section id="argument-abbreviations-prefix-matching"> <span id="prefix-matching"></span><h3>Argument abbreviations (prefix matching)</h3> <p>The <a class="reference internal" href="#argparse.ArgumentParser.parse_args" title="argparse.ArgumentParser.parse_args"><code>parse_args()</code></a> method <a class="reference internal" href="#allow-abbrev"><span class="std std-ref">by default</span></a> allows long options to be abbreviated to a prefix, if the abbreviation is unambiguous (the prefix matches a unique option):</p> <pre data-language="python">>>> parser = argparse.ArgumentParser(prog='PROG') +>>> parser.add_argument('-bacon') +>>> parser.add_argument('-badger') +>>> parser.parse_args('-bac MMM'.split()) +Namespace(bacon='MMM', badger=None) +>>> parser.parse_args('-bad WOOD'.split()) +Namespace(bacon=None, badger='WOOD') +>>> parser.parse_args('-ba BA'.split()) +usage: PROG [-h] [-bacon BACON] [-badger BADGER] +PROG: error: ambiguous option: -ba could match -badger, -bacon +</pre> <p>An error is produced for arguments that could produce more than one options. This feature can be disabled by setting <a class="reference internal" href="#allow-abbrev"><span class="std std-ref">allow_abbrev</span></a> to <code>False</code>.</p> </section> <section id="beyond-sys-argv"> <span id="args"></span><h3>Beyond <code>sys.argv</code> +</h3> <p>Sometimes it may be useful to have an ArgumentParser parse arguments other than those of <a class="reference internal" href="sys#sys.argv" title="sys.argv"><code>sys.argv</code></a>. This can be accomplished by passing a list of strings to <a class="reference internal" href="#argparse.ArgumentParser.parse_args" title="argparse.ArgumentParser.parse_args"><code>parse_args()</code></a>. This is useful for testing at the interactive prompt:</p> <pre data-language="python">>>> parser = argparse.ArgumentParser() +>>> parser.add_argument( +... 'integers', metavar='int', type=int, choices=range(10), +... nargs='+', help='an integer in the range 0..9') +>>> parser.add_argument( +... '--sum', dest='accumulate', action='store_const', const=sum, +... default=max, help='sum the integers (default: find the max)') +>>> parser.parse_args(['1', '2', '3', '4']) +Namespace(accumulate=<built-in function max>, integers=[1, 2, 3, 4]) +>>> parser.parse_args(['1', '2', '3', '4', '--sum']) +Namespace(accumulate=<built-in function sum>, integers=[1, 2, 3, 4]) +</pre> </section> <section id="the-namespace-object"> <span id="namespace"></span><h3>The Namespace object</h3> <dl class="py class"> <dt class="sig sig-object py" id="argparse.Namespace"> +<code>class argparse.Namespace</code> </dt> <dd> +<p>Simple class used by default by <a class="reference internal" href="#argparse.ArgumentParser.parse_args" title="argparse.ArgumentParser.parse_args"><code>parse_args()</code></a> to create an object holding attributes and return it.</p> </dd> +</dl> <p>This class is deliberately simple, just an <a class="reference internal" href="functions#object" title="object"><code>object</code></a> subclass with a readable string representation. If you prefer to have dict-like view of the attributes, you can use the standard Python idiom, <a class="reference internal" href="functions#vars" title="vars"><code>vars()</code></a>:</p> <pre data-language="python">>>> parser = argparse.ArgumentParser() +>>> parser.add_argument('--foo') +>>> args = parser.parse_args(['--foo', 'BAR']) +>>> vars(args) +{'foo': 'BAR'} +</pre> <p>It may also be useful to have an <a class="reference internal" href="#argparse.ArgumentParser" title="argparse.ArgumentParser"><code>ArgumentParser</code></a> assign attributes to an already existing object, rather than a new <a class="reference internal" href="#argparse.Namespace" title="argparse.Namespace"><code>Namespace</code></a> object. This can be achieved by specifying the <code>namespace=</code> keyword argument:</p> <pre data-language="python">>>> class C: +... pass +... +>>> c = C() +>>> parser = argparse.ArgumentParser() +>>> parser.add_argument('--foo') +>>> parser.parse_args(args=['--foo', 'BAR'], namespace=c) +>>> c.foo +'BAR' +</pre> </section> </section> <section id="other-utilities"> <h2>Other utilities</h2> <section id="sub-commands"> <h3>Sub-commands</h3> <dl class="py method"> <dt class="sig sig-object py" id="argparse.ArgumentParser.add_subparsers"> +<code>ArgumentParser.add_subparsers([title][, description][, prog][, parser_class][, action][, option_strings][, dest][, required][, help][, metavar])</code> </dt> <dd> +<p>Many programs split up their functionality into a number of sub-commands, for example, the <code>svn</code> program can invoke sub-commands like <code>svn +checkout</code>, <code>svn update</code>, and <code>svn commit</code>. Splitting up functionality this way can be a particularly good idea when a program performs several different functions which require different kinds of command-line arguments. <a class="reference internal" href="#argparse.ArgumentParser" title="argparse.ArgumentParser"><code>ArgumentParser</code></a> supports the creation of such sub-commands with the <a class="reference internal" href="#argparse.ArgumentParser.add_subparsers" title="argparse.ArgumentParser.add_subparsers"><code>add_subparsers()</code></a> method. The <a class="reference internal" href="#argparse.ArgumentParser.add_subparsers" title="argparse.ArgumentParser.add_subparsers"><code>add_subparsers()</code></a> method is normally called with no arguments and returns a special action object. This object has a single method, <code>add_parser()</code>, which takes a command name and any <a class="reference internal" href="#argparse.ArgumentParser" title="argparse.ArgumentParser"><code>ArgumentParser</code></a> constructor arguments, and returns an <a class="reference internal" href="#argparse.ArgumentParser" title="argparse.ArgumentParser"><code>ArgumentParser</code></a> object that can be modified as usual.</p> <p>Description of parameters:</p> <ul class="simple"> <li>title - title for the sub-parser group in help output; by default “subcommands” if description is provided, otherwise uses title for positional arguments</li> <li>description - description for the sub-parser group in help output, by default <code>None</code> +</li> <li>prog - usage information that will be displayed with sub-command help, by default the name of the program and any positional arguments before the subparser argument</li> <li>parser_class - class which will be used to create sub-parser instances, by default the class of the current parser (e.g. ArgumentParser)</li> <li> +<a class="reference internal" href="#action">action</a> - the basic type of action to be taken when this argument is encountered at the command line</li> <li> +<a class="reference internal" href="#dest">dest</a> - name of the attribute under which sub-command name will be stored; by default <code>None</code> and no value is stored</li> <li> +<a class="reference internal" href="#required">required</a> - Whether or not a subcommand must be provided, by default <code>False</code> (added in 3.7)</li> <li> +<a class="reference internal" href="#help">help</a> - help for sub-parser group in help output, by default <code>None</code> +</li> <li> +<a class="reference internal" href="#metavar">metavar</a> - string presenting available sub-commands in help; by default it is <code>None</code> and presents sub-commands in form {cmd1, cmd2, ..}</li> </ul> <p>Some example usage:</p> <pre data-language="python">>>> # create the top-level parser +>>> parser = argparse.ArgumentParser(prog='PROG') +>>> parser.add_argument('--foo', action='store_true', help='foo help') +>>> subparsers = parser.add_subparsers(help='sub-command help') +>>> +>>> # create the parser for the "a" command +>>> parser_a = subparsers.add_parser('a', help='a help') +>>> parser_a.add_argument('bar', type=int, help='bar help') +>>> +>>> # create the parser for the "b" command +>>> parser_b = subparsers.add_parser('b', help='b help') +>>> parser_b.add_argument('--baz', choices='XYZ', help='baz help') +>>> +>>> # parse some argument lists +>>> parser.parse_args(['a', '12']) +Namespace(bar=12, foo=False) +>>> parser.parse_args(['--foo', 'b', '--baz', 'Z']) +Namespace(baz='Z', foo=True) +</pre> <p>Note that the object returned by <a class="reference internal" href="#argparse.ArgumentParser.parse_args" title="argparse.ArgumentParser.parse_args"><code>parse_args()</code></a> will only contain attributes for the main parser and the subparser that was selected by the command line (and not any other subparsers). So in the example above, when the <code>a</code> command is specified, only the <code>foo</code> and <code>bar</code> attributes are present, and when the <code>b</code> command is specified, only the <code>foo</code> and <code>baz</code> attributes are present.</p> <p>Similarly, when a help message is requested from a subparser, only the help for that particular parser will be printed. The help message will not include parent parser or sibling parser messages. (A help message for each subparser command, however, can be given by supplying the <code>help=</code> argument to <code>add_parser()</code> as above.)</p> <pre data-language="python">>>> parser.parse_args(['--help']) +usage: PROG [-h] [--foo] {a,b} ... + +positional arguments: + {a,b} sub-command help + a a help + b b help + +options: + -h, --help show this help message and exit + --foo foo help + +>>> parser.parse_args(['a', '--help']) +usage: PROG a [-h] bar + +positional arguments: + bar bar help + +options: + -h, --help show this help message and exit + +>>> parser.parse_args(['b', '--help']) +usage: PROG b [-h] [--baz {X,Y,Z}] + +options: + -h, --help show this help message and exit + --baz {X,Y,Z} baz help +</pre> <p>The <a class="reference internal" href="#argparse.ArgumentParser.add_subparsers" title="argparse.ArgumentParser.add_subparsers"><code>add_subparsers()</code></a> method also supports <code>title</code> and <code>description</code> keyword arguments. When either is present, the subparser’s commands will appear in their own group in the help output. For example:</p> <pre data-language="python">>>> parser = argparse.ArgumentParser() +>>> subparsers = parser.add_subparsers(title='subcommands', +... description='valid subcommands', +... help='additional help') +>>> subparsers.add_parser('foo') +>>> subparsers.add_parser('bar') +>>> parser.parse_args(['-h']) +usage: [-h] {foo,bar} ... + +options: + -h, --help show this help message and exit + +subcommands: + valid subcommands + + {foo,bar} additional help +</pre> <p>Furthermore, <code>add_parser</code> supports an additional <code>aliases</code> argument, which allows multiple strings to refer to the same subparser. This example, like <code>svn</code>, aliases <code>co</code> as a shorthand for <code>checkout</code>:</p> <pre data-language="python">>>> parser = argparse.ArgumentParser() +>>> subparsers = parser.add_subparsers() +>>> checkout = subparsers.add_parser('checkout', aliases=['co']) +>>> checkout.add_argument('foo') +>>> parser.parse_args(['co', 'bar']) +Namespace(foo='bar') +</pre> <p>One particularly effective way of handling sub-commands is to combine the use of the <a class="reference internal" href="#argparse.ArgumentParser.add_subparsers" title="argparse.ArgumentParser.add_subparsers"><code>add_subparsers()</code></a> method with calls to <a class="reference internal" href="#argparse.ArgumentParser.set_defaults" title="argparse.ArgumentParser.set_defaults"><code>set_defaults()</code></a> so that each subparser knows which Python function it should execute. For example:</p> <pre data-language="python">>>> # sub-command functions +>>> def foo(args): +... print(args.x * args.y) +... +>>> def bar(args): +... print('((%s))' % args.z) +... +>>> # create the top-level parser +>>> parser = argparse.ArgumentParser() +>>> subparsers = parser.add_subparsers(required=True) +>>> +>>> # create the parser for the "foo" command +>>> parser_foo = subparsers.add_parser('foo') +>>> parser_foo.add_argument('-x', type=int, default=1) +>>> parser_foo.add_argument('y', type=float) +>>> parser_foo.set_defaults(func=foo) +>>> +>>> # create the parser for the "bar" command +>>> parser_bar = subparsers.add_parser('bar') +>>> parser_bar.add_argument('z') +>>> parser_bar.set_defaults(func=bar) +>>> +>>> # parse the args and call whatever function was selected +>>> args = parser.parse_args('foo 1 -x 2'.split()) +>>> args.func(args) +2.0 +>>> +>>> # parse the args and call whatever function was selected +>>> args = parser.parse_args('bar XYZYX'.split()) +>>> args.func(args) +((XYZYX)) +</pre> <p>This way, you can let <a class="reference internal" href="#argparse.ArgumentParser.parse_args" title="argparse.ArgumentParser.parse_args"><code>parse_args()</code></a> do the job of calling the appropriate function after argument parsing is complete. Associating functions with actions like this is typically the easiest way to handle the different actions for each of your subparsers. However, if it is necessary to check the name of the subparser that was invoked, the <code>dest</code> keyword argument to the <a class="reference internal" href="#argparse.ArgumentParser.add_subparsers" title="argparse.ArgumentParser.add_subparsers"><code>add_subparsers()</code></a> call will work:</p> <pre data-language="python">>>> parser = argparse.ArgumentParser() +>>> subparsers = parser.add_subparsers(dest='subparser_name') +>>> subparser1 = subparsers.add_parser('1') +>>> subparser1.add_argument('-x') +>>> subparser2 = subparsers.add_parser('2') +>>> subparser2.add_argument('y') +>>> parser.parse_args(['2', 'frobble']) +Namespace(subparser_name='2', y='frobble') +</pre> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.7: </span>New <em>required</em> keyword argument.</p> </div> </dd> +</dl> </section> <section id="filetype-objects"> <h3>FileType objects</h3> <dl class="py class"> <dt class="sig sig-object py" id="argparse.FileType"> +<code>class argparse.FileType(mode='r', bufsize=- 1, encoding=None, errors=None)</code> </dt> <dd> +<p>The <a class="reference internal" href="#argparse.FileType" title="argparse.FileType"><code>FileType</code></a> factory creates objects that can be passed to the type argument of <a class="reference internal" href="#argparse.ArgumentParser.add_argument" title="argparse.ArgumentParser.add_argument"><code>ArgumentParser.add_argument()</code></a>. Arguments that have <a class="reference internal" href="#argparse.FileType" title="argparse.FileType"><code>FileType</code></a> objects as their type will open command-line arguments as files with the requested modes, buffer sizes, encodings and error handling (see the <a class="reference internal" href="functions#open" title="open"><code>open()</code></a> function for more details):</p> <pre data-language="python">>>> parser = argparse.ArgumentParser() +>>> parser.add_argument('--raw', type=argparse.FileType('wb', 0)) +>>> parser.add_argument('out', type=argparse.FileType('w', encoding='UTF-8')) +>>> parser.parse_args(['--raw', 'raw.dat', 'file.txt']) +Namespace(out=<_io.TextIOWrapper name='file.txt' mode='w' encoding='UTF-8'>, raw=<_io.FileIO name='raw.dat' mode='wb'>) +</pre> <p>FileType objects understand the pseudo-argument <code>'-'</code> and automatically convert this into <a class="reference internal" href="sys#sys.stdin" title="sys.stdin"><code>sys.stdin</code></a> for readable <a class="reference internal" href="#argparse.FileType" title="argparse.FileType"><code>FileType</code></a> objects and <a class="reference internal" href="sys#sys.stdout" title="sys.stdout"><code>sys.stdout</code></a> for writable <a class="reference internal" href="#argparse.FileType" title="argparse.FileType"><code>FileType</code></a> objects:</p> <pre data-language="python">>>> parser = argparse.ArgumentParser() +>>> parser.add_argument('infile', type=argparse.FileType('r')) +>>> parser.parse_args(['-']) +Namespace(infile=<_io.TextIOWrapper name='<stdin>' encoding='UTF-8'>) +</pre> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.4: </span>The <em>encodings</em> and <em>errors</em> keyword arguments.</p> </div> </dd> +</dl> </section> <section id="argument-groups"> <h3>Argument groups</h3> <dl class="py method"> <dt class="sig sig-object py" id="argparse.ArgumentParser.add_argument_group"> +<code>ArgumentParser.add_argument_group(title=None, description=None)</code> </dt> <dd> +<p>By default, <a class="reference internal" href="#argparse.ArgumentParser" title="argparse.ArgumentParser"><code>ArgumentParser</code></a> groups command-line arguments into “positional arguments” and “options” when displaying help messages. When there is a better conceptual grouping of arguments than this default one, appropriate groups can be created using the <a class="reference internal" href="#argparse.ArgumentParser.add_argument_group" title="argparse.ArgumentParser.add_argument_group"><code>add_argument_group()</code></a> method:</p> <pre data-language="python">>>> parser = argparse.ArgumentParser(prog='PROG', add_help=False) +>>> group = parser.add_argument_group('group') +>>> group.add_argument('--foo', help='foo help') +>>> group.add_argument('bar', help='bar help') +>>> parser.print_help() +usage: PROG [--foo FOO] bar + +group: + bar bar help + --foo FOO foo help +</pre> <p>The <a class="reference internal" href="#argparse.ArgumentParser.add_argument_group" title="argparse.ArgumentParser.add_argument_group"><code>add_argument_group()</code></a> method returns an argument group object which has an <a class="reference internal" href="#argparse.ArgumentParser.add_argument" title="argparse.ArgumentParser.add_argument"><code>add_argument()</code></a> method just like a regular <a class="reference internal" href="#argparse.ArgumentParser" title="argparse.ArgumentParser"><code>ArgumentParser</code></a>. When an argument is added to the group, the parser treats it just like a normal argument, but displays the argument in a separate group for help messages. The <a class="reference internal" href="#argparse.ArgumentParser.add_argument_group" title="argparse.ArgumentParser.add_argument_group"><code>add_argument_group()</code></a> method accepts <em>title</em> and <em>description</em> arguments which can be used to customize this display:</p> <pre data-language="python">>>> parser = argparse.ArgumentParser(prog='PROG', add_help=False) +>>> group1 = parser.add_argument_group('group1', 'group1 description') +>>> group1.add_argument('foo', help='foo help') +>>> group2 = parser.add_argument_group('group2', 'group2 description') +>>> group2.add_argument('--bar', help='bar help') +>>> parser.print_help() +usage: PROG [--bar BAR] foo + +group1: + group1 description + + foo foo help + +group2: + group2 description + + --bar BAR bar help +</pre> <p>Note that any arguments not in your user-defined groups will end up back in the usual “positional arguments” and “optional arguments” sections.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.11: </span>Calling <a class="reference internal" href="#argparse.ArgumentParser.add_argument_group" title="argparse.ArgumentParser.add_argument_group"><code>add_argument_group()</code></a> on an argument group is deprecated. This feature was never supported and does not always work correctly. The function exists on the API by accident through inheritance and will be removed in the future.</p> </div> </dd> +</dl> </section> <section id="mutual-exclusion"> <h3>Mutual exclusion</h3> <dl class="py method"> <dt class="sig sig-object py" id="argparse.ArgumentParser.add_mutually_exclusive_group"> +<code>ArgumentParser.add_mutually_exclusive_group(required=False)</code> </dt> <dd> +<p>Create a mutually exclusive group. <a class="reference internal" href="#module-argparse" title="argparse: Command-line option and argument parsing library."><code>argparse</code></a> will make sure that only one of the arguments in the mutually exclusive group was present on the command line:</p> <pre data-language="python">>>> parser = argparse.ArgumentParser(prog='PROG') +>>> group = parser.add_mutually_exclusive_group() +>>> group.add_argument('--foo', action='store_true') +>>> group.add_argument('--bar', action='store_false') +>>> parser.parse_args(['--foo']) +Namespace(bar=True, foo=True) +>>> parser.parse_args(['--bar']) +Namespace(bar=False, foo=False) +>>> parser.parse_args(['--foo', '--bar']) +usage: PROG [-h] [--foo | --bar] +PROG: error: argument --bar: not allowed with argument --foo +</pre> <p>The <a class="reference internal" href="#argparse.ArgumentParser.add_mutually_exclusive_group" title="argparse.ArgumentParser.add_mutually_exclusive_group"><code>add_mutually_exclusive_group()</code></a> method also accepts a <em>required</em> argument, to indicate that at least one of the mutually exclusive arguments is required:</p> <pre data-language="python">>>> parser = argparse.ArgumentParser(prog='PROG') +>>> group = parser.add_mutually_exclusive_group(required=True) +>>> group.add_argument('--foo', action='store_true') +>>> group.add_argument('--bar', action='store_false') +>>> parser.parse_args([]) +usage: PROG [-h] (--foo | --bar) +PROG: error: one of the arguments --foo --bar is required +</pre> <p>Note that currently mutually exclusive argument groups do not support the <em>title</em> and <em>description</em> arguments of <a class="reference internal" href="#argparse.ArgumentParser.add_argument_group" title="argparse.ArgumentParser.add_argument_group"><code>add_argument_group()</code></a>. However, a mutually exclusive group can be added to an argument group that has a title and description. For example:</p> <pre data-language="python">>>> parser = argparse.ArgumentParser(prog='PROG') +>>> group = parser.add_argument_group('Group title', 'Group description') +>>> exclusive_group = group.add_mutually_exclusive_group(required=True) +>>> exclusive_group.add_argument('--foo', help='foo help') +>>> exclusive_group.add_argument('--bar', help='bar help') +>>> parser.print_help() +usage: PROG [-h] (--foo FOO | --bar BAR) + +options: + -h, --help show this help message and exit + +Group title: + Group description + + --foo FOO foo help + --bar BAR bar help +</pre> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.11: </span>Calling <a class="reference internal" href="#argparse.ArgumentParser.add_argument_group" title="argparse.ArgumentParser.add_argument_group"><code>add_argument_group()</code></a> or <a class="reference internal" href="#argparse.ArgumentParser.add_mutually_exclusive_group" title="argparse.ArgumentParser.add_mutually_exclusive_group"><code>add_mutually_exclusive_group()</code></a> on a mutually exclusive group is deprecated. These features were never supported and do not always work correctly. The functions exist on the API by accident through inheritance and will be removed in the future.</p> </div> </dd> +</dl> </section> <section id="parser-defaults"> <h3>Parser defaults</h3> <dl class="py method"> <dt class="sig sig-object py" id="argparse.ArgumentParser.set_defaults"> +<code>ArgumentParser.set_defaults(**kwargs)</code> </dt> <dd> +<p>Most of the time, the attributes of the object returned by <a class="reference internal" href="#argparse.ArgumentParser.parse_args" title="argparse.ArgumentParser.parse_args"><code>parse_args()</code></a> will be fully determined by inspecting the command-line arguments and the argument actions. <a class="reference internal" href="#argparse.ArgumentParser.set_defaults" title="argparse.ArgumentParser.set_defaults"><code>set_defaults()</code></a> allows some additional attributes that are determined without any inspection of the command line to be added:</p> <pre data-language="python">>>> parser = argparse.ArgumentParser() +>>> parser.add_argument('foo', type=int) +>>> parser.set_defaults(bar=42, baz='badger') +>>> parser.parse_args(['736']) +Namespace(bar=42, baz='badger', foo=736) +</pre> <p>Note that parser-level defaults always override argument-level defaults:</p> <pre data-language="python">>>> parser = argparse.ArgumentParser() +>>> parser.add_argument('--foo', default='bar') +>>> parser.set_defaults(foo='spam') +>>> parser.parse_args([]) +Namespace(foo='spam') +</pre> <p>Parser-level defaults can be particularly useful when working with multiple parsers. See the <a class="reference internal" href="#argparse.ArgumentParser.add_subparsers" title="argparse.ArgumentParser.add_subparsers"><code>add_subparsers()</code></a> method for an example of this type.</p> </dd> +</dl> <dl class="py method"> <dt class="sig sig-object py" id="argparse.ArgumentParser.get_default"> +<code>ArgumentParser.get_default(dest)</code> </dt> <dd> +<p>Get the default value for a namespace attribute, as set by either <a class="reference internal" href="#argparse.ArgumentParser.add_argument" title="argparse.ArgumentParser.add_argument"><code>add_argument()</code></a> or by <a class="reference internal" href="#argparse.ArgumentParser.set_defaults" title="argparse.ArgumentParser.set_defaults"><code>set_defaults()</code></a>:</p> <pre data-language="python">>>> parser = argparse.ArgumentParser() +>>> parser.add_argument('--foo', default='badger') +>>> parser.get_default('foo') +'badger' +</pre> </dd> +</dl> </section> <section id="printing-help"> <h3>Printing help</h3> <p>In most typical applications, <a class="reference internal" href="#argparse.ArgumentParser.parse_args" title="argparse.ArgumentParser.parse_args"><code>parse_args()</code></a> will take care of formatting and printing any usage or error messages. However, several formatting methods are available:</p> <dl class="py method"> <dt class="sig sig-object py" id="argparse.ArgumentParser.print_usage"> +<code>ArgumentParser.print_usage(file=None)</code> </dt> <dd> +<p>Print a brief description of how the <a class="reference internal" href="#argparse.ArgumentParser" title="argparse.ArgumentParser"><code>ArgumentParser</code></a> should be invoked on the command line. If <em>file</em> is <code>None</code>, <a class="reference internal" href="sys#sys.stdout" title="sys.stdout"><code>sys.stdout</code></a> is assumed.</p> </dd> +</dl> <dl class="py method"> <dt class="sig sig-object py" id="argparse.ArgumentParser.print_help"> +<code>ArgumentParser.print_help(file=None)</code> </dt> <dd> +<p>Print a help message, including the program usage and information about the arguments registered with the <a class="reference internal" href="#argparse.ArgumentParser" title="argparse.ArgumentParser"><code>ArgumentParser</code></a>. If <em>file</em> is <code>None</code>, <a class="reference internal" href="sys#sys.stdout" title="sys.stdout"><code>sys.stdout</code></a> is assumed.</p> </dd> +</dl> <p>There are also variants of these methods that simply return a string instead of printing it:</p> <dl class="py method"> <dt class="sig sig-object py" id="argparse.ArgumentParser.format_usage"> +<code>ArgumentParser.format_usage()</code> </dt> <dd> +<p>Return a string containing a brief description of how the <a class="reference internal" href="#argparse.ArgumentParser" title="argparse.ArgumentParser"><code>ArgumentParser</code></a> should be invoked on the command line.</p> </dd> +</dl> <dl class="py method"> <dt class="sig sig-object py" id="argparse.ArgumentParser.format_help"> +<code>ArgumentParser.format_help()</code> </dt> <dd> +<p>Return a string containing a help message, including the program usage and information about the arguments registered with the <a class="reference internal" href="#argparse.ArgumentParser" title="argparse.ArgumentParser"><code>ArgumentParser</code></a>.</p> </dd> +</dl> </section> <section id="partial-parsing"> <h3>Partial parsing</h3> <dl class="py method"> <dt class="sig sig-object py" id="argparse.ArgumentParser.parse_known_args"> +<code>ArgumentParser.parse_known_args(args=None, namespace=None)</code> </dt> <dd></dd> +</dl> <p>Sometimes a script may only parse a few of the command-line arguments, passing the remaining arguments on to another script or program. In these cases, the <a class="reference internal" href="#argparse.ArgumentParser.parse_known_args" title="argparse.ArgumentParser.parse_known_args"><code>parse_known_args()</code></a> method can be useful. It works much like <a class="reference internal" href="#argparse.ArgumentParser.parse_args" title="argparse.ArgumentParser.parse_args"><code>parse_args()</code></a> except that it does not produce an error when extra arguments are present. Instead, it returns a two item tuple containing the populated namespace and the list of remaining argument strings.</p> <pre data-language="python">>>> parser = argparse.ArgumentParser() +>>> parser.add_argument('--foo', action='store_true') +>>> parser.add_argument('bar') +>>> parser.parse_known_args(['--foo', '--badger', 'BAR', 'spam']) +(Namespace(bar='BAR', foo=True), ['--badger', 'spam']) +</pre> <div class="admonition warning"> <p class="admonition-title">Warning</p> <p><a class="reference internal" href="#prefix-matching"><span class="std std-ref">Prefix matching</span></a> rules apply to <a class="reference internal" href="#argparse.ArgumentParser.parse_known_args" title="argparse.ArgumentParser.parse_known_args"><code>parse_known_args()</code></a>. The parser may consume an option even if it’s just a prefix of one of its known options, instead of leaving it in the remaining arguments list.</p> </div> </section> <section id="customizing-file-parsing"> <h3>Customizing file parsing</h3> <dl class="py method"> <dt class="sig sig-object py" id="argparse.ArgumentParser.convert_arg_line_to_args"> +<code>ArgumentParser.convert_arg_line_to_args(arg_line)</code> </dt> <dd> +<p>Arguments that are read from a file (see the <em>fromfile_prefix_chars</em> keyword argument to the <a class="reference internal" href="#argparse.ArgumentParser" title="argparse.ArgumentParser"><code>ArgumentParser</code></a> constructor) are read one argument per line. <a class="reference internal" href="#argparse.ArgumentParser.convert_arg_line_to_args" title="argparse.ArgumentParser.convert_arg_line_to_args"><code>convert_arg_line_to_args()</code></a> can be overridden for fancier reading.</p> <p>This method takes a single argument <em>arg_line</em> which is a string read from the argument file. It returns a list of arguments parsed from this string. The method is called once per line read from the argument file, in order.</p> <p>A useful override of this method is one that treats each space-separated word as an argument. The following example demonstrates how to do this:</p> <pre data-language="python">class MyArgumentParser(argparse.ArgumentParser): + def convert_arg_line_to_args(self, arg_line): + return arg_line.split() +</pre> </dd> +</dl> </section> <section id="exiting-methods"> <h3>Exiting methods</h3> <dl class="py method"> <dt class="sig sig-object py" id="argparse.ArgumentParser.exit"> +<code>ArgumentParser.exit(status=0, message=None)</code> </dt> <dd> +<p>This method terminates the program, exiting with the specified <em>status</em> and, if given, it prints a <em>message</em> before that. The user can override this method to handle these steps differently:</p> <pre data-language="python">class ErrorCatchingArgumentParser(argparse.ArgumentParser): + def exit(self, status=0, message=None): + if status: + raise Exception(f'Exiting because of an error: {message}') + exit(status) +</pre> </dd> +</dl> <dl class="py method"> <dt class="sig sig-object py" id="argparse.ArgumentParser.error"> +<code>ArgumentParser.error(message)</code> </dt> <dd> +<p>This method prints a usage message including the <em>message</em> to the standard error and terminates the program with a status code of 2.</p> </dd> +</dl> </section> <section id="intermixed-parsing"> <h3>Intermixed parsing</h3> <dl class="py method"> <dt class="sig sig-object py" id="argparse.ArgumentParser.parse_intermixed_args"> +<code>ArgumentParser.parse_intermixed_args(args=None, namespace=None)</code> </dt> <dd></dd> +</dl> <dl class="py method"> <dt class="sig sig-object py" id="argparse.ArgumentParser.parse_known_intermixed_args"> +<code>ArgumentParser.parse_known_intermixed_args(args=None, namespace=None)</code> </dt> <dd></dd> +</dl> <p>A number of Unix commands allow the user to intermix optional arguments with positional arguments. The <a class="reference internal" href="#argparse.ArgumentParser.parse_intermixed_args" title="argparse.ArgumentParser.parse_intermixed_args"><code>parse_intermixed_args()</code></a> and <a class="reference internal" href="#argparse.ArgumentParser.parse_known_intermixed_args" title="argparse.ArgumentParser.parse_known_intermixed_args"><code>parse_known_intermixed_args()</code></a> methods support this parsing style.</p> <p>These parsers do not support all the argparse features, and will raise exceptions if unsupported features are used. In particular, subparsers, and mutually exclusive groups that include both optionals and positionals are not supported.</p> <p>The following example shows the difference between <a class="reference internal" href="#argparse.ArgumentParser.parse_known_args" title="argparse.ArgumentParser.parse_known_args"><code>parse_known_args()</code></a> and <a class="reference internal" href="#argparse.ArgumentParser.parse_intermixed_args" title="argparse.ArgumentParser.parse_intermixed_args"><code>parse_intermixed_args()</code></a>: the former returns <code>['2', +'3']</code> as unparsed arguments, while the latter collects all the positionals into <code>rest</code>.</p> <pre data-language="python">>>> parser = argparse.ArgumentParser() +>>> parser.add_argument('--foo') +>>> parser.add_argument('cmd') +>>> parser.add_argument('rest', nargs='*', type=int) +>>> parser.parse_known_args('doit 1 --foo bar 2 3'.split()) +(Namespace(cmd='doit', foo='bar', rest=[1]), ['2', '3']) +>>> parser.parse_intermixed_args('doit 1 --foo bar 2 3'.split()) +Namespace(cmd='doit', foo='bar', rest=[1, 2, 3]) +</pre> <p><a class="reference internal" href="#argparse.ArgumentParser.parse_known_intermixed_args" title="argparse.ArgumentParser.parse_known_intermixed_args"><code>parse_known_intermixed_args()</code></a> returns a two item tuple containing the populated namespace and the list of remaining argument strings. <a class="reference internal" href="#argparse.ArgumentParser.parse_intermixed_args" title="argparse.ArgumentParser.parse_intermixed_args"><code>parse_intermixed_args()</code></a> raises an error if there are any remaining unparsed argument strings.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.7.</span></p> </div> </section> </section> <section id="upgrading-optparse-code"> <span id="id15"></span><h2>Upgrading optparse code</h2> <p>Originally, the <a class="reference internal" href="#module-argparse" title="argparse: Command-line option and argument parsing library."><code>argparse</code></a> module had attempted to maintain compatibility with <a class="reference internal" href="optparse#module-optparse" title="optparse: Command-line option parsing library. (deprecated)"><code>optparse</code></a>. However, <a class="reference internal" href="optparse#module-optparse" title="optparse: Command-line option parsing library. (deprecated)"><code>optparse</code></a> was difficult to extend transparently, particularly with the changes required to support the new <code>nargs=</code> specifiers and better usage messages. When most everything in <a class="reference internal" href="optparse#module-optparse" title="optparse: Command-line option parsing library. (deprecated)"><code>optparse</code></a> had either been copy-pasted over or monkey-patched, it no longer seemed practical to try to maintain the backwards compatibility.</p> <p>The <a class="reference internal" href="#module-argparse" title="argparse: Command-line option and argument parsing library."><code>argparse</code></a> module improves on the standard library <a class="reference internal" href="optparse#module-optparse" title="optparse: Command-line option parsing library. (deprecated)"><code>optparse</code></a> module in a number of ways including:</p> <ul class="simple"> <li>Handling positional arguments.</li> <li>Supporting sub-commands.</li> <li>Allowing alternative option prefixes like <code>+</code> and <code>/</code>.</li> <li>Handling zero-or-more and one-or-more style arguments.</li> <li>Producing more informative usage messages.</li> <li>Providing a much simpler interface for custom <code>type</code> and <code>action</code>.</li> </ul> <p>A partial upgrade path from <a class="reference internal" href="optparse#module-optparse" title="optparse: Command-line option parsing library. (deprecated)"><code>optparse</code></a> to <a class="reference internal" href="#module-argparse" title="argparse: Command-line option and argument parsing library."><code>argparse</code></a>:</p> <ul class="simple"> <li>Replace all <a class="reference internal" href="optparse#optparse.OptionParser.add_option" title="optparse.OptionParser.add_option"><code>optparse.OptionParser.add_option()</code></a> calls with <a class="reference internal" href="#argparse.ArgumentParser.add_argument" title="argparse.ArgumentParser.add_argument"><code>ArgumentParser.add_argument()</code></a> calls.</li> <li>Replace <code>(options, args) = parser.parse_args()</code> with <code>args = +parser.parse_args()</code> and add additional <a class="reference internal" href="#argparse.ArgumentParser.add_argument" title="argparse.ArgumentParser.add_argument"><code>ArgumentParser.add_argument()</code></a> calls for the positional arguments. Keep in mind that what was previously called <code>options</code>, now in the <a class="reference internal" href="#module-argparse" title="argparse: Command-line option and argument parsing library."><code>argparse</code></a> context is called <code>args</code>.</li> <li>Replace <a class="reference internal" href="optparse#optparse.OptionParser.disable_interspersed_args" title="optparse.OptionParser.disable_interspersed_args"><code>optparse.OptionParser.disable_interspersed_args()</code></a> by using <a class="reference internal" href="#argparse.ArgumentParser.parse_intermixed_args" title="argparse.ArgumentParser.parse_intermixed_args"><code>parse_intermixed_args()</code></a> instead of <a class="reference internal" href="#argparse.ArgumentParser.parse_args" title="argparse.ArgumentParser.parse_args"><code>parse_args()</code></a>.</li> <li>Replace callback actions and the <code>callback_*</code> keyword arguments with <code>type</code> or <code>action</code> arguments.</li> <li>Replace string names for <code>type</code> keyword arguments with the corresponding type objects (e.g. int, float, complex, etc).</li> <li>Replace <a class="reference internal" href="optparse#optparse.Values" title="optparse.Values"><code>optparse.Values</code></a> with <a class="reference internal" href="#argparse.Namespace" title="argparse.Namespace"><code>Namespace</code></a> and <a class="reference internal" href="optparse#optparse.OptionError" title="optparse.OptionError"><code>optparse.OptionError</code></a> and <a class="reference internal" href="optparse#optparse.OptionValueError" title="optparse.OptionValueError"><code>optparse.OptionValueError</code></a> with <a class="reference internal" href="#argparse.ArgumentError" title="argparse.ArgumentError"><code>ArgumentError</code></a>.</li> <li>Replace strings with implicit arguments such as <code>%default</code> or <code>%prog</code> with the standard Python syntax to use dictionaries to format strings, that is, <code>%(default)s</code> and <code>%(prog)s</code>.</li> <li>Replace the OptionParser constructor <code>version</code> argument with a call to <code>parser.add_argument('--version', action='version', version='<the version>')</code>.</li> </ul> </section> <section id="exceptions"> <h2>Exceptions</h2> <dl class="py exception"> <dt class="sig sig-object py" id="argparse.ArgumentError"> +<code>exception argparse.ArgumentError</code> </dt> <dd> +<p>An error from creating or using an argument (optional or positional).</p> <p>The string value of this exception is the message, augmented with information about the argument that caused it.</p> </dd> +</dl> <dl class="py exception"> <dt class="sig sig-object py" id="argparse.ArgumentTypeError"> +<code>exception argparse.ArgumentTypeError</code> </dt> <dd> +<p>Raised when something goes wrong converting a command line string to a type.</p> </dd> +</dl> </section> <div class="_attribution"> + <p class="_attribution-p"> + © 2001–2023 Python Software Foundation<br>Licensed under the PSF License.<br> + <a href="https://docs.python.org/3.12/library/argparse.html" class="_attribution-link">https://docs.python.org/3.12/library/argparse.html</a> + </p> +</div> |
