Python3 实现串口两进程同时读写

yipeiwu_com5年前Python基础

通过两个进程分别读写串口,并把发送与接收到的内容记录在blog中,收到q时程序结束并退出

import threading,time
import serial
import string
 
 
class SerThread:
  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   
       
 
  def waiting(self):
    # 等待event停止标志
    if not self.waitEnd is None:
      self.waitEnd.wait()
 
  def start(self):
    #开串口以及blog文件 
    self.rfile=open(self.rfname,'w')
    self.sfile=open(self.sfname,'w')
    self.my_serial.open()
       
    if self.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()
      return True
    else:
      return False
 
  
  def Reader(self):
    while self.alive:
      try:
        n=self.my_serial.inWaiting()
        data=''
        if n:
          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)
          if len(data)==1 and ord(data[len(data)-1])==113: #收到字母q,程序退出
            break
      except Exception as ex:
        print (ex)
        
 
    self.waitEnd.set()
    self.alive = False
  
  def Sender(self):
    while self.alive:
      try:
        snddata=input("input data:\n")
        self.my_serial.write(snddata.encode('utf-8'))
        print ('sent'+' '+ time.strftime("%Y-%m-%d %X"))
              print (snddata,file=self.sfile) 
        
      except Exception as ex:
        print (ex)
    
    self.waitEnd.set()
    self.alive = False          
        
    
 
  def stop(self):
    self.alive = False
    #self.thread_read.join()
    #self.thread_send.join()
    if self.my_serial.isOpen():
      self.my_serial.close()
    self.rfile.close()
    self.sfile.close()
      
 
if __name__ == '__main__':  
  
  ser = SerThread('com4')
  try:
    if ser.start():
      ser.waiting()
      ser.stop()
    else:
      pass;      
  except Exception as ex:
    print (ex)
 
  if ser.alive:
    ser.stop()
 
  print ('End OK .');
  del ser; 

以上这篇Python3 实现串口两进程同时读写就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python函数定义及传参方式详解(4种)

一、函数初识 1、定义:将一组语句的集合通过一个名字(函数名)封装起来,要想执行这个函数,只需调用其函数名即可。  2、好处:代码重用;保持一致性;可扩展性。 3、示例如下:    ...

Python中is和==的区别详解

Python中有很多运算符,今天我们就来讲讲is和==两种运算符在应用上的本质区别是什么。 在讲is和==这两种运算符区别之前,首先要知道Python中对象包含的三个基本要素,分别是:i...

使用Python通过win32 COM实现Word文档的写入与保存方法

使用Python通过win32 COM实现Word文档的写入与保存方法

通过win32 COM接口实现软件的操作本质上来看跟直接操作软件一致,这跟我之前经常用的通过各种扩展的组件或者库实现各种文件的处理有较大的差异。如果有过Windows下使用Word的经历...

python实现按关键字筛选日志文件

python实现按关键字筛选日志文件

最近忙成了狗,五六个项目堆在一起,头疼的是测试还失惊无神的给我丢来一个几十甚至上百M的日志文件,动不动就几十上百万行,就算是搜索也看得头昏眼花的,因此自己花了点时间写了一段小脚本去过滤日...

一个小示例告诉你Python语言的优雅之处

比如, 我们希望希望检测"一段string是否以特定的字符串结尾?", 通常我们使用: if needle.endswith('ly') or needle.endswi...