禁用输出缓冲

2024-04-25 23:43:33 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

迄今为止的建议:

  1. 使用-u命令行开关
  2. 在每次写入后刷新的对象中包装sys.stdout
  3. 设置PYTHONUNBUFFERED环境变量
  4. sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)

有没有其他方法可以在执行期间以编程方式在sys/sys.stdout中设置一些全局标志?


Tags: 对象方法答案命令行os编程stdoutsys
3条回答

我宁愿把我的答案放在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):

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

来自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)
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)

Credits:“Sebastian”,在Python邮件列表的某个地方。

相关问题 更多 >