pyserial and threads

pozz pozzugno at gmail.com
Thu Sep 17 05:28:04 EDT 2015


I'm trying to create a simple program in Python that opens N serial 
ports (through pyserial) and forward every byte received on one of those 
ports to the other ports.

At startup I open the ports and create and start a thread to manage the 
receiving. When a byte is received, I call the .write() method for all 
the other ports.

It works, but sometimes it seems to block. I think I haven't used 
correctly the threads.

Below is my code, I hope someone can help me.

Consider that I'm a newbie in python and I never used threads before.


import serial
import threading
import sys, os
import signal
import time

class Miniterm(object):
   def __init__(self, port, baudrate):
     self.serial = serial.Serial(port, baudrate, timeout=1)

   def start(self, com_list):
     self.alive = True
     self.com_list = com_list
     self._reader_alive = True
     self.receiver_thread = threading.Thread(target=self.reader)
     self.receiver_thread.setDaemon(True)
     self.receiver_thread.start()

   def stop(self):
     self.alive = False

   def reader(self):
     try:
       while self.alive and self._reader_alive:
         data = self.serial.read(1)
           if len(data) > 0:
           for p in self.com_list:
             if p[1] != self:
               p[1].write(data)
     except serial.SerialException:
       self.alive = False
       raise

   def write(self, data):
     self.serial.write(data)
	
if __name__ == "__main__":
   ports = []
   for com in sys.argv[1:]:
     try:
       miniterm = Miniterm(com, 38400)
     except serial.SerialException:
       sys.stderr.write("could not open port " + com)
       sys.exit(1)
     ports.append((com, miniterm))
     for p in ports:
       p[1].start(ports)
       print("Port " + p[0] + " has started", flush=True)
     while True:
       time.sleep(1)




More information about the Python-list mailing list