Python Pyserial Readline Example
. 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.

- Welcome to pySerial’s documentation¶. This module encapsulates the access for the serial port. It provides backends for Python running on Windows, OSX, Linux, BSD (possibly any POSIX compliant system) and IronPython. The module named “serial” automatically selects the appropriate backend.
- Build a Python module that can be used as a PySerial replacement while. We pick several examples from the PySerial documentation. Bytes (timeout) line = ser.readline # read a 'n' terminated line ser.close.
The Python function only exists if Python was compiled for a version of the library that supports it. Getcurrenthistorylength ( ) ¶ Return the number of items currently in the history.
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. 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.
Python Serial Write
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.
Pyserial Windows Example
#!/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).