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

Nic*_*ivi 3 python ipython jupyter-notebook

在基于 ipython 的 jupyter 笔记本中,我有一个打印内容的功能。我无法更改此功能,因为它来自库。让我们来

def print_something():
    print("something")
Run Code Online (Sandbox Code Playgroud)

举个例子。当我print_something()在一个单元格中运行时,我想将单元格打印的任何内容保存在一个文件中。我怎么做?我试过%saveand %logstart,但由于print没有创建输出,他们没有做我想要的。

Nic*_*ivi 13

感谢评论,我在另一个问题中找到了答案:

%%capture cap --no-stderr
print_something()

with open('/path/to/capture.txt') as f:
    f.write(cap.stdout)
Run Code Online (Sandbox Code Playgroud)

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