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

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

目前的建议:

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

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


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


当前回答

变种,工作不崩溃(至少在win32;Python 2.7, ipython 0.12)然后随后调用(多次):

def DisOutBuffering():
    if sys.stdout.name == '<stdout>':
        sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)

    if sys.stderr.name == '<stderr>':
        sys.stderr = os.fdopen(sys.stderr.fileno(), 'w', 0)

其他回答

是的,默认启用。当调用python时,可以在命令行上使用-u选项禁用它。

您还可以使用fcntl动态更改文件标志。

fl = fcntl.fcntl(fd.fileno(), fcntl.F_GETFL)
fl |= os.O_SYNC # or os.O_DSYNC (if you don't care the file timestamp updates)
fcntl.fcntl(fd.fileno(), fcntl.F_SETFL, fl)
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。垃圾并不是一个好主意,因为它是放置不可释放循环的地方,您可能需要检查它们。)

是的,它是。

您可以在命令行上使用“-u”开关禁用它。

或者,您可以在sys. flush()上调用。每次写入时的Stdout(或使用自动执行此操作的对象将其包装)

重写sys的只写方法是可能的。带有一个调用flush的Stdout。建议的方法实现如下所示。

def write_flush(args, w=stdout.write):
    w(args)
    stdout.flush()

w参数的默认值将保留原来的写入方法引用。定义了write_flush之后,可能会覆盖原来的写操作。

stdout.write = write_flush

代码假设stdout是从sys import stdout以这种方式导入的。