Capture API¶
Output capture and redirection utilities.
Context Managers¶
capture_output¶
pyreprint.core.capture.capture_output(stdout=True, stderr=True)
¶
Context manager to capture stdout and/or stderr.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
stdout
|
bool
|
Whether to capture stdout. |
True
|
stderr
|
bool
|
Whether to capture stderr. |
True
|
Yields:
| Type | Description |
|---|---|
CapturedOutput
|
CapturedOutput object containing captured content. |
Example
with capture_output() as captured: ... print("Hello") ... print("Error", file=sys.stderr) print(captured.stdout) Hello print(captured.stderr) Error
Source code in pyreprint/core/capture.py
redirect_to_file¶
pyreprint.core.capture.redirect_to_file(path, mode='w', stdout=True, stderr=False, encoding='utf-8')
¶
Context manager to redirect output to a file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
Union[str, Path]
|
Path to the output file. |
required |
mode
|
str
|
File open mode ('w' for write, 'a' for append). |
'w'
|
stdout
|
bool
|
Whether to redirect stdout. |
True
|
stderr
|
bool
|
Whether to redirect stderr. |
False
|
encoding
|
str
|
File encoding. |
'utf-8'
|
Yields:
| Type | Description |
|---|---|
IO[str]
|
The opened file object. |
Example
with redirect_to_file("output.txt") as f: ... print("This goes to the file")
Source code in pyreprint/core/capture.py
Classes¶
CapturedOutput¶
pyreprint.core.capture.CapturedOutput(stdout='', stderr='')
dataclass
¶
OutputTee¶
pyreprint.core.capture.OutputTee(*destinations, include_stdout=True)
¶
Write to multiple destinations simultaneously.
This class allows output to be sent to multiple file-like objects at once, similar to the Unix 'tee' command.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*destinations
|
TextIO
|
File-like objects to write to. |
()
|
include_stdout
|
bool
|
Whether to include sys.stdout as a destination. |
True
|
Example
with open("log.txt", "w") as f: ... tee = OutputTee(f, include_stdout=True) ... old_stdout = sys.stdout ... sys.stdout = tee ... print("This goes to both console and file") ... sys.stdout = old_stdout
Source code in pyreprint/core/capture.py
Functions¶
activate()
¶
Context manager to activate the tee for stdout.
Example
tee = OutputTee(open("log.txt", "w")) with tee.activate(): ... print("Goes to console and file")
Source code in pyreprint/core/capture.py
add_destination(dest)
¶
flush()
¶
remove_destination(dest)
¶
write(text)
¶
Write to all destinations.
Source code in pyreprint/core/capture.py
OutputBuffer¶
pyreprint.core.capture.OutputBuffer(_lines=list(), _capturing=False)
dataclass
¶
A buffer that collects output and can replay it later.
This is useful for capturing output and then deciding whether to display it based on some condition.
Example
buffer = OutputBuffer() with buffer.capture(): ... print("Line 1") ... print("Line 2") if some_condition: ... buffer.replay()