【发布时间】:2014-10-23 07:40:34
【问题描述】:
我正在尝试移植 https://github.com/thearn/Python-Arduino-Command-API 到 python 3,到目前为止,我已经将它导入到没有错误的地步,我尝试运行闪烁示例 found here,但我总是会收到类型错误。
我想我已经把范围缩小到了。
python 2.7.8 的 PySerial 2.7 中的 readline 函数返回一个字符串,python 3.3 的 PySerial 2.7 中的 readline 函数返回字节。
Python 2
>>> import serial
>>> serial.VERSION
'2.7'
>>> ser= serial.Serial(port='COM4')
>>> ser.readline()
'0\r\n'
>>> type(ser.readline())
<type 'str'>
Python 3
>>> import serial
>>> serial.VERSION
'2.7'
>>> ser = serial.Serial(port='COM4')
>>> ser.readline()
b'0\r\n'
>>> type(ser.readline())
<class 'bytes'>
我已经检查了 pyserial 的 python 2 和 python 3 实现的 readline 函数的源代码,它们似乎都应该返回字节,因为每个字节的最后一行是 return bytes(line),这是唯一的返回语句整个函数。
我的问题:为什么 PySerial 2.7 的 readline 函数在 python2 和 python3 中返回不同的结果?
【问题讨论】:
-
如果你以正确的方式提问,你不会得到不同的结果。在 2.7 中,
bytes == str。所以type(ser.readline()) == bytes在 2.7 和 3.x 中都是True。
标签: python python-2.7 python-3.x pyserial