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