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