Debian Codegraph @

docs/features/redirection.md

raw symbols SCIP
1 # Output Redirection and Pipes
2
3 As in POSIX shells, output of a command can be redirected and/or piped. This feature is fully
4 cross-platform and works identically on Windows, macOS, and Linux.
5
6 ## Output Redirection
7
8 ### Redirect to a file
9
10 Redirecting the output of a `cmd2` command to a file works just like in POSIX shells:
11
12 - send to a file with `>`, as in `mycommand args > filename.txt`
13 - append to a file with `>>`, as in `mycommand args >> filename.txt`
14
15 If you need to include any of these redirection characters in your command, you can enclose them in
16 quotation marks, `mycommand 'with > in the argument'`.
17
18 ### Redirect to the clipboard
19
20 `cmd2` output redirection supports an additional feature not found in most shells - if the file name
21 following the `>` or `>>` is left blank, then the output is redirected to the operating system
22 clipboard so that it can then be pasted into another program.
23
24 - overwrite the clipboard with `mycommand args >`
25 - append to the clipboard with `mycommand args >>`
26
27 ## Pipes
28
29 Piping the output of a `cmd2` command to a shell command works just like in POSIX shells:
30
31 - pipe as input to a shell command with `|`, as in `mycommand args | wc`
32
33 ## Multiple Pipes and Redirection
34
35 Multiple pipes, optionally followed by a redirect, are supported. Thus, it is possible to do
36 something like the following:
37
38 (Cmd) help | grep py | wc > output.txt
39
40 The above runs the **help** command, pipes its output to **grep** searching for any lines containing
41 _py_, then pipes the output of grep to the **wc** "word count" command, and finally redirects the
42 output of that to a file called _output.txt_.
43
44 ## Disabling Redirection
45
46 !!! note
47
48 If you wish to disable cmd2's output redirection and pipes features, you can do so by setting the `allow_redirection` attribute of your `cmd2.Cmd` class instance to `False`. This would be useful, for example, if you want to restrict the ability for an end user to write to disk or interact with shell commands for security reasons:
49
50 ```py
51 from cmd2 import Cmd
52 class App(Cmd):
53 def __init__(self):
54 super().__init__(allow_redirection=False)
55 ```
56
57 cmd2's parser will still treat the `>`, `>>`, and `|` symbols as output redirection and pipe symbols and will strip arguments after them from the command line arguments accordingly. But output from a command will not be redirected to a file or piped to a shell command.
58
59 ## Limitations of Redirection
60
61 !!! warning
62
63 Some limitations apply to redirection and piping within `cmd2` applications:
64
65 - Can only pipe to shell commands, not other `cmd2` application commands
66 - **stdout** gets redirected/piped, **stderr** does not