سؤال

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!

هل كانت مفيدة؟

المحلول

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!

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top