Skip to main content
 首页 » 编程设计

Python STDIN readline block

2024年10月25日13jiqing9006

我有一个像这样写入 stdout 的脚本:

# Send.py 
import time 
 
while(1): 
    print "hello" 
    time.sleep(0.1) 

现在我有另一个脚本需要这样读取它:

# Listen.py 
while(1) : 
 
    print "reading.." 
    data = sys.stdin.read() 
    print data 

python Send.py | python listen.py 

不幸的是,这只是在阅读时停止并且没有任何内容被打印出来。这是为什么?

请您参考如下方法:

read() 方法会读取到 EOF,但第一个程序永远不会结束; read() 不会返回。

你需要逐行阅读。

替换以下行:

data = sys.stdin.read() 

与:

data = sys.stdin.readline() 

除此之外,readline() 将返回带有换行符的读取行,并且 print 语句会在字符串之后追加新行,从而产生中间的空行。为防止出现这种情况,请使用 sys.stdout.write:

data = sys.stdin.readline() 
sys.stdout.write(data) 

更新

shell 将缓冲输出。为了防止它,刷新输出:

import sys 
import time 
 
while 1: 
    print "hello" 
    sys.stdout.flush() 
    time.sleep(0.1) 

或者,您可以使用 -u 选项使 stdout、stderr 无缓冲。

python -u send.py | python listen.py