使 ipython notebook 实时打印 [英] Make ipython notebook print in real time
问题描述
Ipython Notebook 似乎无法实时打印结果,但似乎以某种方式进行缓冲,然后批量输出打印结果.如何在处理打印命令后立即让 ipython 打印我的结果?
Ipython Notebook doesn't seem to print results in real time, but seems to buffer in a certain way and then bulk output the prints. How can I make ipython print my results as soon as the print command is processed?
示例代码:
import time
def printer():
for i in range(100):
time.sleep(5)
print i
假设上面的代码在一个导入的文件中.我怎么能做到当我调用打印机函数时,它每 5 秒打印一个数字,而不是最后打印一个数字?
Supposing that the above code is in a file that is imported. How could I make it that when I call the printer function it prints a number every 5 seconds and not all the numbers at the very end?
请注意,我无法编辑函数 printer()
,因为它是从某个外部模块获取的.我希望以某种方式更改 ipython notebook 的配置,以便它不使用缓冲区.因此,我也不想使用 sys.stdout.flush(),我想根据问题实时执行,我不希望任何缓冲区开始.
Please note that I cannot edit the function printer()
because I get it from some external module. I want the to change the configs of ipython notebook somehow so that it doesn't use a buffer. Therefore, I also do not wish to use sys.stdout.flush(), I want to do it in real-time according to the question, I don't want any buffer to start with.
我也尝试使用以下命令加载 ipython notebook:
I also tried loading ipython notebook with the command:
ipython notebook --cache-size=0
但这似乎也不起作用.
推荐答案
从 Python 3.3 开始,print()
有一个 附加刷新 可用于强制刷新的参数:
Since Python 3.3, print()
has an additional flush argument that can be used to force flushing:
for i in range(10):
print(i, flush=True)
time.sleep(1)
这篇关于使 ipython notebook 实时打印的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!