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