2014-12-22 96 views
0

我試圖讀取非阻塞模式下的管道。這裏有一個類似的問題和答案,但它使用的線程Non-blocking read on a subprocess.PIPE in python非阻塞I/O超時

我嘗試了以下內容,看起來比使用線程簡單,但就是非阻塞只有當輸出線緩衝 - 不知道我這樣做是錯了,所以能有人指着我正確的方向?

#!/usr/bin/python 

import select 
from subprocess import * 
import time 

# do non-blocking read but timeout after some time as we don't want to poll forever 
timeout = 4 
READ_ONLY = select.POLLIN | select.POLLPRI | select.POLLHUP | select.POLLERR 

poller = select.poll() 
proc = Popen("./output.sh".split(), stdout=PIPE); 
poller.register(proc.stdout, READ_ONLY) 

now = time.time() 
end = now + timeout 

while time.time() < end: 
    if poller.poll(timeout): 
     # works as expected as long as output.sh produces lines 
     # read() also blocks 
     print "%s" % proc.stdout.readline(), 

proc.kill() 

output.sh是什麼產生輸出

#!/bin/bash 

for i in `seq 1 400`; 
do 
    sleep 1; 
    # doesn't have newlines 
    echo -n $i 
done 
+0

我不確定你可以使用readline()作爲非阻塞I/O。您可能必須切換到使用讀取(1)。 – user590028

回答

1

poll()功能,則表示有至少一個字節隨時閱讀。如果你打電話給readline()你會等到閱讀完成一行。你需要改用read(1)。

while time.time() < end: 
    if poller.poll(timeout): 
     # works as expected as long as output.sh produces lines 
     # read() also blocks 
     print "%s" % proc.stdout.read(1),