使ipython笔记本实时打印

时间:2015-04-21 12:24:20

标签: python buffer ipython-notebook

Ipython Notebook似乎没有实时打印结果,但似乎以某种方式缓冲,然后批量输出打印件。如何在处理打印命令后立即使ipython打印我的结果?

示例代码:

import time


def printer():
    for i in range(100):
        time.sleep(5)
        print i

假设上述代码位于导入的文件中。我怎么能认为当我打电话给打印机功能时,它每5秒打一个数字而不是最后的所有数字?

请注意,我无法编辑函数printer(),因为我是从某个外部模块获取的。我希望以某种方式更改ipython笔记本的配置,以便它不使用缓冲区。因此,我也不希望使用sys.stdout.flush(),我想根据问题实时进行,我不希望任何缓冲区开始。

我也尝试使用以下命令加载ipython notebook:

ipython notebook --cache-size=0

但这似乎也不起作用。

3 个答案:

答案 0 :(得分:14)

one of the answersCarsten建议的__getattr__代表团的评论中,diedthreetimes建议的问题只是money and smallmoney (Transact-SQL).

import sys
oldsysstdout = sys.stdout
class flushfile():
    def __init__(self, f):
        self.f = f
    def __getattr__(self,name): 
        return object.__getattribute__(self.f, name)
    def write(self, x):
        self.f.write(x)
        self.f.flush()
    def flush(self):
        self.f.flush()
sys.stdout = flushfile(sys.stdout)

在原始答案中,未实现__getattr__方法。没有它,它失败了。该问题的答案中的其他变体也在笔记本中失败。

在笔记本中,sys.stdoutIPython.kernel.zmq.iostream.OutStream的一个实例,并且通常sys.stdout中没有多种方法和属性。委派__getattr__允许flushfile伪装成...zmq.iostream.OutStream鸭子。

这适用于使用ipython 3.1.0运行的python 2.7笔记本

答案 1 :(得分:7)

自Python 3.3起,print()有一个additional flush参数可用于强制刷新:

for i in range(10):
    print(i, flush=True)
    time.sleep(1)  

答案 2 :(得分:1)

尝试一下:

from IPython.display import display, clear_output

display("Hello World") # print string
display(df) # print object such as dataframe

clear_output(wait=True) # use this if need to clear the output before display, good for dynamic updates
相关问题