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

運行效果如下;

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM