PySerial and readline() return binary string - convert to regular alphanumeric string?

試著忘記壹切 提交于 2019-12-07 16:18:48

问题


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

which gives the following error:

TypeError: type str doesn't support the buffer API

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

Which gives the expected:

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

But then running:

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

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!


回答1:


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!



来源:https://stackoverflow.com/questions/13373415/pyserial-and-readline-return-binary-string-convert-to-regular-alphanumeric-s

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!