How to flush output of print function?

2018-12-31 01:16发布

How do I force Python's print function to output to the screen?

This is not a duplicate of Disable output buffering - the linked question is attempting unbuffered output, while this is more general. The top answers in that question are too powerful or involved for this one (they're not good answers for this), and this question can be found on Google by a relative newbie.

14条回答
无与为乐者.
2楼-- · 2018-12-31 01:23

Also as suggested in this blog one can reopen sys.stdout in unbuffered mode:

sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)

Each stdout.write and print operation will be automatically flushed afterwards.

查看更多
倾城一夜雪
3楼-- · 2018-12-31 01:23

I did it like this in Python 3.4:

'''To write to screen in real-time'''
message = lambda x: print(x, flush=True, end="")
message('I am flushing out now...')
查看更多
伤终究还是伤i
4楼-- · 2018-12-31 01:24

Loved Dan's solution! For python3 do:

import io,sys
class flushfile:
    def __init__(self, f):
        self.f = f
    def write(self, x):
        self.f.write(x)
        self.f.flush()
sys.stdout = flushfile(sys.stdout)
查看更多
春风洒进眼中
5楼-- · 2018-12-31 01:30

Running python -h, I see a command line option:

-u : unbuffered binary stdout and stderr; also PYTHONUNBUFFERED=x see man page for details on internal buffering relating to '-u'

Here is the relevant doc.

查看更多
梦该遗忘
6楼-- · 2018-12-31 01:32

With Python 3.x the print() function has been extended:

print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)

So, you can just do:

print("Visiting toilet", flush=True)

Python Docs Entry

查看更多
余欢
7楼-- · 2018-12-31 01:32

Why not try using an unbuffered file?

f = open('xyz.log', 'a', 0)

OR

sys.stdout = open('out.log', 'a', 0)
查看更多
登录 后发表回答