Pyserial converting bytes to normal string

你说的曾经没有我的故事 提交于 2019-12-12 04:29:07

问题


I am receiving a packet through a serial port but when I receive the packet it is of class bytes and looks like this:

b'>0011581158NNNNYNNN  +6\r'

How do I convert this to a normal string? When I try to take information from this string, it comes out as a decimal representation it appears.


回答1:


You can call decode on the bytes object to convert it to a string, but that only works if the bytes object actually represents text:

>>> bs = b'>0011581158NNNNYNNN  +6\r'
>>> bs.decode('utf-8')
'>0011581158NNNNYNNN  +6\r'

To really parse the input, you need to know the format, and what it actually means. To do that, identify the device that is connected to the serial port (A scanner? A robot? A receiver of some kind?). And look up the protocol. In your case, it may be a text-based protocol, but you'll often find that bytes stand for digits, in which you'll probably want to have a look at the struct module.



来源:https://stackoverflow.com/questions/24872439/pyserial-converting-bytes-to-normal-string

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