Debian Codegraph @

docs/features/startup_commands.md

raw symbols SCIP
1 # Startup Commands
2
3 `cmd2` provides a couple different ways for running commands immediately after your application
4 starts up:
5
6 1. Commands at Invocation
7 1. Startup Script
8
9 Commands run as part of a startup script are always run immediately after the application finishes
10 initializing so they are guaranteed to run before any _Commands At Invocation_.
11
12 ## Commands At Invocation
13
14 You can send commands to your app as you invoke it by including them as extra arguments to the
15 program. `cmd2` interprets each argument as a separate command, so you should enclose each command
16 in quotation marks if it is more than a one-word command. You can use either single or double quotes
17 for this purpose.
18
19 $ python examples/cmd_as_argument.py "say hello" "say Gracie" quit
20 hello
21 Gracie
22
23 You can end your commands with a **quit** command so that your `cmd2` application runs like a
24 non-interactive command-line utility (CLU). This means that it can then be scripted from an external
25 application and easily used in automation.
26
27 !!! note
28
29 If you wish to disable cmd2's consumption of command-line arguments, you can do so by setting the `allow_cli_args` argument of your [cmd2.Cmd][] class instance to `False`. This would be useful, for example, if you wish to use something like [argparse](https://docs.python.org/3/library/argparse.html) to parse the overall command line arguments for your application:
30
31 ```py
32 from cmd2 import Cmd
33 class App(Cmd):
34 def __init__(self):
35 super().__init__(allow_cli_args=False)
36 ```
37
38 ## Startup Script
39
40 You can execute commands from an initialization script by passing a file path to the
41 `startup_script` argument to the `cmd2.Cmd.__init__()` method like so:
42
43 ```py
44 class StartupApp(cmd2.Cmd):
45 def __init__(self):
46 cmd2.Cmd.__init__(self, startup_script='.cmd2rc')
47 ```
48
49 This text file should contain a [Command Script](./scripting.md#command-scripts). See the
50 [getting_started.py](https://github.com/python-cmd2/cmd2/blob/main/examples/getting_started.py)
51 example for a demonstration.
52
53 You can silence a startup script's output by setting `silence_startup_script` to True:
54
55 ```py
56 cmd2.Cmd.__init__(self, startup_script='.cmd2rc', silence_startup_script=True)
57 ```
58
59 !!! warning
60
61 Anything written to `stderr` will still print for a "silenced" startup script. Additionally, a startup script cannot be silenced if
62 `allow_redirection` is False since silencing works by redirecting a script's output to `os.devnull`.