Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

added a new parameter for method capture(echo) #2697

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Added

- Add type annotation for key_separator of pretty.Node https://github.com/Textualize/rich/issues/2625
- Add new parameter for capture method called echo. https://github.com/Textualize/rich/issues/2338


## [12.6.0] - 2022-10-02
Expand Down
1 change: 1 addition & 0 deletions CONTRIBUTORS.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ The following people have contributed to the development of Rich:
- [Ed Davis](https://github.com/davised)
- [Pete Davison](https://github.com/pd93)
- [James Estevez](https://github.com/jstvz)
- [Sertug Fidan](https://github.com/SertugF)
- [Oleksis Fraga](https://github.com/oleksis)
- [Andy Gimblett](https://github.com/gimbo)
- [Michał Górny](https://github.com/mgorny)
Expand Down
4 changes: 2 additions & 2 deletions docs/source/console.rst
Original file line number Diff line number Diff line change
Expand Up @@ -313,10 +313,10 @@ Note that when writing to a file you may want to explicitly set the ``width`` ar
Capturing output
----------------

There may be situations where you want to *capture* the output from a Console rather than writing it directly to the terminal. You can do this with the :meth:`~rich.console.Console.capture` method which returns a context manager. On exit from this context manager, call :meth:`~rich.console.Capture.get` to return the string that would have been written to the terminal. Here's an example::
There may be situations where you want to *capture* the output from a Console without writing it directly to the terminal. You can do this with the :meth:`~rich.console.Console.capture` method using echo parameter which returns a context manager. If echo value is set to True(default) text is captured and written to the terminal. When echo value is set to False text captured but not written to the terminal. On exit from this context manager, call :meth:`~rich.console.Capture.get` to return the string that would have been written to the terminal. Here's an example::
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

default should be False, given that this was the default before

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Check #2338 "The capture method should have an echo parameter. When echo=True (the default) text should be captured and written to the terminal. When echo=False the text should be captured but not written to the terminal." @willmcgugan wants it true default.


from rich.console import Console
console = Console()
console = Console(echo=False)
with console.capture() as capture:
console.print("[bold red]Hello[/] World")
str_output = capture.get()
Expand Down
18 changes: 13 additions & 5 deletions rich/console.py
Original file line number Diff line number Diff line change
Expand Up @@ -327,9 +327,10 @@ class Capture:
console (Console): A console instance to capture output.
"""

def __init__(self, console: "Console") -> None:
def __init__(self, console: "Console", echo: bool = True) -> None:
self._console = console
self._result: Optional[str] = None
self.echo = echo

def __enter__(self) -> "Capture":
self._console.begin_capture()
Expand All @@ -342,6 +343,9 @@ def __exit__(
exc_tb: Optional[TracebackType],
) -> None:
self._result = self._console.end_capture()
if self.echo:
# print to the original console
self._console.print(self._result, end="")

def get(self) -> str:
"""Get the result of the capture."""
Expand Down Expand Up @@ -1080,9 +1084,12 @@ def bell(self) -> None:
"""Play a 'bell' sound (if supported by the terminal)."""
self.control(Control.bell())

def capture(self) -> Capture:
def capture(self, echo: bool = True) -> Capture:
"""A context manager to *capture* the result of print() or log() in a string,
rather than writing it to the console.
rather than writing it to the console depending on the echo argument.

Args:
echo (bool, optional): Echos captured string to terminal. Defaults to True.

Example:
>>> from rich.console import Console
Expand All @@ -1092,9 +1099,10 @@ def capture(self) -> Capture:
>>> print(capture.get())

Returns:
Capture: Context manager with disables writing to the terminal.
Capture: Context manager depending on echo argument disables writing to the terminal.
"""
capture = Capture(self)

capture = Capture(self, echo=echo)
return capture

def pager(
Expand Down
22 changes: 21 additions & 1 deletion tests/test_console.py
Original file line number Diff line number Diff line change
Expand Up @@ -384,7 +384,7 @@ def test_capture_and_record(capsys):
recorder = Console(record=True)
recorder.print("ABC")

with recorder.capture() as capture:
with recorder.capture(echo=False) as capture:
recorder.print("Hello")

assert capture.get() == "Hello\n"
Expand All @@ -397,6 +397,26 @@ def test_capture_and_record(capsys):
assert out == "ABC\n"


def test_capture_and_record_multiple(capsys):
recorder = Console(record=True)

with recorder.capture(echo=False) as capture:
recorder.print("Hello")
recorder.print("World")

assert capture.get() == "Hello\nWorld\n"

with recorder.capture(echo=True) as capture:
recorder.print("Foo")
recorder.print("Bar")

assert capture.get() == "Foo\nBar\n"

out, err = capsys.readouterr()

assert out == "Foo\nBar\n"


def test_input(monkeypatch, capsys):
def fake_input(prompt=""):
console.file.write(prompt)
Expand Down