Generating Output

how to generate output

  • poutput
  • perror
  • paging
  • exceptions
  • color support

Standard cmd applications produce their output with self.stdout.write('output') (or with print, but print decreases output flexibility). cmd2 applications can use self.poutput('output'), self.pfeedback('message'), self.perror('errmsg'), and self.ppaged('text') instead. These methods have these advantages:

  • Handle output redirection to file and/or pipe appropriately
  • More concise
    • .pfeedback() destination is controlled by quiet parameter.
  • Option to display long output using a pager via ppaged()
Cmd.poutput(msg: Any, *, end: str = '\n') → None

Print message to self.stdout and appends a newline by default

Also handles BrokenPipeError exceptions for when a commands’s output has been piped to another process and that process terminates before the cmd2 command is finished executing.

  • msg – message to print (anything convertible to a str with ‘{}’.format() is OK)
  • end – string appended after the end of the message, default a newline
static Cmd.perror(msg: Any, *, end: str = '\n', apply_style: bool = True) → None

Print message to sys.stderr

  • msg – message to print (anything convertible to a str with ‘{}’.format() is OK)
  • end – string appended after the end of the message, default a newline
  • apply_style – If True, then ansi.style_error will be applied to the message text. Set to False in cases where the message text already has the desired style. Defaults to True.
Cmd.pfeedback(msg: str) → None

For printing nonessential feedback. Can be silenced with quiet. Inclusion in redirected output is controlled by feedback_to_output.

Cmd.ppaged(msg: str, end: str = '\n', chop: bool = False) → None

Print output using a pager if it would go off screen and stdout isn’t currently being redirected.

Never uses a pager inside of a script (Python or text) or when output is being redirected or piped or when stdout or stdin are not a fully functional terminal.

  • msg – message to print to current stdout (anything convertible to a str with ‘{}’.format() is OK)
  • end – string appended after the end of the message if not already present, default a newline
  • chop
    True -> causes lines longer than the screen width to be chopped (truncated) rather than wrapped
    • truncated text is still accessible by scrolling with the right & left arrow keys
    • chopping is ideal for displaying wide tabular data as is done in utilities like pgcli
    False -> causes lines longer than the screen width to wrap to the next line
    • wrapping is ideal when you want to keep users from having to use horizontal scrolling

WARNING: On Windows, the text always wraps regardless of what the chop argument is set to

Suppressing non-essential output

The quiet setting controls whether self.pfeedback() actually produces any output. If quiet is False, then the output will be produced. If quiet is True, no output will be produced.

This makes self.pfeedback() useful for non-essential output like status messages. Users can control whether they would like to see these messages by changing the value of the quiet setting.

Output Redirection

As in a Unix shell, output of a command can be redirected:

  • sent to a file with >, as in mycommand args > filename.txt
  • appended to a file with >>, as in mycommand args >> filename.txt
  • piped (|) as input to operating-system commands, as in mycommand args | wc


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:

from cmd2 import Cmd
class App(Cmd):
    def __init__(self):
        self.allow_redirection = False

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.

If you need to include any of these redirection characters in your command, you can enclose them in quotation marks, mycommand 'with > in the argument'.

Colored Output

The output methods in the previous section all honor the allow_ansi setting, which has three possible values:

poutput(), pfeedback(), and ppaged() strip all ANSI escape sequences which instruct the terminal to colorize output
(the default value) poutput(), pfeedback(), and ppaged() do not strip any ANSI escape sequences when the output is a terminal, but if the output is a pipe or a file the escape sequences are stripped. If you want colorized output you must add ANSI escape sequences using either cmd2’s internal ansi module or another color library such as plumbum.colors, colorama, or colored.
poutput(), pfeedback(), and ppaged() never strip ANSI escape sequences, regardless of the output destination

Colored and otherwise styled output can be generated using the function:*, fg: str = '', bg: str = '', bold: bool = False, underline: bool = False) → str

Styles a string with ANSI colors and/or styles and returns the new string.

The styling is self contained which means that at the end of the string reset code(s) are issued to undo whatever styling was done at the beginning.

  • text – Any object compatible with str.format()
  • fg – foreground color. Relies on fg_lookup() to retrieve ANSI escape based on name. Defaults to no color.
  • bg – background color. Relies on bg_lookup() to retrieve ANSI escape based on name. Defaults to no color.
  • bold – apply the bold style if True. Defaults to False.
  • underline – apply the underline style if True. Defaults to False.

the stylized string