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

问题描述 投票:12回答:1

我希望能够将iPython笔记本单元的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()时,它似乎没有显示。相反,它将输出放入cap变量两次。

ipython ipython-notebook ipython-magic
1个回答
14
投票

你有一个错字,在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)
© www.soinside.com 2019 - 2024. All rights reserved.