Python 3 利用 subprocess 實現管道( pipe )互動操作讀/寫通訊
阿新 • • 發佈:2019-01-06
1 # -*- coding:utf-8 -*- 2 3 import subprocess 4 import sys 5 import threading 6 7 class LoopException(Exception): 8 """迴圈異常自定義異常,此異常並不代表迴圈每一次都是非正常退出的""" 9 def __init__(self,msg="LoopException"): 10 self._msg=msg 11 12 def __str__(self): 13 returnself._msg 14 15 16 17 class SwPipe(): 18 """ 19 與任意子程序通訊管道類,可以進行管道互動通訊 20 """ 21 def __init__(self,commande,func,exitfunc,readyfunc=None, 22 shell=True,stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE,code="GBK"): 23 """ 24 commande 命令25 func 正確輸出反饋函式 26 exitfunc 異常反饋函式 27 readyfunc 當管道建立完畢時呼叫 28 """ 29 self._thread = threading.Thread(target=self.__run,args=(commande,shell,stdin,stdout,stderr,readyfunc)) 30 self._code = code 31 self._func = func 32 self._exitfunc = exitfunc33 self._flag = False 34 self._CRFL = "\r\n" 35 36 def __run(self,commande,shell,stdin,stdout,stderr,readyfunc): 37 """ 私有函式 """ 38 try: 39 self._process = subprocess.Popen( 40 commande, 41 shell=shell, 42 stdin=stdin, 43 stdout=stdout, 44 stderr=stderr 45 ) 46 except OSError as e: 47 self._exitfunc(e) 48 fun = self._process.stdout.readline 49 self._flag = True 50 if readyfunc != None: 51 threading.Thread(target=readyfunc).start() #準備就緒 52 while True: 53 line = fun() 54 if not line: 55 break 56 try: 57 tmp = line.decode(self._code) 58 except UnicodeDecodeError: 59 tmp = \ 60 self._CRFL + "[PIPE_CODE_ERROR] <Code ERROR: UnicodeDecodeError>\n" 61 + "[PIPE_CODE_ERROR] Now code is: " + self._code + self._CRFL 62 self._func(self,tmp) 63 64 self._flag = False 65 self._exitfunc(LoopException("While Loop break")) #正常退出 66 67 68 def write(self,msg): 69 if self._flag: 70 #請注意一下這裡的換行 71 self._process.stdin.write((msg + self._CRFL).encode(self._code)) 72 self._process.stdin.flush() 73 #sys.stdin.write(msg)#怎麼說呢,無法直接用程式碼傳送指令,只能預設的stdin 74 else: 75 raise LoopException("Shell pipe error from '_flag' not True!") #還未準備好就退出 76 77 78 def start(self): 79 """ 開始執行緒 """ 80 self._thread.start() 81 82 def destroy(self): 83 """ 停止並銷燬自身 """ 84 process.stdout.close() 85 self._thread.stop() 86 del self 87 88 89 90 91 92 93 if __name__ == '__main__': #那麼我們來開始使用它吧 94 e = None 95 96 #反饋函式 97 def event(cls,line):#輸出反饋函式 98 sys.stdout.write(line) 99 100 def exit(msg):#退出反饋函式 101 print(msg) 102 103 def ready():#執行緒就緒反饋函式 104 e.write("dir") #執行 105 e.write("ping www.baidu.com") 106 e.write("echo Hello!World 你好中國!你好世界!") 107 e.write("exit") 108 109 e = SwPipe("cmd.exe",event,exit,ready) 110 e.start()