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