Python3 实现串口两进程同时读写
通过两个进程分别读写串口,并把发送与接收到的内容记录在blog中,收到q时程序结束并退出
importthreading,time importserial importstring classSerThread: def__init__(self,Port=0): #初始化串口、blog文件名称 self.my_serial=serial.Serial() self.my_serial.port=Port self.my_serial.baudrate=9600 self.my_serial.timeout=1 self.alive=False self.waitEnd=None fname=time.strftime("%Y%m%d")#blog名称为当前时间 self.rfname='r'+fname#接收blog名称 self.sfname='s'+fname#发送blog名称 self.thread_read=None self.thread_send=None defwaiting(self): #等待event停止标志 ifnotself.waitEndisNone: self.waitEnd.wait() defstart(self): #开串口以及blog文件 self.rfile=open(self.rfname,'w') self.sfile=open(self.sfname,'w') self.my_serial.open() ifself.my_serial.isOpen(): self.waitEnd=threading.Event() self.alive=True self.thread_read=threading.Thread(target=self.Reader) self.thread_read.setDaemon(True) self.thread_send=threading.Thread(target=self.Sender) self.thread_send.setDaemon(True) self.thread_read.start() self.thread_send.start() returnTrue else: returnFalse defReader(self): whileself.alive: try: n=self.my_serial.inWaiting() data='' ifn: data=self.my_serial.read(n).decode('utf-8') print('recv'+''+time.strftime("%Y-%m-%d%X")+''+data.strip()) print(time.strftime("%Y-%m-%d%X:")+data.strip(),file=self.rfile) iflen(data)==1andord(data[len(data)-1])==113:#收到字母q,程序退出 break exceptExceptionasex: print(ex) self.waitEnd.set() self.alive=False defSender(self): whileself.alive: try: snddata=input("inputdata:\n") self.my_serial.write(snddata.encode('utf-8')) print('sent'+''+time.strftime("%Y-%m-%d%X")) print(snddata,file=self.sfile) exceptExceptionasex: print(ex) self.waitEnd.set() self.alive=False defstop(self): self.alive=False #self.thread_read.join() #self.thread_send.join() ifself.my_serial.isOpen(): self.my_serial.close() self.rfile.close() self.sfile.close() if__name__=='__main__': ser=SerThread('com4') try: ifser.start(): ser.waiting() ser.stop() else: pass; exceptExceptionasex: print(ex) ifser.alive: ser.stop() print('EndOK.'); delser;
以上这篇Python3实现串口两进程同时读写就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。