4

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

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”在针对二进制字符串运行时失败 - 如果你运行它,它工作正常:

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

这给出了预期:

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

但随后运行:

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

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

4

1 回答 1

3

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

EDIT: 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(",")

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

I hope that helps!

于 2012-11-14T14:48:00.847 回答