为什么这些print()调用似乎以错误的顺序执行?

时间:2015-06-27 21:18:23

标签: python python-3.x

weird.py:

import sys

def f ():
    print('f', end = '')
    g()

def g ():
    1 / 0

try:
    f()
except:
    print('toplevel', file = sys.stderr)

Python会话:

Python 3.4.2 (v3.4.2:ab2c023a9432, Oct  6 2014, 22:16:31) [MSC v.1600 64 bit (AM
D64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import weird
toplevel
f>>>

为什么" toplevel"打印之前" f"?

如果移除end = ''file = sys.stderr,则不会发生这种情况。

1 个答案:

答案 0 :(得分:7)

因为stdout和stderr 行缓冲。它们缓冲字符,只有当你有一个完整的行时才会刷新。

通过设置end='',确保没有完整的行,并且当Python交互式解释器输出>>>并刷新缓冲区时,缓冲区不会被刷新,直到以后明确。

如果您删除file=sys.stderr,则会再次输出到sys.stdout,并打印toplevel\n,因为print()会添加换行符,从而刷新sys.stdout缓冲区。< / p>

您可以通过将flush=True参数设置为print()函数(Python 3.3及更高版本)或调用sys.stdout.flush()来显式强制刷新。