tee 命令有什么问题?

Ram*_*ddy 2 python command-line bash

我正在运行以下python脚本pipedtee命令

#!/usr/bin/python

from sys import exit,exc_info
from time import sleep

try:
    print "hello"
    #raise KeyboardInterrupt
    while True:
        print "hello"
        sleep(1)

except KeyboardInterrupt:
    print "Key board Interrupt"
    exit(0)
Run Code Online (Sandbox Code Playgroud)

假设我将其存储在file.py

现在如果我执行:

./file.py | tee somefile
Run Code Online (Sandbox Code Playgroud)

现在按Ctrl+C,观察没有任何内容打印到somefilestdout

正常执行情况下:

./file.py
Run Code Online (Sandbox Code Playgroud)

之上Ctrl+C

 hello
 hello
 ^CKey board Interrupt
Run Code Online (Sandbox Code Playgroud)

文件重定向也工作正常。出了什么问题tee

mur*_*uru 6

没什么问题tee。如果 Python 检测到它没有写入 TTY,则会缓冲输出。请参阅这篇 Unix 和 Linux 帖子。用于sys.stdout.flush()强制刷新缓冲区。

  • 在 Python 3 中你可以使用 print('hello',lush=True)` (2认同)