戳人痛处

导航

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()

运行效果如下;

 

posted on 2021-07-30 16:15  戳人痛处  阅读(2636)  评论(0编辑  收藏  举报