我尝试使用这样的子流程模块与python解释器进行交互:
import subprocess
def start(executable_file):
return subprocess.Popen(
executable_file,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
def read(process):
return process.stdout.readline().decode("utf-8").strip()
def write(process, message):
process.stdin.write(f"{message.strip()}\n".encode("utf-8"))
process.stdin.flush()
def terminate(process):
process.stdin.close()
process.terminate()
process.wait(timeout=0.2)
process = start("python")
while True:
write(process, input())
print(read(process))
terminate(process)
但它似乎陷入了僵局。
如果有人知道如何使用python代码与python交互并恢复stdout,则使用流模式的stderr。
发布于 2022-10-12 18:42:49
您需要使用communicate()
而不是read()
和write()
,否则会导致死锁。
请参阅这页面中部的红色警告突破。
https://stackoverflow.com/questions/74046059
复制相似问题