以下代码在通过管道传输到 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/