sys.exit 的输出有时会在 print 输出之前出现在终端上

问题描述 投票:0回答:1

多次运行此代码,我有时会得到预期的输出,但否则我会得到

StopIteration
first,然后是循环中的打印。

import sys

data = ['a', 'b', 'c']

def myf(*args):
    for arg in args:
        yield arg

generator_object = myf(*data)

while True:
    try:
        print(next(generator_object))
    except StopIteration:
        sys.exit('End of list')

我每次期望的输出都是在生成器用完要打印的项目后引发的异常。然而,也许有一半的时间,我明白了:

End of list a b c Process finished with exit code 1
多次运行此代码看起来像这样:

GIF showing multiple executions

为什么?

python terminal
1个回答
1
投票

exit() 的字符串被写入 stderr,而 print() 则(默认情况下)写入 stdout。虽然输出最终到达终端,但由于两个流的独立缓冲,无法保证顺序

© www.soinside.com 2019 - 2024. All rights reserved.