问题
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