如何捕获基于 ipython 的 jupyter notebook 中打印的所有内容?

How to capture everything that is printed in a jupyter notebook based on ipython?

在基于 ipython 的 jupyter notebook 中,我有一个打印内容的功能。我无法更改此功能,因为它来自图书馆。让我们来看看

def print_something():
    print("something")

举个例子。当我 运行 print_something() 在一个单元格中时,我想将单元格正在打印的任何内容保存在一个文件中。我怎么做?我尝试了 %save%logstart,但是由于 print 没有创建输出,所以它们没有按照我的要求进行。

感谢评论,我在另一个 :

中找到了答案
%%capture cap --no-stderr
print_something()

with open('/path/to/capture.txt') as f:
    f.write(cap.stdout)

文档:https://ipython.readthedocs.io/en/stable/interactive/magics.html#cellmagic-capture