用python立即管道

Dob*_*boy 5 python unix pipe

我有两个文件,其中第一个是fizz

#!/usr/bin/python                                                         
import time

print 'started'
time.sleep(3)
print 'ended'
Run Code Online (Sandbox Code Playgroud)

其次是吧

#!/usr/bin/python                                                         
import sys

for line in sys.stdin:
    print line
Run Code Online (Sandbox Code Playgroud)

当我运行命令时,./fizz | ./bar我希望它打印started然后等待3秒并打印ended,但真正发生的是它打印startedended在3秒后同时打印.有没有办法达到我想要的行为?谢谢

glg*_*lgl 6

现在很明显问题出在接收方,我提出了一个我喜欢使用的替代方案:

#!/usr/bin/python                                                   
import sys 
import os

for line in iter(sys.stdin.readline, ''):
    sys.stdout.write(line) # \n included in line
Run Code Online (Sandbox Code Playgroud)

iter(func, sentinel)调用func()每次迭代并在函数结果时结束== sentinel.


Edu*_*nec 5

好问题.它比它应该有点难.

问题确实存在bar,特别sys.stdin是缓冲.我尝试sys.stdin使用较小的缓冲区大小打开并使用python -u但不起作用.该联机帮助页有这样的说法:

   -u     Force  stdin,  stdout  and  stderr to be totally unbuffered.  On
          systems where it matters, also put stdin, stdout and  stderr  in
          binary  mode.   Note  that there is internal buffering in xread?
          lines(), readlines() and file-object  iterators  ("for  line  in
          sys.stdin")  which  is  not  influenced by this option.  To work
          around this, you will want to use "sys.stdin.readline()"  inside
          a "while 1:" loop.
Run Code Online (Sandbox Code Playgroud)

最后这对我有用:

#!/usr/bin/python                                                   
import sys 
import os

while True:
    line = sys.stdin.readline()
    if not line:
        break
    sys.stdout.write(line) # or print, doesn't matter.
Run Code Online (Sandbox Code Playgroud)