How to capture output with `%%capture` in IPython
By Deepnote team
•Updated on November 23, 2023
Using `%%capture` to manage output in IPython notebooks.
In IPython, the %%capture
cell magic is a powerful tool for controlling the output of a cell. It can either suppress or store the output, including standard output (stdout
), standard error (stderr
), and even rich display outputs like plots. Here's a guide on how to use %%capture
effectively.
Basics of %%capture
- Suppressing Output: By default,
%%capture
suppresses the output from a cell. This is useful for hiding output that is not needed.
%%capture
print('hi, stdout')
print('hi, stderr', file=sys.stderr)
- Storing Output You can store the output in a variable by specifying a name after
%%capture
.
%%capture captured
print('hi, stdout')
print('hi, stderr', file=sys.stderr)
captured
<IPython.utils.capture.CapturedIO at 0x2c06a2914>
Retrieving and Using Captured Output
Accessing Captured Output: After capturing the output in a variable, you can access it:
# Display captured output
captured()
hi, stdout
hi, stderr
Access stdout and stderr separately:
print(captured.stdout)
hi, stdout
print(captured.stderr)
hi, stderr
Captured Output Object: The captured output is stored in an IPython.utils.capture.CapturedIO
object, allowing separate access to stdout
and stderr
.
Advanced Uses of %%capture
Capturing Rich Output: %%capture
is not limited to text output; it can also capture rich outputs like plots.
%%capture capture
print("setting up X")
x = np.linspace(0,5,1000)
y = np.sin(x)
print("hello")
plt.plot(x,y)
captured2()
hello
Selective Capturing: You can choose to capture only stdout
, stderr
, or rich display outputs by using flags like --no-stdout
, --no-stderr
, and --no-display
.
%%capture cap --no-stderr
print('hi, stdout')
print("hello, stderr", file=sys.stderr)
Summary
%%capture
in IPython is a versatile tool for controlling cell output. It's useful for suppressing unwanted output, storing output for later use, and even capturing rich display outputs like plots. By understanding how to use %%capture
effectively, you can manage the output of your Jupyter notebooks more efficiently, making them cleaner and more focused on the results that matter.