Python 2.7到3的转换

2024-04-20 15:02:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我在网上找到了一个代码片段,它可以显示android手机的传感器读数,但我需要在Python3上运行它。我不知道该怎么解决:

# -------------------------------------------------------
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()
# -------------------------------------------------------

我得到这个错误:

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'

Tags: importhostmessagedataportstderrsocketax
1条回答
网友
1楼 · 发布于 2024-04-20 15:02:15

您正在尝试拆分bytes对象

通过将字节解码回字符串,将其转换回如下字符串

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

这是一个正在发生的事情的示范

>>> 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']

相关问题 更多 >