7

文件 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是否在等我呢?
换句话说,我希望pobj.stdout.read()在 sp.py 等待(或因为 睡眠time.sleep())时返回。

4

1 回答 1

2

好的,我已经解决了。我的代码基于对python 中 subprocess.PIPE 的非阻塞读取(谢谢,@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()
于 2012-08-30T15:08:14.197 回答