问题描述
我正在使用来启动子流程并连接到它的输出流(stdout)。我希望能够在其stdout上执行非阻塞读取。有没有办法让.readline非阻塞或在我调用 .readline
之前检查流上是否有数据?我希望这是可移植的,或至少在Windows和Linux下工作。
I'm using the subprocess module to start a subprocess and connect to it's output stream (stdout). I want to be able to execute non-blocking reads on its stdout. Is there a way to make .readline non-blocking or to check if there is data on the stream before I invoke .readline
? I'd like this to be portable or at least work under Windows and Linux.
这是我现在的工作方式(它在 .readline 如果没有数据可用):
here is how I do it for now (It's blocking on the .readline
if no data is avaible):
p = subprocess.Popen('myprogram.exe', stdout = subprocess.PIPE)
output_str = p.stdout.readline()
推荐答案
,,在这种情况下无效。
fcntl
, select
, asyncproc
won't help in this case.
无论操作系统如何,无阻塞地读取流的可靠方法是使用:
A reliable way to read a stream without blocking regardless of operating system is to use Queue.get_nowait()
:
import sys
from subprocess import PIPE, Popen
from threading import Thread
try:
from queue import Queue, Empty
except ImportError:
from Queue import Queue, Empty # python 2.x
ON_POSIX = 'posix' in sys.builtin_module_names
def enqueue_output(out, queue):
for line in iter(out.readline, b''):
queue.put(line)
out.close()
p = Popen(['myprogram.exe'], stdout=PIPE, bufsize=1, close_fds=ON_POSIX)
q = Queue()
t = Thread(target=enqueue_output, args=(p.stdout, q))
t.daemon = True # thread dies with the program
t.start()
# ... do other things here
# read line without blocking
try: line = q.get_nowait() # or q.get(timeout=.1)
except Empty:
print('no output yet')
else: # got line
# ... do something with line
这篇关于python中subprocess.PIPE上的非阻塞读取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!