Sometimes you may want to store the output of IPython (Jupyter) line magic, cell magic, and other output in an object (variable) instead of the standard output and process it later. (Example: I want the output, not the return value of the executed function)
It may not be a very complimented method, but I will implement it by temporarily skipping the output destination of sys.stdout
to StringIO
.
try:
from io import StringIO # Python3
except:
from cStringIO import StringIO # Python2
import sys
old_stdout = sys.stdout
sys.stdout = mystdout = StringIO()
%% time
%%time
for i in range(1000000):
i ** 2
sys.stdout = old_stdout
clock_times = mystdout.getvalue()
print(clock_times)
CPU times: user 467 ms, sys: 0 ns, total: 467 ms
Wall time: 469 ms
Recommended Posts