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