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