如何在 iPython 笔记本中保存单元格的输出 [英] How to save the output of a cell in iPython notebook
问题描述
我希望能够将 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.
这是我目前所拥有的:
%%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 变量两次.
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.
推荐答案
你有一个错字,在 cap.stout
中缺少 d
.它应该是 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屋!