You can skip buffering for a whole
python process using "python -u"
(or#!/usr/bin/env python -u etc) or by
setting the environment variable
PYTHONUNBUFFERED.
You could also replace sys.stdout with
some other stream like wrapper which
does a flush after every call.
# reopen stdout file descriptor with write mode
# and 0 as the buffer size (unbuffered)
import io, os, sys
try:
# Python 3, open as binary, then wrap in a TextIOWrapper, and write through
# everything. Alternatively, use line_buffering=True to flush on newlines.
unbuffered = io.TextIOWrapper(open(sys.stdout.fileno(), 'wb', 0), write_through=True)
except TypeError:
# Python 2
unbuffered = os.fdopen(sys.stdout.fileno(), 'w', 0)
我宁愿把我的答案放在How to flush output of print function?或Python's print function that flushes the buffer when it's called?中,但由于它们被标记为这个答案的副本(我不同意),所以我将在这里回答它。
由于Python 3.3,print()支持关键字参数“flush”(see documentation):
来自Magnus Lycka answer on a mailing list:
Credits:“Sebastian”,在Python邮件列表的某个地方。
相关问题 更多 >
编程相关推荐