如何在Python中向运行中的.exe程序反复传入输入并获取输出
实现与持续运行的.exe程序交互
要实现不重启.exe就能反复输入并获取结果,得用subprocess.Popen替代subprocess.run——因为run会等待进程终止才返回,没法持续和进程交互。下面是针对你修改后的hello.exe的具体实现:
核心代码(test.py)
import subprocess # 启动.exe,建立双向通信管道 proc = subprocess.Popen( ['./exe_example/output/hello/hello.exe'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True, bufsize=1 # 行缓冲模式,避免输出滞留 ) # 封装发送输入、获取输出的函数 def interact_with_exe(input_str): # 发送输入:必须加换行符,因为exe里用input()读取(以换行作为输入结束标记) proc.stdin.write(f"{input_str}\n") proc.stdin.flush() # 强制刷新缓冲区,确保输入立即传给exe # 读取对应输出并去除首尾空白 response = proc.stdout.readline().strip() return response # 测试多次交互 print(interact_with_exe("a")) print(interact_with_exe("b")) print(interact_with_exe("c")) # 用完后清理资源(可选,按需决定是否关闭进程) proc.stdin.close() proc.terminate() proc.wait()
关键细节说明
subprocess.Popen的作用:它不会阻塞等待进程结束,而是返回一个进程对象,让你能随时和运行中的.exe通信。- 管道配置:
stdin=subprocess.PIPE和stdout=subprocess.PIPE开启了Python与.exe之间的输入、输出管道,支持双向数据传递。 - 文本模式与缓冲:
text=True让输入输出以字符串而非字节流处理,避免编码问题;bufsize=1设置行缓冲,保证.exe输出的每一行能被立即读取。 - 输入格式:因为你的.exe用
input()读取内容,该函数会以换行符作为输入结束的标志,所以发送输入时必须加上\n。 - 缓冲区刷新:
proc.stdin.flush()能确保输入内容不会留在Python的缓冲区里,而是立刻发送给.exe。
额外注意事项
- 如果.exe的输出包含多行,需要用循环读取(比如
while True配合readline())直到获取到预期内容。 - 若.exe意外终止,读取输出时会抛出异常,建议添加
try-except块处理这种情况。 - 进程使用完毕后,记得关闭管道并终止进程,避免系统资源泄漏。
内容的提问来源于stack exchange,提问作者adameye2020
相关产品推荐
相关产品推荐

