@@ -56,7 +56,14 @@ conveniences:
56561 . Since users can pipe output to a shell command, it catches ` BrokenPipeError ` and outputs the
5757 contents of ` self.broken_pipe_warning ` to ` stderr ` . ` self.broken_pipe_warning ` defaults to an
5858 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 ` .
59+ message, put it in ` self.broken_pipe_warning ` when you initialize ` cmd2.Cmd ` . A command which
60+ prints through a ` cmd2 ` console of its own, such as the
61+ [ Cmd2GeneralConsole] [ cmd2.rich_utils.Cmd2GeneralConsole ] used for the progress displays described
62+ below, is covered too, with one difference. A command which uses ` poutput ` carries on after the
63+ pipe breaks, but one which prints through its own console ends at the call which found the pipe
64+ broken, and its postcommand hooks do not run. Put any cleanup such a command has to do in a
65+ ` finally ` block or a context manager. Use a ` cmd2 ` console rather than a plain
66+ ` rich.console.Console ` , which exits the application when it writes to a broken pipe.
60672 . It examines and honors the [ allow_style] ( ./settings.md#allow_style ) setting. See
6168 [ Colored Output] ( #colored-output ) below for more details.
62693 . It allows printing arbitrary ` rich ` renderable objects which can get visually quite complex.
@@ -69,6 +76,134 @@ def do_echo(self, args):
6976 self .poutput(args)
7077```
7178
79+ ## Updating Output in Place
80+
81+ Countdowns, progress indicators, and status lines repeatedly overwrite the same line of the
82+ terminal. The traditional way to do that with ` print() ` is to embed a carriage return (` \r ` ) in the
83+ string, but that does not work with ` poutput ` or any of the other ` cmd2 ` print methods. ` rich `
84+ removes the carriage return, backspace, bell, vertical tab, and form feed characters from every
85+ string it renders because they would break its width calculations, so the cursor never returns to
86+ the start of the line.
87+
88+ ` rich ` can manage the cursor for you instead. Its status spinners and progress bars work inside a
89+ command when you give them a console which writes to ` self.stdout ` . Create one with
90+ [ Cmd2GeneralConsole] [ cmd2.rich_utils.Cmd2GeneralConsole ] so the display uses the ` cmd2 ` theme and
91+ follows the [ allow_style] ( ./settings.md#allow_style ) setting. The
92+ [ rich_progress.py] ( https://github.com/python-cmd2/cmd2/blob/main/examples/rich_progress.py ) example
93+ demonstrates everything described below.
94+
95+ ### Status Messages
96+
97+ For work of an unknown length, show a spinner and a message with a
98+ [ status] ( https://rich.readthedocs.io/en/stable/console.html#status ) :
99+
100+ ``` py
101+ import time
102+
103+ from cmd2.rich_utils import Cmd2GeneralConsole
104+
105+
106+ def do_countdown (self , _ ):
107+ """ Count down from 5 on a single line"""
108+ console = Cmd2GeneralConsole(file = self .stdout)
109+ with console.status(" Starting..." ) as status:
110+ for remaining in range (5 , 0 , - 1 ):
111+ status.update(f " Time remaining: { remaining} s " )
112+ time.sleep(1 )
113+ self .poutput(" Done!" )
114+ ```
115+
116+ The status line disappears when the ` with ` block exits.
117+
118+ ### Progress Bars
119+
120+ When you know how much work there is, show a
121+ [ progress bar] ( https://rich.readthedocs.io/en/stable/progress.html ) :
122+
123+ ``` py
124+ import time
125+
126+ from rich.progress import Progress
127+
128+ from cmd2.rich_utils import Cmd2GeneralConsole
129+
130+
131+ def do_process (self , _ ):
132+ """ Process some files while showing a progress bar"""
133+ files = [f " file_ { i} .dat " for i in range (1 , 11 )]
134+ console = Cmd2GeneralConsole(file = self .stdout)
135+ with Progress(console = console) as progress:
136+ task_id = progress.add_task(" Processing files" , total = len (files))
137+ for file in files:
138+ time.sleep(0.4 )
139+ progress.console.print(f " Processed { file } " )
140+ progress.advance(task_id)
141+ self .poutput(" All files processed." )
142+ ```
143+
144+ A few things to know when using a progress bar in a command:
145+
146+ - While the bar is active, print with ` progress.console.print() ` as shown above. The message then
147+ appears above the bar. ` poutput ` and the other print methods do not know about the bar: their
148+ output lands on the end of its line and a stale copy of the bar is left behind. Once the ` with `
149+ block exits, they are safe to use again.
150+ - The finished bar is left on the screen. Pass ` transient=True ` to ` Progress ` to erase it instead.
151+ - Call ` add_task ` more than once to show several bars at the same time, and pass
152+ [ columns] ( https://rich.readthedocs.io/en/stable/progress.html#columns ) to ` Progress ` to change
153+ what is shown for each one.
154+ - To add a bar to a simple loop, wrap the sequence being iterated over with
155+ ` rich.progress.track(sequence, console=console) ` .
156+
157+ ### Styles, Redirection, and Markup
158+
159+ Status messages and progress bars differ from the print methods in two ways:
160+
161+ - ** They are only animated where ` allow_style ` allows it.** With the default setting of ` Terminal ` ,
162+ they are animated on a terminal. When the output of the command is redirected to a file or piped
163+ to a shell command, a status writes nothing and a progress bar writes only its final state, or
164+ just a blank line if it is transient. With ` Never ` , that is what happens on a terminal too. With
165+ ` Always ` , redirected output also contains the escape sequences which hide and show the cursor and
166+ style the bar.
167+ - ** Their text is parsed as [ console markup] ( https://rich.readthedocs.io/en/stable/markup.html ) .** A
168+ status message or the description of a progress bar task is searched for markup tags such as
169+ ` [bold] ` and emoji codes such as ` :warning: ` , even though both are off by default in the print
170+ methods. So ` report[draft].txt ` is displayed as ` report.txt ` , ` user:id:42 ` as ` user🆔42 ` , and an
171+ unmatched closing tag such as ` [/b] ` raises a ` MarkupError ` . To display text you do not control,
172+ such as a file name, exactly as it is, give a status a ` rich.text.Text ` object instead of a
173+ string, and show task descriptions with a ` TextColumn("{task.description}", markup=False) `
174+ [ column] ( https://rich.readthedocs.io/en/stable/progress.html#columns ) .
175+
176+ ### Carriage Returns
177+
178+ If you would rather write the escape sequences yourself, put the carriage return in the ` end `
179+ parameter, which ` rich ` does not strip:
180+
181+ ``` py
182+ import time
183+
184+ CLEAR_LINE = " \x1b [2K"
185+
186+
187+ def do_countdown (self , _ ):
188+ """ Count down from 5 on a single line"""
189+ for remaining in range (5 , 0 , - 1 ):
190+ self .poutput(f " { CLEAR_LINE } Time remaining: { remaining} s " , end = " \r " )
191+ time.sleep(1 )
192+ self .poutput(f " { CLEAR_LINE } Done! " )
193+ ```
194+
195+ Use the ` style ` parameter if you want to color text printed this way. A string which already
196+ contains ANSI style sequences is parsed as ANSI text, which discards every other kind of escape
197+ sequence in it, including the one that clears the line.
198+
199+ Unlike the ` rich ` displays, this always writes the escape sequences and carriage returns, including
200+ when the output of the command is redirected to a file or pipe.
201+
202+ The print methods flush the stream after every call, so there is no ` flush ` parameter to pass.
203+ Strings written directly to ` self.stdout ` are not processed by ` rich ` , so control characters in them
204+ are left alone. They are not flushed either, so call ` self.stdout.flush() ` after writing a line
205+ which does not end with a newline.
206+
72207## Error Messages
73208
74209When an error occurs in your program, you can display it on ` sys.stderr ` by calling the
0 commit comments