| 1 | # Argument Processing |
| 2 | |
| 3 | `cmd2` makes it easy to add sophisticated argument processing to your commands using the |
| 4 | [argparse](https://docs.python.org/3/library/argparse.html) python module. `cmd2` handles the |
| 5 | following for you: |
| 6 | |
| 7 | 1. Parsing input and quoted strings in a manner similar to how POSIX shells do it |
| 8 | 1. Parse the resulting argument list using an instance of |
| 9 | [Cmd2ArgumentParser](https://docs.python.org/3/library/argparse.html#argparse.ArgumentParser) |
| 10 | that you provide |
| 11 | 1. Passes the resulting |
| 12 | [argparse.Namespace](https://docs.python.org/3/library/argparse.html#argparse.Namespace) object |
| 13 | to your command function. The `Namespace` includes the [Statement][cmd2.Statement] object that |
| 14 | was created when parsing the command line. It is accessible via the `cmd2_statement` attribute on |
| 15 | the `Namespace`. |
| 16 | 1. Adds the usage message from the argument parser to your command's help. |
| 17 | 1. Checks if the `-h/--help` option is present, and if so, displays the help message for the command |
| 18 | |
| 19 | These features are provided by two decorators: |
| 20 | |
| 21 | - [@with_argparser][cmd2.with_argparser] -- build parsers manually with `add_argument()` calls |
| 22 | - [@with_annotated][cmd2.with_annotated] -- build parsers automatically from type hints |
| 23 | |
| 24 | See the |
| 25 | [argparse_completion](https://github.com/python-cmd2/cmd2/blob/main/examples/argparse_completion.py) |
| 26 | and [annotated_example](https://github.com/python-cmd2/cmd2/blob/main/examples/annotated_example.py) |
| 27 | examples to compare the two styles side by side. |
| 28 | |
| 29 | `cmd2` provides the following [decorators](../api/decorators.md) for assisting with parsing |
| 30 | arguments passed to commands: |
| 31 | |
| 32 | - [cmd2.decorators.with_argparser][] |
| 33 | - [cmd2.annotated.with_annotated][] |
| 34 | - [cmd2.decorators.with_argument_list][] |
| 35 | |
| 36 | All of these decorators accept an optional **preserve_quotes** argument which defaults to `False`. |
| 37 | Setting this argument to `True` is useful for cases where you are passing the arguments to another |
| 38 | command which might have its own argument parsing. |
| 39 | |
| 40 | ## with_argparser decorator |
| 41 | |
| 42 | The [@with_argparser][cmd2.with_argparser] decorator can accept the following for its first |
| 43 | argument: |
| 44 | |
| 45 | 1. An existing instance of `Cmd2ArgumentParser` |
| 46 | 2. A function or static method which returns an instance of `Cmd2ArgumentParser` |
| 47 | 3. Cmd or CommandSet class method which returns an instance of `Cmd2ArgumentParser` |
| 48 | |
| 49 | In all cases the `@with_argparser` decorator creates a deep copy of the parser instance which it |
| 50 | stores internally. A consequence is that parsers don't need to be unique across commands. |
| 51 | |
| 52 | !!! warning |
| 53 | |
| 54 | Since the `@with_argparser` decorator is making a deep-copy of the parser provided, if you wish |
| 55 | to dynamically modify this parser at a later time, you need to retrieve this deep copy. This can |
| 56 | be done using `self.command_parsers.get(self.do_commandname)`. |
| 57 | |
| 58 | ## with_annotated decorator |
| 59 | |
| 60 | !!! warning "Experimental" |
| 61 | |
| 62 | The `@with_annotated` decorator is **experimental** and its API may change in future releases. |
| 63 | |
| 64 | The [@with_annotated][cmd2.with_annotated] decorator builds an argparse parser automatically from |
| 65 | the decorated function's type annotations -- no manual `add_argument()` calls required. See |
| 66 | [Annotated Argument Processing](annotated.md) for the full reference, including type mapping, |
| 67 | metadata classes, subcommands, and stability caveats. |
| 68 | |
| 69 | ## Argument Parsing |
| 70 | |
| 71 | For each command in the `cmd2.Cmd` subclass which requires argument parsing, create an instance of |
| 72 | `Cmd2ArgumentParser` which can parse the input appropriately for the command (or provide a |
| 73 | function/method that returns such a parser). Then decorate the command method with the |
| 74 | `@with_argparser` decorator, passing the argument parser as the first parameter to the decorator. |
| 75 | This changes the second argument of the command method, which will contain the results of |
| 76 | `Cmd2ArgumentParser.parse_args()`. |
| 77 | |
| 78 | Here's what it looks like: |
| 79 | |
| 80 | ```py |
| 81 | from cmd2 import Cmd2ArgumentParser, with_argparser |
| 82 | |
| 83 | argparser = Cmd2ArgumentParser() |
| 84 | argparser.add_argument('-p', '--piglatin', action='store_true', help='atinLay') |
| 85 | argparser.add_argument('-s', '--shout', action='store_true', help='N00B EMULATION MODE') |
| 86 | argparser.add_argument('-r', '--repeat', type=int, help='output [n] times') |
| 87 | argparser.add_argument('word', nargs='?', help='word to say') |
| 88 | |
| 89 | @with_argparser(argparser) |
| 90 | def do_speak(self, opts): |
| 91 | """Repeats what you tell me to.""" |
| 92 | arg = opts.word |
| 93 | if opts.piglatin: |
| 94 | arg = '%s%say' % (arg[1:], arg[0]) |
| 95 | if opts.shout: |
| 96 | arg = arg.upper() |
| 97 | repetitions = opts.repeat or 1 |
| 98 | for i in range(min(repetitions, self.maxrepeats)): |
| 99 | self.poutput(arg) |
| 100 | ``` |
| 101 | |
| 102 | !!! note |
| 103 | |
| 104 | `cmd2` sets the `prog` variable in the argument parser based on the name of the method it is decorating. |
| 105 | This will override anything you specify in `prog` variable when creating the argument parser. |
| 106 | |
| 107 | As of the 3.0.0 release, `cmd2` sets `prog` when the instance-specific parser is created, which is later |
| 108 | than in previous versions. |
| 109 | |
| 110 | ## Help Messages |
| 111 | |
| 112 | By default, `cmd2` uses the docstring of the command method when a user asks for help on the |
| 113 | command. When you use the `@with_argparser` decorator, the docstring for the `do_*` method is used |
| 114 | to set the description for the `Cmd2ArgumentParser`. |
| 115 | |
| 116 | !!! tip "description and epilog fields are rich objects" |
| 117 | |
| 118 | While the `help` field is simply a string, both the `description` and `epilog` fields can accept any |
| 119 | [rich](https://github.com/Textualize/rich) renderable. This allows you to include all of rich's |
| 120 | built-in objects like `Text`, `Table`, and `Markdown`. |
| 121 | |
| 122 | With this code: |
| 123 | |
| 124 | ```py |
| 125 | from cmd2 import Cmd2ArgumentParser, with_argparser |
| 126 | |
| 127 | argparser = Cmd2ArgumentParser() |
| 128 | argparser.add_argument('tag', help='tag') |
| 129 | argparser.add_argument('content', nargs='+', help='content to surround with tag') |
| 130 | @with_argparser(argparser) |
| 131 | def do_tag(self, args): |
| 132 | """Create an HTML tag""" |
| 133 | self.stdout.write('<{0}>{1}</{0}>'.format(args.tag, ' '.join(args.content))) |
| 134 | self.stdout.write('\n') |
| 135 | ``` |
| 136 | |
| 137 | the `help tag` command displays: |
| 138 | |
| 139 | ```text |
| 140 | usage: tag [-h] tag content [content ...] |
| 141 | |
| 142 | Create an HTML tag |
| 143 | |
| 144 | positional arguments: |
| 145 | tag tag |
| 146 | content content to surround with tag |
| 147 | |
| 148 | optional arguments: |
| 149 | -h, --help show this help message and exit |
| 150 | ``` |
| 151 | |
| 152 | If you would prefer, you can set the `description` while instantiating the `Cmd2ArgumentParser` and |
| 153 | leave the docstring on your method blank: |
| 154 | |
| 155 | ```py |
| 156 | from cmd2 import Cmd2ArgumentParser, with_argparser |
| 157 | |
| 158 | argparser = Cmd2ArgumentParser(description='create an HTML tag') |
| 159 | argparser.add_argument('tag', help='tag') |
| 160 | argparser.add_argument('content', nargs='+', help='content to surround with tag') |
| 161 | @with_argparser(argparser) |
| 162 | def do_tag(self, args): |
| 163 | self.stdout.write('<{0}>{1}</{0}>'.format(args.tag, ' '.join(args.content))) |
| 164 | self.stdout.write('\n') |
| 165 | ``` |
| 166 | |
| 167 | Now when the user enters `help tag` they see: |
| 168 | |
| 169 | ```text |
| 170 | usage: tag [-h] tag content [content ...] |
| 171 | |
| 172 | create an HTML tag |
| 173 | |
| 174 | positional arguments: |
| 175 | tag tag |
| 176 | content content to surround with tag |
| 177 | |
| 178 | optional arguments: |
| 179 | -h, --help show this help message and exit |
| 180 | ``` |
| 181 | |
| 182 | To add additional text to the end of the generated help message, use the `epilog` variable: |
| 183 | |
| 184 | ```py |
| 185 | from cmd2 import Cmd2ArgumentParser, with_argparser |
| 186 | |
| 187 | argparser = Cmd2ArgumentParser(description='create an HTML tag', |
| 188 | epilog='This command cannot generate tags with no content, like <br/>.') |
| 189 | argparser.add_argument('tag', help='tag') |
| 190 | argparser.add_argument('content', nargs='+', help='content to surround with tag') |
| 191 | @with_argparser(argparser) |
| 192 | def do_tag(self, args): |
| 193 | self.stdout.write('<{0}>{1}</{0}>'.format(args.tag, ' '.join(args.content))) |
| 194 | self.stdout.write('\n') |
| 195 | ``` |
| 196 | |
| 197 | Which yields: |
| 198 | |
| 199 | ```text |
| 200 | usage: tag [-h] tag content [content ...] |
| 201 | |
| 202 | create an HTML tag |
| 203 | |
| 204 | positional arguments: |
| 205 | tag tag |
| 206 | content content to surround with tag |
| 207 | |
| 208 | optional arguments: |
| 209 | -h, --help show this help message and exit |
| 210 | |
| 211 | This command cannot generate tags with no content, like <br/> |
| 212 | ``` |
| 213 | |
| 214 | !!! warning |
| 215 | |
| 216 | If a command **foo** is decorated with `cmd2`'s `with_argparse` decorator, then **help_foo** will not be |
| 217 | invoked when `help foo` is called. The [argparse](https://docs.python.org/3/library/argparse.html) module |
| 218 | provides a rich API which can be used to tweak every aspect of the displayed help and we encourage `cmd2` |
| 219 | developers to utilize that. |
| 220 | |
| 221 | ### Argparse HelpFormatter classes |
| 222 | |
| 223 | `cmd2` has 5 different Argparse HelpFormatter classes, all of which are based on the |
| 224 | `RichHelpFormatter` class from [rich-argparse](https://github.com/hamdanal/rich-argparse). The |
| 225 | benefit is that your `cmd2` applications now have more aesthetically pleasing help which includes |
| 226 | color to make it quicker and easier to visually parse help text. This works for all supported |
| 227 | versions of Python. |
| 228 | |
| 229 | - [Cmd2HelpFormatter][cmd2.argparse_utils.Cmd2HelpFormatter] - default help formatter class |
| 230 | - [ArgumentDefaultsCmd2HelpFormatter][cmd2.argparse_utils.ArgumentDefaultsCmd2HelpFormatter] - adds |
| 231 | default values to argument help |
| 232 | - [MetavarTypeCmd2HelpFormatter][cmd2.argparse_utils.MetavarTypeCmd2HelpFormatter] - uses the |
| 233 | argument 'type' as the default metavar value (instead of the argument 'dest') |
| 234 | - [RawDescriptionCmd2HelpFormatter][cmd2.argparse_utils.RawDescriptionCmd2HelpFormatter] - retains |
| 235 | any formatting in descriptions and epilogs |
| 236 | - [RawTextCmd2HelpFormatter][cmd2.argparse_utils.RawTextCmd2HelpFormatter] - retains formatting of |
| 237 | all help text |
| 238 | |
| 239 | The default `Cmd2HelpFormatter` class inherits from `argparse.HelpFormatter`. If you want a |
| 240 | different behavior, then pass the desired class to the `formatter_class` argument of your argparse |
| 241 | parser, e.g. `formatter_class=ArgumentDefaultsCmd2HelpFormatter` to your parser. |
| 242 | |
| 243 | ## Argument List |
| 244 | |
| 245 | The default behavior of `cmd2` is to pass the user input directly to your `do_*` methods as a |
| 246 | string. The object passed to your method is actually a [Statement][cmd2.Statement] object, which has |
| 247 | additional attributes that may be helpful, including `arg_list` and `argv`: |
| 248 | |
| 249 | ```py |
| 250 | class CmdLineApp(cmd2.Cmd): |
| 251 | """ Example cmd2 application. """ |
| 252 | |
| 253 | def do_say(self, statement): |
| 254 | # statement contains a string |
| 255 | self.poutput(statement) |
| 256 | |
| 257 | def do_speak(self, statement): |
| 258 | # statement also has a list of arguments |
| 259 | # quoted arguments remain quoted |
| 260 | for arg in statement.arg_list: |
| 261 | self.poutput(arg) |
| 262 | |
| 263 | def do_articulate(self, statement): |
| 264 | # statement.argv contains the command |
| 265 | # and the arguments, which have had quotes |
| 266 | # stripped |
| 267 | for arg in statement.argv: |
| 268 | self.poutput(arg) |
| 269 | ``` |
| 270 | |
| 271 | If you don't want to access the additional attributes on the string passed to your `do_*` method you |
| 272 | can still have `cmd2` apply shell parsing rules to the user input and pass you a list of arguments |
| 273 | instead of a string. Apply the [@with_argument_list][cmd2.with_argument_list] decorator to those |
| 274 | methods that should receive an argument list instead of a string: |
| 275 | |
| 276 | ```py |
| 277 | from cmd2 import with_argument_list |
| 278 | |
| 279 | class CmdLineApp(cmd2.Cmd): |
| 280 | """ Example cmd2 application. """ |
| 281 | |
| 282 | def do_say(self, cmdline): |
| 283 | # cmdline contains a string |
| 284 | pass |
| 285 | |
| 286 | @with_argument_list |
| 287 | def do_speak(self, arglist): |
| 288 | # arglist contains a list of arguments |
| 289 | pass |
| 290 | ``` |
| 291 | |
| 292 | ## Unknown Positional Arguments |
| 293 | |
| 294 | To pass all unknown arguments to your command as a list of strings, then decorate the command method |
| 295 | with the `@with_argparser(..., with_unknown_args=True)` decorator. |
| 296 | |
| 297 | Here's what it looks like: |
| 298 | |
| 299 | ```py |
| 300 | from cmd2 import Cmd2ArgumentParser, with_argparser |
| 301 | |
| 302 | dir_parser = Cmd2ArgumentParser() |
| 303 | dir_parser.add_argument('-l', '--long', action='store_true', |
| 304 | help="display in long format with one item per line") |
| 305 | |
| 306 | @with_argparser(dir_parser, with_unknown_args=True) |
| 307 | def do_dir(self, args, unknown): |
| 308 | """List contents of current directory.""" |
| 309 | # No arguments for this command |
| 310 | if unknown: |
| 311 | self.perror("dir does not take any positional arguments:") |
| 312 | self.do_help('dir') |
| 313 | self.last_result = 'Bad arguments' |
| 314 | return |
| 315 | |
| 316 | # Get the contents as a list |
| 317 | contents = os.listdir(self.cwd) |
| 318 | |
| 319 | ... |
| 320 | ``` |
| 321 | |
| 322 | ## Using A Custom Namespace |
| 323 | |
| 324 | In some cases, it may be necessary to write custom `argparse` code that is dependent on your |
| 325 | application's state data. To support this ability while still allowing use of the decorators, |
| 326 | `@with_argparser` has an optional argument called `ns_provider`. |
| 327 | |
| 328 | `ns_provider` is a Callable that accepts a `cmd2.Cmd` object as an argument and returns an |
| 329 | `argparse.Namespace`: |
| 330 | |
| 331 | ```py |
| 332 | Callable[[cmd2.Cmd], argparse.Namespace] |
| 333 | ``` |
| 334 | |
| 335 | For example: |
| 336 | |
| 337 | ```py |
| 338 | def settings_ns_provider(self) -> argparse.Namespace: |
| 339 | """Populate an argparse Namespace with current settings""" |
| 340 | ns = argparse.Namespace() |
| 341 | ns.app_settings = self.settings |
| 342 | return ns |
| 343 | ``` |
| 344 | |
| 345 | To use this function with the `@with_argparser` decorator, do the following: |
| 346 | |
| 347 | ```py |
| 348 | @with_argparser(my_parser, ns_provider=settings_ns_provider) |
| 349 | ``` |
| 350 | |
| 351 | The Namespace is passed by the decorators to the `argparse` parsing functions, giving your custom |
| 352 | code access to the state data it needs for its parsing logic. |
| 353 | |
| 354 | ## Subcommands |
| 355 | |
| 356 | Subcommands are supported for commands using the `@with_argparser` decorator. The syntax is based on |
| 357 | argparse sub-parsers. |
| 358 | |
| 359 | You may add multiple layers of subcommands for your command. `cmd2` will automatically traverse and |
| 360 | tab complete subcommands for all commands using argparse. |
| 361 | |
| 362 | See the |
| 363 | [argparse_example](https://github.com/python-cmd2/cmd2/blob/main/examples/argparse_example.py) |
| 364 | example to learn more about how to use subcommands in your `cmd2` application. |
| 365 | |
| 366 | The [@as_subcommand_to][cmd2.as_subcommand_to] decorator makes adding subcommands easy. |
| 367 | |
| 368 | ## Argparse Extensions |
| 369 | |
| 370 | `cmd2` augments the standard `argparse.nargs` with range tuple capability: |
| 371 | |
| 372 | - `nargs=(5,)` - accept 5 or more items |
| 373 | - `nargs=(8, 12)` - accept 8 to 12 items |
| 374 | |
| 375 | `cmd2` also provides the [Cmd2ArgumentParser][cmd2.Cmd2ArgumentParser] class which inherits from |
| 376 | `argparse.ArgumentParser` and improves error and help output. |
| 377 | |
| 378 | ## Decorator Order |
| 379 | |
| 380 | If you are using custom decorators in combination with `@cmd2.with_argparser`, then the order of |
| 381 | your custom decorator(s) relative to the `cmd2` decorator affects runtime behavior and `argparse` |
| 382 | errors. There is nothing `cmd2`-specific here, this is just a side-effect of how decorators work in |
| 383 | Python. To learn more about how decorators work, see |
| 384 | [decorator_primer](https://realpython.com/primer-on-python-decorators). |
| 385 | |
| 386 | If you want your custom decorator's runtime behavior to occur in the case of an `argparse` error, |
| 387 | then that decorator needs to go **after** the `argparse` one, e.g.: |
| 388 | |
| 389 | ```py |
| 390 | @cmd2.with_argparser(foo_parser) |
| 391 | @my_decorator |
| 392 | def do_foo(self, args: argparse.Namespace) -> None: |
| 393 | """foo docs""" |
| 394 | pass |
| 395 | ``` |
| 396 | |
| 397 | However, if you do NOT want the custom decorator runtime behavior to occur during an `argparse` |
| 398 | error, then that decorator needs to go **before** the `argparse` one, e.g.: |
| 399 | |
| 400 | ```py |
| 401 | @my_decorator |
| 402 | @cmd2.with_argparser(bar_parser) |
| 403 | def do_bar(self, args: argparse.Namespace) -> None: |
| 404 | """bar docs""" |
| 405 | pass |
| 406 | ``` |
| 407 | |
| 408 | The [help_categories](https://github.com/python-cmd2/cmd2/blob/main/examples/help_categories.py) |
| 409 | example demonstrates both above cases in a concrete fashion. |
| 410 | |
| 411 | ## Reserved Argument Names |
| 412 | |
| 413 | `cmd2`'s `@with_argparser` decorator adds the following attributes to argparse Namespaces. To avoid |
| 414 | naming collisions, do not use any of these names for your argparse arguments. |
| 415 | |
| 416 | - `cmd2_statement` - [cmd2.Statement][] object that was created when parsing the command line. |
| 417 | - `cmd2_subcommand_func` - subcommand handler function or `None` if one was not set. |