我怎么知道我的子进程是否在等待我的输入?(在python3中)

时间:2012-08-29 14:18:23

标签: python python-3.x subprocess

文件sp.py:

#!/usr/bin/env python3
s = input('Waiting for your input:')
print('Data:' + s)

文件main.py

import subprocess as sp
pobj = sp.Popen('sp.py',stdin=sp.PIPE,stdout=sp.PIPE,shell=True)
print(pobj.stdout.read().decode())
pobj.stdin.write(b'something...')
print(pobj.stdout.read().decode())

main.py将在第一个pobj.stdout.read()中阻止,因为sp.py在等我 但是如果我想首先处理字符串'Waiting for you input:',我怎么知道sp.py是否在等我呢?
换句话说,我希望{。{1}}在sp.py等待时返回(或因pobj.stdout.read()而休眠)。

1 个答案:

答案 0 :(得分:2)

好的,我已经解决了。我的代码基于Non-blocking read on a subprocess.PIPE in python(谢谢,@ VaughnCato)

#!/usr/bin/env python3
import subprocess as sp
from threading import Thread
from queue import Queue,Empty
import time

def getabit(o,q):
    for c in iter(lambda:o.read(1),b''):
        q.put(c)
    o.close()

def getdata(q):
    r = b''
    while True:
        try:
            c = q.get(False)
        except Empty:
            break
        else:
            r += c
    return r

pobj = sp.Popen('sp.py',stdin=sp.PIPE,stdout=sp.PIPE,shell=True)
q = Queue()
t = Thread(target=getabit,args=(pobj.stdout,q))
t.daemon = True
t.start()

while True:
    print('Sleep for 1 second...')
    time.sleep(1)#to ensure that the data will be processed completely
    print('Data received:' + getdata(q).decode())
    if not t.isAlive():
        break
    in_dat = input('Your data to input:')
    pobj.stdin.write(bytes(in_dat,'utf-8'))
    pobj.stdin.write(b'\n')
    pobj.stdin.flush()