| 1 | # Scripting |
| 2 | |
| 3 | Operating system shells have long been able to execute a sequence of commands saved in a text file. |
| 4 | These script files simplify the repeated execution of long command sequences. `cmd2` supports two |
| 5 | similar mechanisms: command scripts and python scripts. |
| 6 | |
| 7 | ## Command Scripts |
| 8 | |
| 9 | A command script contains a sequence of commands typed at the prompt of a `cmd2` based application. |
| 10 | Unlike operating system shell scripts, command scripts can't contain logic or loops. |
| 11 | |
| 12 | ### Creating Command Scripts |
| 13 | |
| 14 | Command scripts can be created in several ways: |
| 15 | |
| 16 | - creating a text file using any method of your choice |
| 17 | - using the built-in [edit](./builtin_commands.md#edit) command to create or edit an existing text |
| 18 | file |
| 19 | - saving previously entered commands to a script file using [history -s](./history.md#for-users) |
| 20 | |
| 21 | If you create a text file from scratch, just include one command per line, exactly as you would type |
| 22 | it inside a `cmd2` application. |
| 23 | |
| 24 | ### Running Command Scripts |
| 25 | |
| 26 | Command script files can be executed using the built-in |
| 27 | [run_script](./builtin_commands.md#run_script) command or the `@` shortcut (if your application is |
| 28 | using the default shortcuts). Both ASCII and UTF-8 encoded Unicode text files are supported. The |
| 29 | [run_script](./builtin_commands.md#run_script) command supports tab completion of file system paths. |
| 30 | There is a variant [\_relative_run_script](./builtin_commands.md#_relative_run_script) command or |
| 31 | `@@` shortcut (if using the default shortcuts) for use within a script which uses paths relative to |
| 32 | the first script. |
| 33 | |
| 34 | ### Comments |
| 35 | |
| 36 | A command line is a comment if the first non-whitespace character is a `#`. This means any `#` |
| 37 | character appearing later in the command will be treated as a literal. The same applies to a `#` in |
| 38 | the middle of a multiline command, even if it is the first character on a line. |
| 39 | |
| 40 | Comments are useful in scripts, but are generally not used within an interactive session. |
| 41 | |
| 42 | (Cmd) # this is a comment |
| 43 | (Cmd) command # this is not a comment |
| 44 | |
| 45 | ## Python Scripts |
| 46 | |
| 47 | If you require logic flow, loops, branching, or other advanced features, you can write a python |
| 48 | script which executes in the context of your `cmd2` app. This script is run using the |
| 49 | [run_pyscript](./builtin_commands.md#run_pyscript) command. Here's a simple example that uses the |
| 50 | [arg_printer.py](https://github.com/python-cmd2/cmd2/blob/main/examples/scripts/arg_printer.py) |
| 51 | pyscript: |
| 52 | |
| 53 | (Cmd) run_pyscript examples/scripts/arg_printer.py foo bar 'baz 23' |
| 54 | Running Python script 'arg_printer.py' which was called with 3 arguments |
| 55 | arg 1: 'foo' |
| 56 | arg 2: 'bar' |
| 57 | arg 3: 'baz 23' |
| 58 | |
| 59 | [run_pyscript](./builtin_commands.md#run_pyscript) supports tab completion of file system paths, and |
| 60 | as shown above it has the ability to pass command-line arguments to the scripts invoked. |
| 61 | |
| 62 | ## Developing a cmd2 API |
| 63 | |
| 64 | If you as an app designer have not explicitly disabled the `run_pyscript` command, you should assume |
| 65 | your application will be used for higher-level Python scripting. The following sections are meant as |
| 66 | guidelines and highlight possible pitfalls with both production and consumption of API |
| 67 | functionality. For clarity, a "scripter" writes pyscripts, and a "designer" is the `cmd2` |
| 68 | application author. |
| 69 | |
| 70 | ### Basics |
| 71 | |
| 72 | Without any work on the part of the designer, a scripter can take advantage of piecing together |
| 73 | workflows using simple `app` calls. The result of a `run_pyscript` app call yields a |
| 74 | [CommandResult][cmd2.CommandResult] object exposing four members: `stdout`, `stderr`, `stop`, and |
| 75 | `data`. |
| 76 | |
| 77 | `stdout` and `stderr` are fairly straightforward representations of normal data streams and |
| 78 | accurately reflect what the user sees during normal cmd2 interaction. `stop` contains information |
| 79 | about how the invoked command has ended its lifecycle. Lastly `data` contains any information the |
| 80 | designer sets via `self.last_result` or `self._cmd.last_result` if called from inside a CommandSet. |
| 81 | |
| 82 | Python scripts executed with [run_pyscript](./builtin_commands.md#run_pyscript) can run `cmd2` |
| 83 | application commands by using the syntax: |
| 84 | |
| 85 | ```py |
| 86 | app(‘command args’) |
| 87 | ``` |
| 88 | |
| 89 | where: |
| 90 | |
| 91 | - `app` is a configurable name which can be changed by setting the `cmd2.Cmd.py_bridge_name` |
| 92 | attribute |
| 93 | - `command` and `args` are entered exactly like they would be entered by a user of your application. |
| 94 | |
| 95 | Using f-strings tends to be the most straightforward and easily readable way to provide parameters.: |
| 96 | |
| 97 | ```py |
| 98 | first = 'first' |
| 99 | second = 'second' |
| 100 | |
| 101 | app(f'command {first} -t {second}) |
| 102 | ``` |
| 103 | |
| 104 | See |
| 105 | [python_scripting.py](https://github.com/python-cmd2/cmd2/blob/main/examples/python_scripting.py) |
| 106 | example and associated |
| 107 | [conditional.py](https://github.com/python-cmd2/cmd2/blob/main/examples/scripts/conditional.py) |
| 108 | script for more information. |
| 109 | |
| 110 | ### Design principles |
| 111 | |
| 112 | If your cmd2 application follows the |
| 113 | [Unix design philosophy](https://en.wikipedia.org/wiki/Unix_philosophy) a scripter will have the |
| 114 | most flexibility to create workflows using different commands. If the designer's application is more |
| 115 | complete and less likely to be augmented in the future, a scripter can use simple serial scripts |
| 116 | with little control flow. In either case, choices made by the designer will have effects on |
| 117 | scripters. |
| 118 | |
| 119 | The following diagram illustrates the different boundaries to keep in mind. |
| 120 | |
| 121 | ```mermaid |
| 122 | flowchart LR |
| 123 | subgraph Py scripts |
| 124 | direction TB |
| 125 | subgraph cmd2 Application |
| 126 | direction TB |
| 127 | subgraph Class Library |
| 128 | direction TB |
| 129 | class1 |
| 130 | class2 |
| 131 | class3 |
| 132 | class4 |
| 133 | end |
| 134 | end |
| 135 | end |
| 136 | |
| 137 | ``` |
| 138 | |
| 139 | !!! note |
| 140 | |
| 141 | As a designer, you should design from the inside out. Your code will be much easier to unit test than at the higher level. While there are regression testing extensions for cmd2, unit testing will always be faster for development. |
| 142 | |
| 143 | !!! warning |
| 144 | |
| 145 | It is bad design for a high-level pyscript to know about, let alone access, low-level class libraries of an application. Resist this urge as much as possible, unless it's necessary. |
| 146 | |
| 147 | ### Developing a Basic API |
| 148 | |
| 149 | By default, `cmd2` allows scripters to take advantage of all exposed `do_*` commands. As a scripter, |
| 150 | you can easily interact with the application via `stdout` and `stderr`. |
| 151 | |
| 152 | As a baseline, let's start with the following `cmd2` application called `FirstApp` |
| 153 | |
| 154 | ```py |
| 155 | #!/usr/bin/env python |
| 156 | """A simple cmd2 application.""" |
| 157 | import cmd2 |
| 158 | |
| 159 | |
| 160 | class FirstApp(cmd2.Cmd): |
| 161 | """A simple cmd2 application.""" |
| 162 | def __init__(self): |
| 163 | shortcuts = cmd2.DEFAULT_SHORTCUTS |
| 164 | shortcuts.update({'&': 'speak'}) |
| 165 | super().__init__(shortcuts=shortcuts) |
| 166 | |
| 167 | # Make maxrepeats settable at runtime |
| 168 | self.maxrepeats = 3 |
| 169 | self.add_settable(cmd2.Settable('maxrepeats', int, 'max repetitions for speak command', self)) |
| 170 | |
| 171 | |
| 172 | speak_parser = cmd2.Cmd2ArgumentParser() |
| 173 | speak_parser.add_argument('-p', '--piglatin', action='store_true', help='atinLay') |
| 174 | speak_parser.add_argument('-s', '--shout', action='store_true', help='N00B EMULATION MODE') |
| 175 | speak_parser.add_argument('-r', '--repeat', type=int, help='output [n] times') |
| 176 | speak_parser.add_argument('words', nargs='+', help='words to say') |
| 177 | |
| 178 | @cmd2.with_argparser(speak_parser) |
| 179 | def do_speak(self, args): |
| 180 | """Repeats what you tell me to.""" |
| 181 | words = [] |
| 182 | for word in args.words: |
| 183 | if args.piglatin: |
| 184 | word = '%s%say' % (word[1:], word[0]) |
| 185 | if args.shout: |
| 186 | word = word.upper() |
| 187 | words.append(word) |
| 188 | repetitions = args.repeat or 1 |
| 189 | for _ in range(min(repetitions, self.maxrepeats)): |
| 190 | # .poutput handles newlines, and accommodates output redirection too |
| 191 | self.poutput(' '.join(words)) |
| 192 | |
| 193 | if __name__ == '__main__': |
| 194 | import sys |
| 195 | c = FirstApp() |
| 196 | sys.exit(c.cmdloop()) |
| 197 | ``` |
| 198 | |
| 199 | Let's start with an example of what not to do: |
| 200 | |
| 201 | ```py |
| 202 | app('speak' |
| 203 | print('Working') |
| 204 | |
| 205 | SyntaxError: unexpected EOF while parsing |
| 206 | (Cmd) run_pyscript script.py |
| 207 | File "<string>", line 2 |
| 208 | app('speak' |
| 209 | ^ |
| 210 | SyntaxError: unexpected EOF while parsing |
| 211 | ``` |
| 212 | |
| 213 | `cmd2` pyscripts require **valid** Python code as a first step. |
| 214 | |
| 215 | !!! warning |
| 216 | |
| 217 | It is a common misconception that all application exceptions will propagate up from below. This is not the case. `cmd2` catches all application exceptions and there are no means to handle them. |
| 218 | |
| 219 | When executing the `speak` command without parameters you see the following error: |
| 220 | |
| 221 | (Cmd) speak |
| 222 | Usage: speak [-h] [-p] [-s] [-r REPEAT] words [...] |
| 223 | Error: the following arguments are required: words |
| 224 | |
| 225 | Even though this is a fully qualified `cmd2` error, the pyscript must check for this error and |
| 226 | perform error checking.: |
| 227 | |
| 228 | ```py |
| 229 | app('speak') |
| 230 | print("Working") |
| 231 | ``` |
| 232 | |
| 233 | (Cmd) run_pyscript script.py |
| 234 | Working |
| 235 | (Cmd) |
| 236 | |
| 237 | You should notice that no error message is printed. Let's utilize the `CommandResult` object to |
| 238 | inspect the actual returned data.: |
| 239 | |
| 240 | ```py |
| 241 | result = app('speak') |
| 242 | print(result) |
| 243 | ``` |
| 244 | |
| 245 | (Cmd) run_pyscript script.py |
| 246 | CommandResult(stdout='', stderr='Usage: speak [-h] [-p] [-s] [-r REPEAT] words [...]\nError: the following arguments are required: words\n\n', stop=False, data=None) |
| 247 | |
| 248 | Now we can see that there has been an error. Let's rewrite the script to perform error checking.: |
| 249 | |
| 250 | ```py |
| 251 | result = app('speak') |
| 252 | |
| 253 | if not result: |
| 254 | print(result.stderr) |
| 255 | ``` |
| 256 | |
| 257 | (Cmd) run_pyscript script.py |
| 258 | Something went wrong |
| 259 | |
| 260 | In Python development, it is good practice to fail fast after user input.: |
| 261 | |
| 262 | ```py |
| 263 | import sys |
| 264 | |
| 265 | result = app('speak TRUTH!!') |
| 266 | |
| 267 | if not result: |
| 268 | print("Something went wrong") |
| 269 | sys.exit() |
| 270 | |
| 271 | print("Continuing along..") |
| 272 | ``` |
| 273 | |
| 274 | (Cmd) run_pyscript script.py |
| 275 | Continuing along.. |
| 276 | |
| 277 | We changed the input to be a valid `speak` command, but there was no output. Again we must inspect |
| 278 | the `CommandResult`: |
| 279 | |
| 280 | ```py |
| 281 | import sys |
| 282 | |
| 283 | #Syntax error |
| 284 | result = app('speak TRUTH!!!') |
| 285 | if not result: |
| 286 | print("Something went wrong") |
| 287 | sys.exit() |
| 288 | |
| 289 | print(result.stdout) |
| 290 | ``` |
| 291 | |
| 292 | (Cmd) run_pyscript script.py |
| 293 | TRUTH!!! |
| 294 | |
| 295 | By just using `stdout` and `stderr` it is possible to chain commands with rudimentary control flow. |
| 296 | In the next section we will show how to use `cmd_result` data. |
| 297 | |
| 298 | ### Developing an Advanced API |
| 299 | |
| 300 | So far, we haven't focused on the scripter's needs. Wouldn't it be nice if while creating pyscripts |
| 301 | you did not have to parse data from `stdout`? We can accommodate the scripter by adding one small |
| 302 | line at the end of our `do_*` commands. |
| 303 | |
| 304 | `self.last_result = <value>` |
| 305 | |
| 306 | Adding the above line enhances a cmd2 application and opens a new world of possibilities. |
| 307 | |
| 308 | !!! tip |
| 309 | |
| 310 | When setting results for a command function inside of a CommandSet use the private cmd instance: |
| 311 | |
| 312 | ```py |
| 313 | self._cmd.last_result = <value> |
| 314 | ``` |
| 315 | |
| 316 | In the following command example we return a list containing directory elements.: |
| 317 | |
| 318 | ```py |
| 319 | dir_parser = cmd2.Cmd2ArgumentParser() |
| 320 | dir_parser.add_argument('-l', '--long', action='store_true', |
| 321 | help="display in long format with one item per line") |
| 322 | |
| 323 | @cmd2.with_argparser(dir_parser, with_unknown_args=True) |
| 324 | def do_dir(self, args, unknown): |
| 325 | """List contents of current directory.""" |
| 326 | # No arguments for this command |
| 327 | if unknown: |
| 328 | self.perror("dir does not take any positional arguments:") |
| 329 | self.do_help('dir') |
| 330 | return |
| 331 | |
| 332 | # Get the contents as a list |
| 333 | contents = os.listdir(self.cwd) |
| 334 | |
| 335 | for f in contents: |
| 336 | self.poutput(f'{f}') |
| 337 | self.poutput('') |
| 338 | |
| 339 | self.last_result = contents |
| 340 | ``` |
| 341 | |
| 342 | The following script retrieves the array contents.: |
| 343 | |
| 344 | ```py |
| 345 | result = app('dir') |
| 346 | print(result.data) |
| 347 | ``` |
| 348 | |
| 349 | Results: |
| 350 | |
| 351 | Cmd) run_pyscript script.py |
| 352 | ['.venv', 'app.py', 'script.py'] |
| 353 | |
| 354 | As a rule of thumb, designers should return simple scalar types as command results instead of |
| 355 | complex objects. If it is beneficial in providing class objects designers should choose immutable |
| 356 | over mutable types and never provide direct access to class members as this could potentially lead |
| 357 | to violation of the |
| 358 | [open-closed_principle](https://en.wikipedia.org/wiki/Open%E2%80%93closed_principle). |
| 359 | |
| 360 | When possible, a frozen dataclass is a lightweight solution ideal for data manipulation. Let's look |
| 361 | at an example. |
| 362 | |
| 363 | The following application has two commands: `build` and `status`. Let's assume that the build action |
| 364 | happens somewhere else in the world at a REST API endpoint and has significant computational cost. |
| 365 | The status command, will only show the current status of a build task. The application has provided |
| 366 | everything that is needed for a user to start a build and then determine its status. However, the |
| 367 | problem is that with a long running process the user may want to wait for it to finish. A designer |
| 368 | may be tempted to create a command to start a build and then poll for status until finished, but |
| 369 | this scenario is better solved as a script. |
| 370 | |
| 371 | app.py: |
| 372 | |
| 373 | ```py |
| 374 | #!/usr/bin/env python |
| 375 | """A simple cmd2 application.""" |
| 376 | import sys |
| 377 | from dataclasses import dataclass |
| 378 | from random import choice, randint |
| 379 | from typing import Optional |
| 380 | |
| 381 | import cmd2 |
| 382 | from cmd2.parsing import Statement |
| 383 | |
| 384 | |
| 385 | @dataclass(frozen=True) |
| 386 | class BuildStatus: |
| 387 | id: int |
| 388 | name: str |
| 389 | status: str |
| 390 | |
| 391 | |
| 392 | class FirstApp(cmd2.Cmd): |
| 393 | """A simple cmd2 application.""" |
| 394 | |
| 395 | def __init__(self): |
| 396 | self._status_cache = dict() |
| 397 | |
| 398 | def _start_build(self, name: str) -> BuildStatus: |
| 399 | return BuildStatus(randint(10, 100), name, "Started") |
| 400 | |
| 401 | def _get_status(self, name: str) -> Optional[BuildStatus]: |
| 402 | |
| 403 | status = self._status_cache.get(name) |
| 404 | |
| 405 | status_types = ["canceled", "restarted", "error", "finished"] |
| 406 | |
| 407 | if status.status != "finished": |
| 408 | status = BuildStatus(status.id, status.name, choice(status_types)) |
| 409 | self._status_cache[name] = status |
| 410 | |
| 411 | return status |
| 412 | |
| 413 | build_parser = cmd2.Cmd2ArgumentParser() |
| 414 | build_parser.add_argument("name", help="Name of build to start") |
| 415 | |
| 416 | @cmd2.with_argparser(build_parser) |
| 417 | def do_build(self, args: Statement): |
| 418 | """Executes a long running process at an API endpoint""" |
| 419 | status = self._start_build(args.name) |
| 420 | self._status_cache[args.name] = status |
| 421 | |
| 422 | self.poutput( |
| 423 | f"Build {args.name.upper()} successfully started with id : {status.id}" |
| 424 | ) |
| 425 | self.last_result = status |
| 426 | |
| 427 | status_parser = cmd2.Cmd2ArgumentParser() |
| 428 | status_parser.add_argument("name", help="Name of build determine status of") |
| 429 | |
| 430 | @cmd2.with_argparser(status_parser) |
| 431 | def do_status(self, args: Statement): |
| 432 | """Shows the current status of a build""" |
| 433 | |
| 434 | status = self._get_status(args.name) |
| 435 | |
| 436 | self.poutput(f"Status for Build: {args.name} \n {status.status}") |
| 437 | self.last_result = status |
| 438 | |
| 439 | |
| 440 | if __name__ == "__main__": |
| 441 | import sys |
| 442 | |
| 443 | c = FirstApp() |
| 444 | sys.exit(c.cmdloop()) |
| 445 | ``` |
| 446 | |
| 447 | Below is a possible solution via pyscript: |
| 448 | |
| 449 | ```py |
| 450 | import sys |
| 451 | import time |
| 452 | |
| 453 | # start build |
| 454 | result = app('build tower') |
| 455 | |
| 456 | # If there was an error then exit |
| 457 | if not result: |
| 458 | print('Build failed') |
| 459 | sys.exit() |
| 460 | |
| 461 | # This is a BuildStatus dataclass object |
| 462 | build = result.data |
| 463 | |
| 464 | print(f"Build {build.name} : {build.status}") |
| 465 | |
| 466 | # Poll status |
| 467 | while True: |
| 468 | |
| 469 | # Perform status check |
| 470 | result = app('status tower') |
| 471 | |
| 472 | #error checking |
| 473 | if not result: |
| 474 | print("Unable to determine status") |
| 475 | break |
| 476 | |
| 477 | build_status = result.data |
| 478 | |
| 479 | # If the status shows complete then the script is done |
| 480 | if build_status.status in ['finished', 'canceled']: |
| 481 | print(f"Build {build.name} has completed") |
| 482 | break |
| 483 | |
| 484 | print(f"Current Status: {build_status.status}") |
| 485 | time.sleep(1) |
| 486 | ``` |