Operating system shells have long had the ability to execute a sequence of
commands saved in a text file. These script files make long sequences of
commands easier to repeatedly execute.
cmd2 supports two similar
mechanisms: command scripts and python scripts.
A command script contains a sequence of commands typed at the the prompt of a
cmd2 based application. Unlike operating system shell scripts, command
scripts can’t contain logic or loops.
Creating Command Scripts¶
Command scripts can be created in several ways:
- creating a text file using any method of your choice
- using the built-in
editcommand to create or edit an existing text file
- saving previously entered commands to a script file using
history -s. See History for more details.
If you create create a text file from scratch, just include one command per
line, exactly as you would type it inside a
Running Command Scripts¶
Command script files can be executed using the built-in
@ shortcut. Both ASCII and UTF-8 encoded unicode text files are
run_script command supports tab-completion of file system
paths. There is a variant
_relative_run_script command or
shortcut for use within a script which uses paths relative to the first script.
If you require logic flow, loops, branching, or other advanced features, you
can write a python script which executes in the context of your
This script is run using the
run_pyscript command. A simple example of
run_pyscript is shown below along with the arg_printer script:
(Cmd) run_pyscript examples/scripts/arg_printer.py foo bar 'baz 23' Running Python script 'arg_printer.py' which was called with 3 arguments arg 1: 'foo' arg 2: 'bar' arg 3: 'baz 23'
run_pyscript supports tab-completion of file system paths, and as shown
above it has the ability to pass command-line arguments to the scripts invoked.
Python scripts executed with
run_pyscript can run
commands by using the syntax:
appis a configurable name which can be changed by setting the
py_bridge_nameattribute of your
argsare entered exactly like they would be entered on the command line of your