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