Debian Codegraph @

docs/features/generating_output.md

raw symbols SCIP
1 # Generating Output
2
3 A standard `cmd` application can produce output by using either of these methods:
4
5 ```py
6 print("Greetings, Professor Falken.", file=self.stdout)
7 self.stdout.write("Shall we play a game?\n")
8 ```
9
10 While you could send output directly to `sys.stdout`, [cmd2.Cmd][] can be initialized with a `stdin`
11 and `stdout` variables, which it stores as `self.stdin` and `self.stdout`. By using these variables
12 every time you produce output, you can trivially change where all the output goes by changing how
13 you initialize your class.
14
15 `cmd2.Cmd` extends this approach in a number of convenient ways. See
16 [Output Redirection and Pipes](./redirection.md#output-redirection-and-pipes) for information on how
17 users can change where the output of a command is sent. In order for those features to work, the
18 output you generate must be sent to `self.stdout`. You can use the methods described above, and
19 everything will work fine. [cmd2.Cmd][] also includes a number of output related methods which you
20 may use to enhance the output your application produces.
21
22 Since `cmd2` has a dependency on the [rich](https://github.com/Textualize/rich) library, the
23 following [cmd2.Cmd][] output methods can natively render `rich`
24 [renderable objects](https://rich.readthedocs.io/en/latest/protocol.html), enabling beautiful and
25 complex output:
26
27 - [poutput][cmd2.Cmd.poutput]
28 - [perror][cmd2.Cmd.perror]
29 - [psuccess][cmd2.Cmd.psuccess]
30 - [pwarning][cmd2.Cmd.pwarning]
31 - [pfeedback][cmd2.Cmd.pfeedback]
32 - [ppaged][cmd2.Cmd.ppaged]
33
34 !!! tip "Advanced output customization"
35
36 Each of the above methods accepts additional optional parameters that help control how the output is
37 formatted:
38
39 - `sep`: string to write between printed text. Defaults to " "
40 - `end`: string to write at end of printed text. Defaults to a newline
41 - `style`: optional style to apply to output
42 - `soft_wrap`: Enable soft wrap mode. If True, lines of text will not be word-wrapped or cropped to fit the terminal width. Defaults to True
43 - `justify`: justify method ("left", "center", "right", "full"). Defaults to None.
44 - `emoji`: If True, Rich will replace emoji codes (e.g., 😃) with their corresponding Unicode characters. Defaults to False
45 - `markup`: If True, Rich will interpret strings with tags (e.g., [bold]hello[/bold]) as styled output. Defaults to False
46 - `highlight`: If True, Rich will automatically apply highlighting to elements within strings, such as common Python data types like numbers, booleans, or None.
47 - `rich_print_kwargs`: optional additional keyword arguments to pass to `console.print()`
48 - `kwargs`: arbitrary keyword arguments to support extending the print methods. These are not passed to `console.print()`.
49
50 ## Ordinary Output
51
52 The [poutput][cmd2.Cmd.poutput] method is similar to the Python built-in
53 [print](https://docs.python.org/3/library/functions.html#print) function. `poutput` adds a few
54 conveniences:
55
56 1. Since users can pipe output to a shell command, it catches `BrokenPipeError` and outputs the
57 contents of `self.broken_pipe_warning` to `stderr`. `self.broken_pipe_warning` defaults to an
58 empty string so this method will just swallow the exception. If you want to show an error
59 message, put it in `self.broken_pipe_warning` when you initialize `cmd2.Cmd`.
60 2. It examines and honors the [allow_style](./settings.md#allow_style) setting. See
61 [Colored Output](#colored-output) below for more details.
62 3. It allows printing arbitrary `rich` renderable objects which can get visually quite complex.
63
64 Here's a simple command that shows this method in action:
65
66 ```py
67 def do_echo(self, args):
68 """A simple command showing how poutput() works"""
69 self.poutput(args)
70 ```
71
72 ## Error Messages
73
74 When an error occurs in your program, you can display it on `sys.stderr` by calling the
75 [perror][cmd2.Cmd.perror] method. By default this method applies
76 [Cmd2Style.ERROR][cmd2.styles.Cmd2Style.ERROR] to the output.
77
78 ## Warning Messages
79
80 [pwarning][cmd2.Cmd.pwarning] is just like `cmd2.Cmd.perror` but applies `Cmd2Style.WARNING` to the
81 output.
82
83 ## Feedback
84
85 You may have the need to display information to the user which is not intended to be part of the
86 generated output. This could be debugging information or status information about the progress of
87 long running commands. It's not output, it's not error messages, it's status. If you use the
88 [Timing](./settings.md#timing) setting, the output of how long it took the command to run will be
89 output as to `stderr` without any styling. You can use the [perror][cmd2.Cmd.perror] method to
90 produce this type of output by passing it `style=None`.
91
92 If the [quiet](./settings.md#quiet) setting is `True`, then calling `cmd2.Cmd.pfeedback` produces no
93 output. If [quiet](./settings.md#quiet) is `False`,the `pfeedback` method sends output to `stdout`.
94 Hence, `pfeedback` is useful for non-essential output that you want the ability to silence when
95 `quiet` is `True`.
96
97 ## Exceptions
98
99 If your app catches an exception and you would like to display the exception to the user, the
100 [pexcept][cmd2.Cmd.pexcept] method can help. The default behavior is to just display the message
101 contained within the exception. However, if the [debug](./settings.md#debug) setting is `True`, then
102 the entire stack trace will be displayed.
103
104 ## Paging Output
105
106 If you know you are going to generate a lot of output, you may want to display it in a way that the
107 user can scroll forwards and backwards through it. If you pass all of the output to be displayed in
108 a single call to [ppaged][cmd2.Cmd.ppaged], it will be piped to an operating system appropriate
109 shell command to page the output. On Windows, the output is piped to
110 [more](https://learn.microsoft.com/en-us/windows-server/administration/windows-commands/more); on
111 Unix-like operating systems like MacOS and Linux, it is piped to
112 [less](https://man7.org/linux/man-pages/man1/less.1.html).
113
114 ## Colored Output
115
116 You can add your own [ANSI escape sequences](https://en.wikipedia.org/wiki/ANSI_escape_code#Colors)
117 to your output which tell the terminal to change the foreground and background colors.
118
119 `cmd2` provides a number of convenience functions and classes for adding color and other styles to
120 text. These are all based on [rich](https://github.com/Textualize/rich) and are documented in the
121 following sections:
122
123 - [cmd2.colors][]
124 - [cmd2.rich_utils][]
125 - [cmd2.string_utils][]
126
127 The [color.py](https://github.com/python-cmd2/cmd2/blob/main/examples/color.py) example demonstrates
128 all colors available to your `cmd2` application.
129
130 ### Custom Themes
131
132 `cmd2` uses a `rich` [Theme](https://rich.readthedocs.io/en/stable/reference/theme.html) object to
133 define styles for various UI elements. You can define your own custom theme using
134 [cmd2.theme.update_theme][]. See the
135 [rich_theme.py](https://github.com/python-cmd2/cmd2/blob/main/examples/rich_theme.py) example for
136 more information.
137
138 After adding the desired escape sequences to your output, you should use one of these methods to
139 present the output to the user:
140
141 - [cmd2.Cmd.poutput][]
142 - [cmd2.Cmd.perror][]
143 - [cmd2.Cmd.pwarning][]
144 - [cmd2.Cmd.pexcept][]
145 - [cmd2.Cmd.pfeedback][]
146 - [cmd2.Cmd.ppaged][]
147
148 These methods all honor the [allow_style](./settings.md#allow_style) setting, which users can modify
149 to control whether these escape codes are passed through to the terminal or not.
150
151 ## Aligning Text
152
153 If you would like to generate output which is left, center, or right aligned within a specified
154 width or the terminal width, the following functions can help:
155
156 - [cmd2.string_utils.align_left][]
157 - [cmd2.string_utils.align_center][]
158 - [cmd2.string_utils.align_right][]
159
160 These functions differ from Python's string justifying functions in that they support characters
161 with display widths greater than 1. Additionally, ANSI style sequences are safely ignored and do not
162 count toward the display width. This means colored text is supported. If text has line breaks, then
163 each line is aligned independently.
164
165 !!! tip "Advanced alignment customization"
166
167 You can also control output alignment using the `justify` parameter when calling
168 `cmd2`'s print methods.
169
170 ## Columnar Output
171
172 When generating output in multiple columns, you often need to calculate the width of each item so
173 you can pad it appropriately with spaces. However, there are categories of Unicode characters that
174 occupy 2 cells, and other that occupy 0. To further complicate matters, you might have included ANSI
175 escape sequences in the output to generate colors on the terminal.
176
177 The [cmd2.string_utils.str_width][] function solves both of these problems. Pass it a string, and
178 regardless of which Unicode characters and ANSI text style escape sequences it contains, it will
179 tell you how many characters on the screen that string will consume when printed.