有没有一种方法可以轮询从subprocess.Popen返回的文件句柄? [英] Is there a way to poll a file handle returned from subprocess.Popen?
问题描述
说我写这个:
from subprocessing import Popen, STDOUT, PIPE
p = Popen(["myproc"], stderr=STDOUT, stdout=PIPE)
现在可以了
line = p.stdout.readline()
我的程序等待,直到子进程输出下一行.
my program waits until the subprocess outputs the next line.
我可以对p.stdout
做任何魔术,以便我可以读取输出(如果有的话),否则可以继续吗?我正在寻找类似Queue.get_nowait()
Is there any magic I can do to p.stdout
so that I could read the output if it's there, but just continue otherwise? I'm looking for something like Queue.get_nowait()
我知道我可以创建一个用于读取p.stdout
的线程,但是假设我无法创建新线程.
I know I can just create a thread for reading p.stdout
, but let's assume I can't create new threads.
推荐答案
使用Python标准库中的select
模块,请参见 http://docs.python.org/library/select.html . select.select([p.stdout.fileno()], [], [], 0)
立即返回一个元组,该元组的项目为三个列表:如果该文件描述符上有内容要读取,则第一个将为非空.
Use the select
module in Python's standard library, see http://docs.python.org/library/select.html . select.select([p.stdout.fileno()], [], [], 0)
immediately returns a tuple whose items are three lists: the first one is going to be non-empty if there's something to read on that file descriptor.
这篇关于有没有一种方法可以轮询从subprocess.Popen返回的文件句柄?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!