在基于ipython的jupyter笔记本中,我有一个打印一些东西的函数。由于它来自一个库,我不能更改此功能。我们来看看:
def print_something():
print("something")
以一个例子说明。当我在单元格中运行 print_something()
时,我希望将单元格打印的任何内容保存在文件中。我该怎么做?我尝试了%save
和%logstart
,但由于print
没有创建输出,它们不能满足我的需求。
在基于ipython的jupyter笔记本中,我有一个打印一些东西的函数。由于它来自一个库,我不能更改此功能。我们来看看:
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
--no-stderr
是什么意思? - seralouk--no-stderr
是什么意思? - undefined
。此外,还可以使用
%%capture_img和
%%capture_video`。 - Kolibril