Repository navigation
Add Rich progress docs and example, and handle broken pipes from any piped command - #1809
Merged
Merged
Conversation
Rich strips carriage returns and a few other control characters from the strings it renders, so a '\r' embedded in a string passed to poutput() is dropped. Explain this and show the supported alternatives: a Rich status or live display on a console writing to self.stdout, or passing the carriage return in the end parameter.
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #1809 +/- ##
=======================================
Coverage 99.75% 99.75%
=======================================
Files 23 23
Lines 6609 6632 +23
=======================================
+ Hits 6593 6616 +23
Misses 16 16
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. |
Add examples/rich_progress.py, which shows a status spinner, a progress bar with messages printed above it, several simultaneous bars with custom columns, and rich.progress.track() inside cmd2 commands. Split the 'Updating Output in Place' documentation into status message, progress bar, and carriage return subsections, and explain how to print while a bar is active and what is written when output is redirected.
- Stop advancing finished tasks in the downloads command, which showed more bytes received than the size of the file - Handle BrokenPipeError in the progress command when its output is piped to a command which exits early - Document how Rich status and progress displays differ from the print methods: animation depends on allow_style, their text is parsed as markup, and they do not handle broken pipes - Drop the Live recommendation, which truncates wrapped renderables on a soft-wrapping console - Note that the carriage return recipe is for strings without ANSI style sequences - Add a CHANGELOG entry for the new example and documentation
The print methods ignore the BrokenPipeError raised when a command's output is piped to a shell command which exits early, but a command which writes to self.stdout another way, such as with its own Rich console, let it escape and ended with an error message. Handle it in onecmd_plus_hooks() the way print_to() does, honoring broken_pipe_warning. This applies only while self.stdout is a pipe to a shell command, including for commands run by a piped command such as run_script, so a BrokenPipeError from something else a command did is still reported.
- Drop the broken pipe caveat and the example's handler now that cmd2 handles it for any piped command - Document that status and task text also gets emoji codes replaced, and recommend Text objects and TextColumn(markup=False) rather than escape() - Describe what the print methods actually do to an active progress bar - Note that direct writes to self.stdout need a flush - Keep each download's chunk size in its task's fields - Add the missing import to the carriage return snippet
Coverage starts in Python subprocesses and, on Python 3.11, warns on stderr that it cannot use the sysmon core. The test asserts that nothing is written to stderr, so it failed there.
Deciding whether to swallow a BrokenPipeError by whether the command's output was piped hid unrelated errors, such as one from a socket, made a failed app() call in a piped pyscript look successful, and did not cover an application whose own stdout is a pipe. Cmd2BaseConsole.on_broken_pipe() now raises ConsoleBrokenPipeError, a BrokenPipeError subclass, and onecmd_plus_hooks() handles only that. It needs no state about redirection, and any other BrokenPipeError which escapes a command is reported as before. print_to() and the new handler share one method for printing broken_pipe_warning. The end-to-end tests no longer depend on the pipe process outliving the check that it started.
A consumer which exits at once, like true, can be found to have exited before the command runs, which cmd2 reports as a failed pipe instead of running the command. head -n 1 stays until the command has written a line, so the tests no longer depend on how fast the two processes start.
- ConsoleBrokenPipeError names the stream which broke, and only one that is the command's output is handled quietly. A console which was writing somewhere else, to a socket for instance, has its error reported. - A KeyboardInterrupt or SystemExit which the broken pipe replaced, as when the with block of a progress display exits, is raised again, so Ctrl-C still stops a script and exiting still exits. - The console of a command finalization hook is handled the same way. - The documentation and changelog no longer say this is what poutput() does: the command ends at the call which found the pipe broken.
kmvanbrunt
previously approved these changes
Nov 14, 2026
kmvanbrunt
reviewed
Nov 14, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Documents how to overwrite output in place (countdowns, status lines, progress bars) from a
cmd2command, adds an example application which does it with Rich, and fixes a
BrokenPipeErrorthatthis kind of command ran into when its output was piped.
poutput()and the other print methods render through Rich, which strips carriage returns (alongwith backspace, bell, vertical tab, and form feed) from every string it renders. A
\rembedded ina string is therefore dropped, so the cursor never returns to the start of the line. This has been
the behavior since the print methods moved to Rich in 3.0.0, but it was not documented.
Bug fix
The print methods ignore the
BrokenPipeErrorraised when a command's output goes to a pipe whosereader exits early, such as
head. A command which printed through acmd2console of its own, asone showing a Rich progress bar does, let the error escape and ended with a
BrokenPipeErrormessage.
Cmd2BaseConsole.on_broken_pipe()now raisesConsoleBrokenPipeError, an internalBrokenPipeErrorsubclass which names the stream that broke, andonecmd_plus_hooks()ends thecommand quietly, printing
broken_pipe_warningif it is set. Marking the error where the consoleraises it means:
cmd | shellpipe, a command run by a pipedrun_script,or an application whose own stdout is a pipe. A command finalization hook's console is covered too
socket, and any other
BrokenPipeErrorwhich escapes a command are still reportedKeyboardInterruptorSystemExitwhich the broken pipe replaced, as when thewithblock ofa progress display exits, is raised again, so Ctrl-C still stops a script
Unlike a command which uses
poutput(), which carries on after the pipe breaks, a command printingthrough its own console ends at the call which found the pipe broken. A command which writes to
self.stdoutdirectly, or through a plainrich.console.Console, is not covered. The documentationsays both.
Documentation
Adds an "Updating Output in Place" section to the
Generating Output page, which
explains why an embedded
\rdoes not work and has four subsections:Cmd2GeneralConsolewriting toself.stdoutProgressbar on the same kind of console, including how to printwhile the bar is active (
progress.console.print()rather than the print methods),transient=True, multiple bars, custom columns, andtrack()they are animated depends on
allow_style, and their text is parsed for markup tags and emojicodes
endparameter, which Rich does notstrip, for those who want to write the escape sequences themselves
Example
Adds
examples/rich_progress.pyand lists it inexamples/README.md. Its commands are:status- a spinner with a status messageprogress- a progress bar with messages printed above it while it runsdownloads- several transient progress bars with custom columns updating at the same timetrack- a progress bar added to a loop withrich.progress.track()README and CHANGELOG
Mentions progress bars in the README's "Build more with less code" list, linking to the new
documentation, and adds CHANGELOG entries for the bug fix and the example under a new 4.4.3 heading.
Testing
tests/test_cmd2.pycover a command whose own console writes to a broken pipe(stdout itself, a
cmd | shellpipe, a command run by a piped script, and a finalization hook),with and without
broken_pipe_warning. They also cover what must not be hidden: a console onanother stream, a
KeyboardInterruptorSystemExitthe broken pipe replaced, and aBrokenPipeErrorthe command raised itself with no redirection, when piped, and when redirectedto a file. The tests for new behavior were written first and seen to fail. Those which need a real
broken pipe are skipped on Windows, where a closed pipe can raise a different
OSErrorthatcmd2has never handledpseudo-terminal, with output redirected to a file, and (for the example) interrupted with Ctrl-C
and piped to commands which exit early, from inside the application and from the shell
allow_style, markup, emoji, and styled-string behavior described in the documentation wasreproduced against Rich 15.0.0
make check,make docs-test, andmake testpassCloses #1808