如何在iPython笔记本中保存单元格的输出?

时间:2015-01-16 22:58:50

标签: ipython ipython-notebook ipython-magic

我希望能够将iPython笔记本 cell 的TEXT输出保存到磁盘上的文件中。

我有2个额外的要求/要求:

  • 能够重新运行单元格并用最新的输出覆盖我的输出。
  • 还会在笔记本中显示输出。

我已经想出如何使用%%capture魔法将iPython笔记本电脑的基本单元保存到一个文件中,但它看起来不够灵活:每当我重新使用它时它会保持附加状态运行单元格,我不能让它显示在同一个单元格中。

这是我到目前为止所做的:

%%capture cap --no-stderr
print 'stuff'
with open('output.txt', 'w') as f:
    f.write(cap.stdout)

# clear the cap by deleting the variable here?
# del cap 

当我在写入后尝试放置cap.show()时,似乎没有显示。相反,它将输出放入上限变量两次。

2 个答案:

答案 0 :(得分:12)

您在d中输入错误cap.stout。它应该是cap.stdout 我测试了以下内容并且工作正常。 cap.show()还打印了“stuff”并重新运行单元格覆盖了文件。

%%capture cap --no-stderr
print 'stuff'
with open('output.txt', 'w') as f:
    f.write(cap.stdout)

答案 1 :(得分:0)

%%capture cap --no-stderr
print("a")
with open('output.txt', 'w') as f:
    f.write(str(cap))
相关问题