问题描述
我正在通过串行端口接收数据包,但是当我收到数据包时,它是字节类,如下所示:
b'>0011581158NNNNYNNN +6\r'
如何将其转换为普通字符串?当我尝试从这个字符串中获取信息时,它以十进制表示形式出现.
您可以调用 decode
在 bytes 对象上将其转换为字符串,但只有当 bytes 对象实际表示文本时才有效:
要真正解析输入,您需要知道格式及其实际含义.为此,请识别连接到串行端口的设备(扫描仪?机器人?某种接收器?).并查找协议.在您的情况下,它可能是一个基于文本的协议,但您经常会发现字节代表数字,您可能需要查看 struct
模块.
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.
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.
这篇关于Pyserial 将字节转换为普通字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!