为什么python3k的pyserial返回字节而python2k返回字符串?

2024-04-25 19:25:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我正试图靠岸 https://github.com/thearn/Python-Arduino-Command-API到python3,到目前为止,我已经将它导入到可以无错误地导入它的地步,我尝试运行blink示例found here,但总是得到一个类型错误。在

我想我已经把范围缩小到这个范围了。在

PySerial 2.7 for python2.7.8中的readline函数返回字符串,PySerial 2.7中python3.3的readline函数返回字节。在

Python2

>>> import serial
>>> serial.VERSION
'2.7'
>>> ser= serial.Serial(port='COM4')
>>> ser.readline()
'0\r\n'
>>> type(ser.readline())
<type 'str'>

Python3

^{pr2}$

我已经检查了pyserial的python2和python3实现的readline函数的源代码,它们似乎都应该返回字节,因为每个字节的最后一行是return bytes(line),这是整个函数中唯一的返回语句。在

我的问题:为什么pyserial2.7的readline函数在python2和python3中返回不同的结果?在


Tags: 函数httpsgithubcomreadline字节type错误
3条回答

在Python3中执行套接字程序时,我遇到了这个问题。当我接收到一个流时,我最终使用了decode()函数使其正常工作。在

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

解码很有帮助。不确定它是否适用于你的情况,但试试看。在

这是Python2和3之间的主要区别之一。在

来自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.

您可以在上面链接的“文本与数据而不是Unicode与8位”部分找到完整的解释。在

这是因为在python3.x中,文本始终是Unicode,并用str类型表示,而二进制数据则由bytes类型表示。这个特性不同于python2.x版本。在

在您的示例中,ser.readline()实际上返回二进制数据。在

相关问题 更多 >