Disable output buffering
Is output buffering enabled by default in Python's interpreter for sys.stdout
?
If the answer is positive, what are all the ways to disable it?
Suggestions so far:
-u
command line switch sys.stdout
in an object that flushes after every write PYTHONUNBUFFERED
env var sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)
Is there any other way to set some global flag in sys
/ sys.stdout
programmatically during execution?
From Magnus Lycka answer on a mailing list:
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.
class Unbuffered(object):
def __init__(self, stream):
self.stream = stream
def write(self, data):
self.stream.write(data)
self.stream.flush()
def writelines(self, datas):
self.stream.writelines(datas)
self.stream.flush()
def __getattr__(self, attr):
return getattr(self.stream, attr)
import sys
sys.stdout = Unbuffered(sys.stdout)
print 'Hello'
# reopen stdout file descriptor with write mode
# and 0 as the buffer size (unbuffered)
sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)
积分:“Sebastian”,在Python邮件列表中的某处。
I would rather put my answer in How to flush output of Python print? or in Python's print function that flushes the buffer when it's called?, but since they were marked as duplicates of this one (what I do not agree), I'll answer it here.
Since Python 3.3 print() supports the keyword argument "flush" (see documentation):
print('Hello World!', flush=True)
链接地址: http://www.djcxy.com/p/77202.html
下一篇: 禁用输出缓冲