2013-03-27 66 views
1

我想通過這樣的管道讀取過程的輸出:如何在不阻塞的情況下讀取python中的unix管道?

./backup.sh | my-python_program.py 

我的Python程序目前從標準輸入讀取:

buff = sys.stdin.read() 

這看似幼稚,似乎阻斷一個需要很長時間執行的腳本。有沒有更好的辦法?

+1

是不是阻止你期望做這樣一個呼叫? – kratenko 2013-03-27 15:52:20

回答

1

不知道python如何包裝它,但你會想要使用select()與一個很小的超時值。

0

管道顯式設置爲阻塞,對於大多數目的而言,它是有意義的 - 您的程序是否有其他可能在不讀取輸入時執行的操作?如果是這樣,那麼你可以看看異步I/O,如果你打算在python中這樣做,我建議使用[gevent [(http://www.gevent.org/),它可以讓你使用輕量級的線程高效的異步I/O:

import gevent 
from gevent import monkey; monkey.patch_all() 

def read_from_stdin(): 
    buff = sys.stdin.read() 
    # Whatever you're going to do with it 

def some_other_stuff_to_do(): 
    # ... 
    pass 

gevent.Greenlet(read_from_stdin).run() 
gevent.Greenlet(some_other_stuff_to_do).run() 
+0

當然,你可以使用'select(2)',但它非常低級,'gevent'抽象了很多重複的細節。它也可以使用更高效的算法('epoll(2)'和'kqueue(2)')。 – 2013-03-27 15:56:41

相關問題