我想通过这样的管道读取进程的输出:
./backup.sh | my-python_program.py
我的 python 程序当前从标准输入读取:
buff = sys.stdin.read()
虽然这看起来很幼稚,并且似乎阻碍了需要很长时间才能执行的脚本。有没有更好的办法?
不知道 python 是如何包装它的,但你会想要使用具有较小超时值的select() 。
Pipes are set up explicitly to block and for most purposes it makes sense -- does your program have other stuff that it could be doing when not reading the input?
If so, then you can look into asynchronous I/O, and if you're going to be doing this in python, I'd recommend using [gevent
[(http://www.gevent.org/) which will let you use lightweight threads that do efficient asynchronous 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()