文件 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()
而休眠)时返回。
最佳答案
好的,我已经解决了。我的代码基于 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()
关于python - 我怎么知道我的子进程是否在等待我的输入?(在 python3 中),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12180073/