gpt4 book ai didi

python - Gcode解析问题? - for 循环字节和字符串

转载 作者:太空宇宙 更新时间:2023-11-03 21:29:23 25 4
gpt4 key购买 nike

我正在学习 python,我需要从套接字解析一些 gcode,并将命令传递到串行端口。我使用选择器让其中一些工作正常。conn 是我正在接收 Gcode 的 tcp 连接。 sbus 是我的串口。

假设 data = b'G0 X1.0 Y2.0 Z0.0 ;移动到 X,Y,Z'这是典型的 gcode 行。下面我的代码的输出是这样的:

1 b'G0
2 X1.0
3 Y2.0
4 Z0.0

所以,它像我想要的那样丢弃了评论后的所有内容。它像我想要的那样丢弃了裸露的 b'\n' 。但是,第一个元素包含 b' ,而其他元素则不包含。我很困惑如何摆脱 b'

我确信我没有以正确的Pythonic方式这样做,我希望能够深入了解如何处理第一个项目上的b'(如果没有gcode,最后一个项目有一个尾随'评论,我也必须处理)

谢谢

def read(conn, mask):
data = conn.recv(1000) # Should be ready
print(Color.Red, data,Color.end) #debug print, make text red
if data==b'\n': # don't process the slash-n
return
if data:
conn.send(b'ok\r\n') # sends back to openPnP
print('wroteback ok to tcp') # debug print
i=1
for word in repr(data).split(' '):
if word==';':
break
if word=='':
continue
print(i,Color.Green+word+Color.end) # prints each part of gcode line
i=i+1
sbus.write(data) # will actually send translated commands to serial prot, not just echo the data
else:
print('closing', conn)
sel.unregister(conn)
conn.close()

最佳答案

b 代表字节。它只是告诉您数据类型是字节。下面是一段检查字节和字符串以及如何从一个字节移动到另一个字节和字符串的代码。

b = b'I am a bytes'
s = 'I am a string'



print(type(b), # bytes
type(s), # string
type(b.decode('utf8')), # string
type(s.encode('utf8')) # bytes
)

# change byte to string
b_s = b.decode('utf8')
print(b_s == 'I am a bytes')
# True

# change string to bytes
s_b = s.encode('utf8')
print(s_b == b'I am a string')
# True

关于python - Gcode解析问题? - for 循环字节和字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53625854/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com