为什么 pyserial for python3k 返回字节而 python2k 返回字符串? [英] Why does pyserial for python3k return bytes while python2k returns strings?

查看:41
本文介绍了为什么 pyserial for python3k 返回字节而 python2k 返回字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试移植https://github.com/thearn/Python-Arduino-Command-API到 python 3,到目前为止,我已经到了可以毫无错误地导入它的地步,我尝试运行闪烁示例 在这里找到,我总是会收到类型错误.

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

来自 PySerial 2.7 for python 2.7.8 的 readline 函数返回一个字符串,来自 PySerial 2.7 for python 3.3 的 readline 函数返回字节.

Python 2

<预><代码>>>>导入序列>>>串行版本'2.7'>>>ser=serial.Serial(port='COM4')>>>ser.readline()'0\r\n'>>>类型(ser.readline())<输入'str'>

Python 3

<预><代码>>>>导入序列>>>串行版本'2.7'>>>ser = serial.Serial(port='COM4')>>>ser.readline()b'0\r\n'>>>类型(ser.readline())<类'字节'>

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

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

解决方案

这是因为在 Python 3.x 中,文本始终是 Unicode 并由 str 类型表示,而二进制数据则由 bytes 类型表示.此功能与 Python 2.x 版本不同.

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

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 the blink example found here and i would always get a type error.

I think I have narrowed it down to this.

The readline function from PySerial 2.7 for python 2.7.8 returns a string and the readline function from PySerial 2.7 for python 3.3 returns bytes.

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'>

I have checked out the source of the readline function for the python 2 and python 3 implementation of pyserial and they seem like they should both return bytes as the last line of each is return bytes(line) and thats the only return statement in the whole function.

My Question: Why does the readline function for PySerial 2.7 return different results in python2 and python3?

解决方案

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.

这篇关于为什么 pyserial for python3k 返回字节而 python2k 返回字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆