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

poc*_*ese 16 ipython ipython-notebook ipython-magic

我希望能够将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 
Run Code Online (Sandbox Code Playgroud)

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

Ami*_*mit 15

你有一个错字,缺dcap.stout.它应该是cap.stdout 我测试以下,它工作正常.cap.show()还打印"stuff"并重新运行单元格覆盖文件.

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

  • 事实上,“with open('output.txt', 'w') as f: f.write(cap.stdout)”必须位于另一个单元格中。 (4认同)
  • 每次我第一次运行该命令时,都会出现错误,提示“名称上限不存在”。我第二次运行它,它运行良好。 (3认同)
  • 我认为在单元完成执行之前你无法访问“cap” (3认同)