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

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

目前的建议:

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

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


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


当前回答

获得无缓冲输出的一种方法是使用sys。Stderr而不是sys。Stdout或简单地调用sys.stdout.flush()显式强制执行写操作。

你可以很容易地重定向打印的所有内容:

import sys; sys.stdout = sys.stderr
print "Hello World!"

或者为特定的打印语句重定向:

print >>sys.stderr, "Hello World!"

要重置stdout,你可以这样做:

sys.stdout = sys.__stdout__

其他回答

这与Cristóvão D. Sousa的回答有关,但我还不能评论。

使用Python 3的flush关键字参数以始终拥有未缓冲输出的直接方法是:

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

然后,print将始终直接刷新输出(除非flush=False给出)。

注意,(a)这只回答了部分问题,因为它没有重定向所有输出。但我猜打印是在python中创建输出到stdout/stderr的最常用方法,所以这两行可能涵盖了大多数用例。

注意(b)它只在定义它的模块/脚本中工作。这在编写模块时很好,因为它不会混淆sys.stdout。

Python 2不提供flush参数,但您可以模拟Python 3类型的打印函数,如此处所述https://stackoverflow.com/a/27991478/3734258。

def disable_stdout_buffering():
    # Appending to gc.garbage is a way to stop an object from being
    # destroyed.  If the old sys.stdout is ever collected, it will
    # close() stdout, which is not good.
    gc.garbage.append(sys.stdout)
    sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)

# Then this will give output in the correct order:
disable_stdout_buffering()
print "hello"
subprocess.call(["echo", "bye"])

不拯救旧的系统。Stdout, disable_stdout_buffering()不是幂等的,多次调用将导致这样的错误:

Traceback (most recent call last):
  File "test/buffering.py", line 17, in <module>
    print "hello"
IOError: [Errno 9] Bad file descriptor
close failed: [Errno 9] Bad file descriptor

另一种可能性是:

def disable_stdout_buffering():
    fileno = sys.stdout.fileno()
    temp_fd = os.dup(fileno)
    sys.stdout.close()
    os.dup2(temp_fd, fileno)
    os.close(temp_fd)
    sys.stdout = os.fdopen(fileno, "w", 0)

(附加到gc。垃圾并不是一个好主意,因为它是放置不可释放循环的地方,您可能需要检查它们。)

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

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

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

您可以创建一个未缓冲的文件,并将该文件分配给sys.stdout。

import sys 
myFile= open( "a.log", "w", 0 ) 
sys.stdout= myFile

你不能神奇地改变系统提供的标准输出;因为它是由操作系统提供给python程序的。

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