![](/uploads/1/2/7/3/127372813/824117331.jpg)
![Serial Serial](/uploads/1/2/7/3/127372813/543542315.jpg)
The DataReceived event is raised on a secondary thread when data is received from the SerialPort object. Because this event is raised on a secondary thread, and not the main thread, attempting to modify some elements in the main thread, such as UI elements, could raise a threading exception.
. I created a read thread to do all the reading.readingevent = thread.Eventreadingthread = thread.Thread(target=reading, daemon=True)def reading:while readingevent.isset:rawreading = ser.readlineprint(rawreading).I am using the latest python 3.6.1 and the latest pyserial installed by pip3 in a vitualenv.Yes, I have tried read and detected newline characters by myself but it didn't solve the problem.I will try the two links tomorrow and provide feedback.Thank you for your help. It is easy to implement a non-CPU time wasting readline method.
In a loop, first call ser.read(1) and then call ser.read(ser.inwaiting). Each time, check whether the returned data contains n. Of course the data after n needs to be saved as it may be part of another line.
![Event Event](/uploads/1/2/7/3/127372813/898623771.png)
Also see the my recv function from issueNot only does ser.readline waste 100% of one CPU core. It is also slow as hell! Reading from a virtual COM port /dev/ttyACM1 attached via USB, ser.readline would give me a throughput of about 150 kB/sec.
Using ser.read(1) in combination with ser.read(ser.inwaiting) would give me a throughput of about 660kB/sec. Here's a class that serves as a wrapper to a pyserial object. It allows you to read lines without 100% CPU. It does not contain any timeout logic. If a timeout occurs, self.s.read(i) returns an empty string and you might want to throw an exception to indicate the timeout.I just measured. The code below gives me 790 kB/sec while replacing the code with pyserial's readline method gives me just 170kB/sec. #!/usr/bin/python3class ReadLine:def init(self, s):self.buf = bytearrayself.s = sdef readline(self):i = self.buf.find(b'n')if i = 0:r = self.buf:i+1self.buf = self.bufi+1:return rwhile True:i = max(1, min(2048, self.s.inwaiting))data = self.s.read(i)i = data.find(b'n')if i = 0:r = self.buf + data:i+1self.buf0: = datai+1:return relse:self.buf.extend(data).
![](/uploads/1/2/7/3/127372813/824117331.jpg)