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