python 3非阻塞p.stdout.readline()

时间:2018-01-30 00:44:54

标签: python-3.x

大家好我想尝试从subprocess.PIPE读取而不阻塞主进程。我找到了这段代码:

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 3.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

代码不返回任何内容。我在Windows上使用Python 3。 你有什么想法可能是什么问题吗?

1 个答案:

答案 0 :(得分:1)

我离开了我的项目很长一段时间,但最后我还是要解决这个问题。

from subprocess import PIPE, Popen
from threading  import Thread

p = Popen(['myprogram.exe'], stdout=PIPE)
t = Thread(target=results)
t.daemon = True
t.start()


def results():
    a = p.stdout.readline()

也许这不是正确的方法,但它对我有用。我只是张贴它,因为我个人认为,提出问题的人应该在找到问题后发布解决方案。