python stdout flush 和 tee

标签 python tee

以下代码在通过管道传输到 tee 时以管道损坏结束,但在未通过管道传输时运行正常:

#!/usr/bin/python
import sys
def testfun():
    while 1:
        try :
            s = sys.stdin.readline()
        except(KeyboardInterrupt) :
            print('Ctrl-C pressed')
            sys.stdout.flush()
            return
        print s

if __name__ == "__main__":
    testfun()
    sys.exit()

预期输出:

./bug.py 
Ctrl-C pressed

当管道传输到 tee 时观察到的是管道损坏或根本没有输出,即 tee stdout 上没有任何内容,bug.log 中也没有任何内容:

./bug.py | tee bug.log
Traceback (most recent call last):
  File "./bug.py", line 14, in <module>
    sys.stdout.flush()
IOError: [Errno 32] Broken pipe

这可能是什么原因?

最佳答案

不,按 Ctrl-C 不会终止两个进程。它仅终止 tee 过程, tee 进程结束时关闭脚本和 tee 之间的管道,因此您的脚本会因管道消息损坏而终止。

为了解决这个问题,tee 有一个选项可以将 Ctrl-C 传递给它在管道中的前一个进程:-i

尝试:男士 T 恤

./bug.py
^CCtrl-C pressed
./bug.py | tee log
^CTraceback (most recent call last):
  File "./bug.py", line 14, in <module>
    testfun()
  File "./bug.py", line 9, in testfun
    sys.stdout.flush()
IOError: [Errno 32] Broken pipe

./bug.py | tee -i log
^CCtrl-C pressed

关于python stdout flush 和 tee,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1192870/

相关文章:

python - 如何解释 fairseq 生成的 P 数?

python - Django Redis 在键上附加相同的注释

unix - 强制管道中标准输出的行缓冲

linux - 按时间顺序捕获 STDOUT 和 STDERR

python - 使用 ctypes 将 malloc 数组从 C 返回到 Python

python - 回调问题 FailedPreconditionError

python - 在 PyQt 中将变量从一个类传递到另一个类

linux - 是否保证 tee 打印到 stdout 的顺序?

shell - 为什么用 tee 重定向不能按预期工作?

C 将标准输出重定向到几个地方