实时python打印功能 [英] python print function in real time

查看:168
本文介绍了实时python打印功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近切换了操作系统,并正在使用更新的Python(2.7).在旧系统上,我曾经能够即时打印.例如,假设我有一个计算密集的for循环:

I recently switched OS and am using a newer Python (2.7). On my old system, I used to be able to print instantaneously. For instance, suppose I had a computationally intense for loop:

for i in range(10):
  huge calculation
  print i

然后,当代码完成每次迭代时,它将打印i

then as the code completed each iteration, it would print i

但是,在我当前的系统上,python似乎缓存了stdout,以便终端空白几分钟,然后打印:

However, on my current system, python seems to cache the stdout so that the terminal is blank for several minutes, after which it prints:


1
2
3

一小段时间.然后,几分钟后,它将打印:

in short succession. Then, after a few more minutes, it prints:


4
5
6

,依此类推.到达print语句后,如何使python打印?

and so on. How can I make python print as soon as it reaches the print statement?

推荐答案

尝试在打印后调用标准输出的刷新

Try to call flush of stdout after the print

import sys

...
sys.stdout.flush()

或使用命令行选项-u,其中:

Or use a command line option -u which:

强制完全不缓冲stdin,stdout和stderr.

Force stdin, stdout and stderr to be totally unbuffered.

这篇关于实时python打印功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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