我在这个问题的代码上实现了一个变体:
在 Python 中对 subprocess.PIPE 进行非阻塞读取
要尝试从此虚拟程序实时读取输出test.py
:
import time, sys
print "Hello there"
for i in range(100):
time.sleep(0.1)
sys.stdout.write("\r%d"%i)
sys.stdout.flush()
print
print "Go now or I shall taunt you once again!"
另一个问题的变化是调用程序必须逐个字符读取,而不是逐行读取,因为虚拟程序test.py
使用\r
. 所以这里是:
import sys,time
from subprocess import PIPE, Popen
from threading import Thread
try:
from Queue import Queue, Empty
except ImportError:
from queue import Queue, Empty # Python 3.x
ON_POSIX = 'posix' in sys.builtin_module_names
def enqueue_output(out, queue):
while True:
buffersize = 1
data = out.read(buffersize)
if not data:
break
queue.put(data)
out.close()
p = Popen(sys.executable + " test.py", 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()
while True:
p.poll()
if p.returncode:
break
# Read line without blocking
try:
char = q.get_nowait()
time.sleep(0.1)
except Empty:
pass
else: # Got line
sys.stdout.write(char)
sys.stdout.flush()
print "left loop"
sys.exit(0)
这有两个问题
- 它永远不会退出 -
p.returncode
永远不会返回值并且循环不会离开。我该如何解决? - 真的很慢!有没有办法在不增加的情况下提高效率
buffersize
?