我需要继续与子进程通信。我试图通过我的方式暴力。该过程从请求字符串开始。我提供一个。虽然我一直得到“不!”作为回应我需要再试一次,直到我得到另一个回复。我创建了一个Popen对象:
# creating Popen object
sp = Popen(['ba.exe'],stdout = PIPE, stdin = PIPE, stderr = STDOUT)
#writing to it
sp.stdin.write(word)
# Read process response
resp = (sp.stdout.read()[0].decode('utf-8'))
# based on resp report success or update the value of word
但是读取暂停...我不想关闭sp.stdin,因为我很快就会需要它。我不能使用.communicate(),因为我需要继续沟通。
为什么read()会挂起?我怎样才能完成任务?谢谢
而不是调用read方法,迭代线:
for iter(sp.stdout.readline,b''):#用line做一些事情
(假设子进程是有线缓冲的,这应该可行)
似乎没有新行。
逐字节读取字符串,然后字符串匹配预期的写入新字。
c = True
line=""
while c:
c = sp.stdout.read(1)
line+=c
if line[-3:] == "No!":
#do something and clear line buffer
line = ""