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