python print function in real time

允我心安 提交于 2019-11-27 22:58:06

Try to call flush of stdout after the print

import sys

...
sys.stdout.flush()

Or use a command line option -u which:

Force stdin, stdout and stderr to be totally unbuffered.

Since Python 3.3, you can simply pass flush=True to the print function.

Remi

Import the new print-as-function as in Python 3.x:

from __future__ import print_function

(put the statement at the top of your script/module)

This allows you to replace the new print function with your own:

def print(s, end='\n', file=sys.stdout):
    file.write(s + end)
    file.flush()

The advantage is that this way your script will work just the same when you upgrade one day to Python 3.x.

Ps1: I did not try it out, but the print-as-function might just flush by default.

PS2: you might also be interested in my progressbar example.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!