在Python的sys.stdout解释器中默认启用输出缓冲吗?

如果答案是肯定的,那么有哪些方法可以禁用它?

目前的建议:

使用-u命令行开关 包装系统。每次写入后刷新的对象中的标准输出 设置PYTHONUNBUFFERED env变量 sys。Stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)

是否有其他方法在sys/sys中设置全局标志。在执行期间以编程方式Stdout ?


如果只是想在使用打印的特定写入之后刷新,请参阅如何刷新打印函数的输出?。


当前回答

在Python 3中,你可以修补打印函数,以始终发送flush=True:

_orig_print = print

def print(*args, **kwargs):
    _orig_print(*args, flush=True, **kwargs)

正如在评论中指出的,你可以通过functools.partial将flush形参绑定到一个值来简化这一点:

print = functools.partial(print, flush=True)

其他回答

你也可以使用stdbuf实用程序运行Python:

stdbuf -oL蟒蛇<脚本>

来自Magnus Lycka在邮件列表上的回答:

You can skip buffering for a whole python process using python -u 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)
import io, os, sys
try:
    # Python 3, open as binary, then wrap in a TextIOWrapper with write-through.
    sys.stdout = io.TextIOWrapper(open(sys.stdout.fileno(), 'wb', 0), write_through=True)
    # If flushing on newlines is sufficient, as of 3.7 you can instead just call:
    # sys.stdout.reconfigure(line_buffering=True)
except TypeError:
    # Python 2
    sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)

工作人员:“塞巴斯蒂安”,在Python邮件列表的某个地方。

我宁愿把我的答案放在如何刷新打印功能的输出?或者在Python的print函数中,当它被调用时,会刷新缓冲区?,但由于它们被标记为这一个的副本(我不同意),我将在这里回答它。

从Python 3.3开始,print()支持关键字参数"flush"(参见文档):

print('Hello World!', flush=True)

在Python 3中,你可以修补打印函数,以始终发送flush=True:

_orig_print = print

def print(*args, **kwargs):
    _orig_print(*args, flush=True, **kwargs)

正如在评论中指出的,你可以通过functools.partial将flush形参绑定到一个值来简化这一点:

print = functools.partial(print, flush=True)