Gyula Soós Gyula Soós - 2 months ago 15
Python Question

Python 2.7 conversion to 3

I found a code snippet online, that would be able to display sensor readings from an android phone, but I need this to run on Python 3. And I have no idea how to fix it:

# -------------------------------------------------------
import socket, traceback, string
from sys import stderr

host = ''
port = 5555
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
s.bind((host, port))

# print one blank line
print

while 1:
try:
message, address = s.recvfrom(8192)
# print message

# split records using comma as delimiter (data are streamed in CSV format)
data = message.split( "," )

# convert to flaot for plotting purposes
t = data[0]
sensorID = int(data[1])
if sensorID==3: # sensor ID for the eccelerometer
ax, ay, az = data[2], data[3], data[4]
# SAVE TO FILE
# print >> open("prova.txt","a"), t, ax, ay, az
# print t, ax, ay, az
# FLUSH TO STERR
stderr.write("\r t = %s s | (ax,ay,az) = (%s,%s,%s) m/s^2" % (t, ax, ay, az) )
stderr.flush()

except (KeyboardInterrupt, SystemExit):
raise
except:
traceback.print_exc()
# -------------------------------------------------------


I'm getting this error:

Traceback (most recent call last):
File "D:\Desktop\androidSensor123.py", line 21, in <module>
data = message.split( "," )
TypeError: a bytes-like object is required, not 'str'

Answer

you're trying to split bytes object

convert it back to a string like this, by decoding the bytes back to a string

data = data.decode() # you can also specify the encoding of the string if it's not unicode
data = message.split(",")

this is a demonstration of what is going on

>>> a = b'hello,world'
>>> a.split(',')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: a bytes-like object is required, not 'str'
>>> a = a.decode()
>>> a.split(',')
['hello', 'world']
Comments