2013-03-27 65 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

相关问题