Skip to content Skip to sidebar Skip to footer

Why Does Pyserial For Python3k Return Bytes While Python2k Returns Strings?

I am attempting to port https://github.com/thearn/Python-Arduino-Command-API to python 3, so far i have gotten it to the point where i can import it without error, i tried to run

Solution 1:

This is because in Python 3.x, text is always Unicode and is represented by the str type, and binary data is represented by the bytes type. This feature differs the Python 2.x version.

In your example, ser.readline() in fact returns binary data.

Solution 2:

It's one of the major differences between Python 2 and 3.

From https://docs.python.org/3.0/whatsnew/3.0.html :

Python 3.0 uses the concepts of text and (binary) data instead of Unicode strings and 8-bit strings. All text is Unicode; however encoded Unicode is represented as binary data. The type used to hold text is str, the type used to hold data is bytes. The biggest difference with the 2.x situation is that any attempt to mix text and data in Python 3.0 raises TypeError, whereas if you were to mix Unicode and 8-bit strings in Python 2.x, it would work if the 8-bit string happened to contain only 7-bit (ASCII) bytes, but you would get UnicodeDecodeError if it contained non-ASCII values. This value-specific behavior has caused numerous sad faces over the years.

You will find the full explaination in the "Text Vs. Data Instead Of Unicode Vs. 8-bit" section of the link above.

Solution 3:

This issue came up for me when doing a socket program in python 3. When I was receiving a stream, I ended up using the decode() function for it to work correctly.

retval = sock.recv(1024).decode()

The decode was very helpful. Not sure if it's applicable to your situation, but give it a try.

Post a Comment for "Why Does Pyserial For Python3k Return Bytes While Python2k Returns Strings?"