如何在iPython笔记本中保存单元格的输出? [英] how to save the output of a cell in iPython notebook?

查看:200
本文介绍了如何在iPython笔记本中保存单元格的输出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I would like to be able to save the TEXT output of an iPython notebook cell into a file on disk.

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

I have 2 additional requirements/requests:


  • 能够重新运行单元格并用最新的输出覆盖我的输出。

  • 还显示笔记本中的输出。

我已经想出如何使用 %% capture 魔法来将iPython笔记本的单元格基本保存到文件中,但它似乎不够灵活:每当我重新运行单元格时它会不断附加,我无法在同一单元格中显示它。

I have figured out how to use the %%capture magic for some basic saving of an iPython notebook's cell into a file, but it does not seem flexible enough: it keeps appending every time I re-run the cell and I cannot get it to display within the same cell.

这是我到目前为止所拥有的:

Here is what I have so far:

%%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 ()写完后,似乎没有显示。相反,它将输出放入上限变量两次。

When I try to put cap.show() after the write, it does not seem to display. Instead, it puts the output into the cap variable twice.

推荐答案

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

You have a typo, missing d in cap.stout. It should be cap.stdout I tested the following and it worked fine. cap.show() also printed "stuff" and re-running the cell overwrote the file.

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

这篇关于如何在iPython笔记本中保存单元格的输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆