python subprocess模块调用外部exe控制台程序并实时进行交互
前记:sreach all web source,I can‘t find the example for python control external .exe procedure and chat with it Real-time. and now,the good new is I share with you;
Prepare:
1.一个一直能一直运行的exe控制台程序;
它的code如下,需编译为console程序;
#include <iostream> #include<windows.h> int main(int argc, char* argv[]) { char xx[233]; while (1) { std::cin >> xx; std::cout << xx << std::endl; } return 0; }
编译后运行效果如下;输入什么回车就返回什么,除非x掉它;
NOW:python code with it;
1 import subprocess 2 import time 3 import threading 4 import random 5 import os 6 def rrun(ojj): 7 print("in") 8 while True: 9 # time.sleep(1) 10 fet_t = ojj.stdout.readline().decode("GBK") 11 if fet_t: 12 print(fet_t) 13 if fet_t == 'iin9\r\n': 14 exit(0)\\条件终止 15 \\博客园:戳人痛处 16 p= subprocess.Popen("D:\\data\\test\\5.exe",shell=True,stdin=subprocess.PIPE,stdout=subprocess.PIPE) 17 \\博客园:戳人痛处 18 rt= threading.Thread(target=rrun,args=(p,)) 19 rt.start() 20 while True: 21 time.sleep(0.5) 22 xi=random.randint(0,10)\\博客园:戳人痛处 23 print("发送字节数:{}".format(p.stdin.write("iin{}\n".format(xi).encode("GBK")))) 24 p.stdin.flush() 25 if xi==9: 26 print('kill?') 27 exit(0)\\条件终止
line 16:创建控制台程序5.exe的子进程并设置参数标准输入输出stdin=subprocess.PIPE,stdout=subprocess.PIPE,此参数为开启流;
line 6:多线程处理接收部分,不为空即打印,windows 有\r\n换行 !
line 23:remember 转换多字节和换行;
line 24:对输入缓冲区进行刷新;
now,运行结果如下;
---[优化版本1如下,解决子进程残留]
1. "5.exe" code如下
#include <iostream> #include<windows.h> int main(int argc, char* argv[]) { char xx[233]; while (1) { std::cin >> xx; std::cout << "输入的:" << xx ; } return 0; }
运行效果:
2. python code 如下;
1 import subprocess 2 import threading 3 import os 4 def rrun(ojj:subprocess.Popen): 5 print("in")#崩析:bili 6 while True: 7 fet_t = ojj.stdout.readline().decode("GBK") 8 if fet_t:#戳人痛处 9 print(fet_t) 10 def run(): 11 p= subprocess.Popen("D:\\data\\test\\5.exe",shell=True,stdin=subprocess.PIPE,stdout=subprocess.PIPE) 12 rt= threading.Thread(target=rrun,args=(p,)) 13 rt.start()#崩析:bili 14 while True: 15 xi=input("input:---:")#by:博客园-戳人痛处 16 print("发送字节数:{}".format(p.stdin.write("{}\n".format(xi).encode("GBK")))) 17 p.stdin.flush()#by:博客园-戳人痛处 18 if xi=='9': #设定的结束子进程的条件 19 os.kill(p.pid,1)#结束子进程 20 print('kill?') 21 break #退出循环 22 if __name__=='__main__': 23 run()
运行效果如下;
-------------====================分割线====================-------------
作者:戳人痛处
本博客link:https://www.cnblogs.com/hardfood/p/15080182.html
硬币,懂?
https://space.bilibili.com/68973181
标签:
subprocess
, python
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!