我正在使用子流程模块 http://docs.python.org/library/subprocess.html启动子进程并连接到其输出流(标准输出)。我希望能够在其标准输出上执行非阻塞读取。有没有办法使 .readline 非阻塞或在调用之前检查流上是否有数据.readline
?我希望它是可移植的或者至少可以在 Windows 和 Linux 下工作。
这是我现在的做法(它阻止了.readline
如果没有可用数据):
p = subprocess.Popen('myprogram.exe', stdout = subprocess.PIPE)
output_str = p.stdout.readline()
fcntl https://stackoverflow.com/questions/375427/non-blocking-read-on-a-stream-in-python/4025909#4025909, select https://stackoverflow.com/questions/375427/non-blocking-read-on-a-stream-in-python/375511#375511, asyncproc https://stackoverflow.com/questions/375427/non-blocking-read-on-a-stream-in-python/437888#437888在这种情况下没有帮助。
无论操作系统如何,无阻塞地读取流的可靠方法是使用Queue.get_nowait() https://docs.python.org/3/library/queue.html#queue.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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)