PySerial 和 readline() 返回二进制字符串 - 转换为常规字母数字字符串? [英] PySerial and readline() return binary string - convert to regular alphanumeric string?

查看:36
本文介绍了PySerial 和 readline() 返回二进制字符串 - 转换为常规字母数字字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用 PySerial 和 Python (3.3) 时遇到问题:我正在运行的代码(目前,这只是一个简单的测试用例)如下:

I'm having an issue with PySerial and Python (3.3): The code I'm running (for now, this is just a simple test case) is as follows:

ser = serial.Serial('/dev/ttyACM0', 115200)
result = ser.readline()
parsed = result.split(",")

出现以下错误:

TypeError: type str doesn't support the buffer API

我犯了什么愚蠢的错误?我想我已经将其追溯到这样一个事实,即 PySerial 的 readline 正在返回一个二进制字符串(python 3 中的新功能?)并且字符串操作split"在针对二进制字符串运行时失败 - 如果您运行它,它可以正常工作:

What's my stupid mistake? I think I've traced this to the fact that PySerial's readline is returning a binary string (new in python 3?) and that the string operation "split" is failing when run against a binary string - it works fine if you run this:

'1234, asdf, 456, jkl'.split(",")

哪个给出了预期:

['1234', 'asdf', '456', jkl']

然后运行:

b'1234, asdf, 456, jkl'.split(",")

给出了上面的错误.是否有不同的 readline 方法可以使用?我应该使用 read 编写自己的代码(并且只阅读直到看到/r/n)还是可以轻松转换为满足 str.isalnum() 的字符串?谢谢!

gives the error above. Is there a different readline method to use? should I code my own with read (and just read until it sees /r/n) or can I easily convert to a string that will satisfy str.isalnum()? Thanks!

推荐答案

最快捷的解决方案是使用名为 binascii 的 Python 模块,该模块具有一系列用于将二进制字符串转换为 ascii 字符串的函数:http://docs.python.org/2/library/binascii.html

The quickest solution will be to use a python module called binascii that has a selection of functions for converting the binary string to an ascii string: http://docs.python.org/2/library/binascii.html

b 表示它是一个字节数组而不是文字字符串.将字节数组转换为文字字符串的正确方法是使用 str() 函数:

The b means that it is a byte array and not a literal string. The correct way to convert the byte array to a litteral string will be to use the str() function:

str(b'1234, asdf, 456, jkl', 'ascii').split(",")

str(b'1234, asdf, 456, jkl', 'ascii').split(",")

这给出了你想要的输出:['1234', 'asdf', '456', jkl']

this gives the output you want: ['1234', 'asdf', '456', jkl']

希望能帮到你!

这篇关于PySerial 和 readline() 返回二进制字符串 - 转换为常规字母数字字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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