如何在IPython中刷新打印的语句 [英] How to flush the printed statements in IPython

查看:139
本文介绍了如何在IPython中刷新打印的语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的函数循环期间打印一些调试语句,我使用IPython来调用该函数。让一个示例函数为:

I want to print some debug statements during a loop in my function and I use IPython to call the function. Let an example function be:

def test_print():
    import time
    for i in range(5):
        time.sleep(2)
        print i,  time.time()

结果如下:

0 1372337149.84
1 1372337151.84
2 1372337153.85
3 1372337155.85
4 1372337157.85

我希望每行都打印,然后等待2秒。但行为如下。我首先观察:

I expect each row to be printed, then wait for 2 seconds. But the behavior is as follows. I first observe:

0 1372337149.84
1 

然后,在2秒后,我观察到 1 的时间戳和下一行的ID,即 2 。我终于看到了最后一张时间戳。我无法弄清楚为什么它表现得像这样,而不是一次一行。有什么想法吗?我需要一个特殊的刷新功能来打印等待打印的内容吗?

Then, after 2 seconds I observe the time stamp of 1 and the id of the next row, which is 2. I observe the last time stamp finally. I couldn't figure out why it behaves like this instead of one row at a time. Any thoughts? Do I need a special flush function to print what is waiting to be printed?

推荐答案

我从未使用过IPython,但它应该足以在每个 print 语句后刷新标准输出。

I've never used IPython, but it should suffice to flush stdout after each print statement.

这样的事情应该有效......

Something like this ought to work...

def test_print():
    import time
    import sys
    for i in range(5):
        time.sleep(2)
        print i,  time.time()
        sys.stdout.flush()

这篇关于如何在IPython中刷新打印的语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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