问题描述
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笔记本:
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笔记本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!