Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,15 @@
## 3.4.0 (TBD)

- Enhancements
- Moved cmd2-specific printing logic from `Cmd.print_to()` into `Cmd2BaseConsole.print()` and
`Cmd2BaseConsole.log()`. This removes need to pass a console object to `Cmd.print_to()`.
- Addressed a bug in `rich.console.Console` where complex renderables (like `Table` and `Rule`)
may not receive formatting settings passed to `console.print()` and `console.log()`.

- Breaking Changes
- Renamed the `destination` parameter of `Cmd.print_to()` back to `file` since you can no longer
pass in a console.

## 3.3.0 (March 1, 2026)

- Enhancements
Expand Down
145 changes: 43 additions & 102 deletions cmd2/cmd2.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,6 @@

import rich.box
from rich.console import (
Console,
Group,
RenderableType,
)
Expand Down Expand Up @@ -1252,66 +1251,30 @@ def visible_prompt(self) -> str:

def print_to(
self,
destination: IO[str] | Cmd2BaseConsole,
file: IO[str],
*objects: Any,
sep: str = " ",
end: str = "\n",
style: StyleType | None = None,
soft_wrap: bool | None = None,
emoji: bool | None = None,
markup: bool | None = None,
highlight: bool | None = None,
soft_wrap: bool = True,
emoji: bool = False,
markup: bool = False,
highlight: bool = False,
rich_print_kwargs: RichPrintKwargs | None = None,
**kwargs: Any, # noqa: ARG002
) -> None:
"""Print objects to a given destination (file stream or cmd2 console).

If ``destination`` is a file-like object, it is wrapped in a ``Cmd2GeneralConsole``
which is configured for general-purpose printing. By default, it enables soft wrap and
disables Rich's automatic detection for markup, emoji, and highlighting. These defaults
can be overridden by passing explicit keyword arguments.

If ``destination`` is a ``Cmd2BaseConsole``, the console's default settings for
soft wrap, markup, emoji, and highlighting are used unless overridden by passing
explicit keyword arguments.

See the Rich documentation for more details on emoji codes, markup tags, and highlighting.

**Why use this method instead of console.print()?**

This method calls ``cmd2.rich_utils.prepare_objects_for_rendering()`` on the objects
being printed. This ensures that strings containing ANSI style sequences are converted
to Rich Text objects, so that Rich can correctly calculate their display width when
printing.

Example:
```py
with console.capture() as capture:
self.print_to(console, some_ansi_styled_string)
```

!!! note

To ensure consistent behavior, this method requires a file-like object or
an instance of ``Cmd2BaseConsole``.
Consoles not derived from ``Cmd2BaseConsole`` are disallowed because:
"""Print objects to a given file stream.

1. **Style Control**: They ignore the global ``ALLOW_STYLE`` setting.
2. **Theming**: They do not respect the application-wide ``APP_THEME``.
3. **Error Handling**: They trigger a ``SystemExit`` on broken pipes.
``Cmd2BaseConsole`` instead raises a catchable ``BrokenPipeError``,
ensuring the CLI application remains alive if a pipe is closed.
This method is configured for general-purpose printing. By default, it enables
soft wrap and disables Rich's automatic detection for markup, emoji, and highlighting.
These defaults can be overridden by passing explicit keyword arguments.

:param destination: The output target. File-like objects are automatically
wrapped in a ``Cmd2GeneralConsole`` to ensure they respect
cmd2 global settings; otherwise, this must be an
instance of ``Cmd2BaseConsole``.
:param file: file stream being written to
:param objects: objects to print
:param sep: string to write between printed text. Defaults to " ".
:param end: string to write at end of printed text. Defaults to a newline.
:param style: optional style to apply to output
:param soft_wrap: Enable soft wrap mode. Defaults to None.
If None, the destination console's default behavior is used.
:param soft_wrap: Enable soft wrap mode. Defaults to True.
If True, text that doesn't fit will run on to the following line,
just like with print(). This is useful for raw text and logs.
If False, Rich wraps text to fit the terminal width.
Expand All @@ -1320,44 +1283,23 @@ def print_to(
For example, when soft_wrap is True Panels truncate text
which is wider than the terminal.
:param emoji: If True, Rich will replace emoji codes (e.g., :smiley:) with their
corresponding Unicode characters. Defaults to None.
If None, the destination console's default behavior is used.
corresponding Unicode characters. Defaults to False.
:param markup: If True, Rich will interpret strings with tags (e.g., [bold]hello[/bold])
as styled output. Defaults to None.
If None, the destination console's default behavior is used.
as styled output. Defaults to False.
:param highlight: If True, Rich will automatically apply highlighting to elements within
strings, such as common Python data types like numbers, booleans, or None.
This is particularly useful when pretty printing objects like lists and
dictionaries to display them in color. Defaults to None.
If None, the destination console's default behavior is used.
dictionaries to display them in color. Defaults to False.
:param rich_print_kwargs: optional additional keyword arguments to pass to Rich's Console.print().
:param kwargs: Arbitrary keyword arguments. This allows subclasses to extend the signature of this
method and still call `super()` without encountering unexpected keyword argument errors.
These arguments are not passed to Rich's Console.print().
:raises TypeError: If ``destination`` is a non-cmd2 ``Console`` instance that
does not derive from ``Cmd2BaseConsole``.

See the Rich documentation for more details on emoji codes, markup tags, and highlighting.
"""
if isinstance(destination, Console):
if not isinstance(destination, Cmd2BaseConsole):
# Explicitly reject non-cmd2 consoles to ensure safe behavior
raise TypeError(
f"destination must be a 'Cmd2BaseConsole' or a file-like object, "
f"not a non-cmd2 '{type(destination).__name__}'. "
"Consoles not derived from 'Cmd2BaseConsole' bypass cmd2's "
"'ALLOW_STYLE' logic, 'APP_THEME' settings, and trigger 'SystemExit' "
"on broken pipes."
)
console = destination
else:
# It's a file-like object (e.g., sys.stdout, StringIO)
console = Cmd2GeneralConsole(file=destination)

prepared_objects = ru.prepare_objects_for_rendering(*objects)

try:
console.print(
*prepared_objects,
Cmd2BaseConsole(file=file).print(
*objects,
sep=sep,
end=end,
style=style,
Expand All @@ -1373,7 +1315,7 @@ def print_to(
# writing. If you would like your application to print a
# warning message, then set the broken_pipe_warning attribute
# to the message you want printed.
if self.broken_pipe_warning and console.file != sys.stderr:
if self.broken_pipe_warning and file != sys.stderr:
Cmd2GeneralConsole(file=sys.stderr).print(self.broken_pipe_warning)

def poutput(
Expand All @@ -1382,10 +1324,10 @@ def poutput(
sep: str = " ",
end: str = "\n",
style: StyleType | None = None,
soft_wrap: bool | None = None,
emoji: bool | None = None,
markup: bool | None = None,
highlight: bool | None = None,
soft_wrap: bool = True,
emoji: bool = False,
markup: bool = False,
highlight: bool = False,
rich_print_kwargs: RichPrintKwargs | None = None,
**kwargs: Any, # noqa: ARG002
) -> None:
Expand All @@ -1412,10 +1354,10 @@ def perror(
sep: str = " ",
end: str = "\n",
style: StyleType | None = Cmd2Style.ERROR,
soft_wrap: bool | None = None,
emoji: bool | None = None,
markup: bool | None = None,
highlight: bool | None = None,
soft_wrap: bool = True,
emoji: bool = False,
markup: bool = False,
highlight: bool = False,
rich_print_kwargs: RichPrintKwargs | None = None,
**kwargs: Any, # noqa: ARG002
) -> None:
Expand Down Expand Up @@ -1443,10 +1385,10 @@ def psuccess(
*objects: Any,
sep: str = " ",
end: str = "\n",
soft_wrap: bool | None = None,
emoji: bool | None = None,
markup: bool | None = None,
highlight: bool | None = None,
soft_wrap: bool = True,
emoji: bool = False,
markup: bool = False,
highlight: bool = False,
rich_print_kwargs: RichPrintKwargs | None = None,
**kwargs: Any, # noqa: ARG002
) -> None:
Expand All @@ -1471,10 +1413,10 @@ def pwarning(
*objects: Any,
sep: str = " ",
end: str = "\n",
soft_wrap: bool | None = None,
emoji: bool | None = None,
markup: bool | None = None,
highlight: bool | None = None,
soft_wrap: bool = True,
emoji: bool = False,
markup: bool = False,
highlight: bool = False,
rich_print_kwargs: RichPrintKwargs | None = None,
**kwargs: Any, # noqa: ARG002
) -> None:
Expand Down Expand Up @@ -1554,10 +1496,10 @@ def pfeedback(
sep: str = " ",
end: str = "\n",
style: StyleType | None = None,
soft_wrap: bool | None = None,
emoji: bool | None = None,
markup: bool | None = None,
highlight: bool | None = None,
soft_wrap: bool = True,
emoji: bool = False,
markup: bool = False,
highlight: bool = False,
rich_print_kwargs: RichPrintKwargs | None = None,
**kwargs: Any, # noqa: ARG002
) -> None:
Expand Down Expand Up @@ -1602,9 +1544,9 @@ def ppaged(
style: StyleType | None = None,
chop: bool = False,
soft_wrap: bool = True,
emoji: bool | None = None,
markup: bool | None = None,
highlight: bool | None = None,
emoji: bool = False,
markup: bool = False,
highlight: bool = False,
rich_print_kwargs: RichPrintKwargs | None = None,
**kwargs: Any, # noqa: ARG002
) -> None:
Expand Down Expand Up @@ -1646,10 +1588,9 @@ def ppaged(
soft_wrap = True

# Generate the bytes to send to the pager
console = Cmd2GeneralConsole(file=self.stdout)
console = Cmd2BaseConsole(file=self.stdout)
with console.capture() as capture:
self.print_to(
console,
console.print(
*objects,
sep=sep,
end=end,
Expand Down
Loading
Loading