简体   繁体   中英

Decode bytes to ascii string

I receive bytes from external device with pyserial in the form:

b'S\\rSN 00\\rSC 00\\rFC 00\\rRI 00\\rMF 00006643\\rTS 0000BA39\\rTB 00000000\\rCB FFFFFFFF\\rCL 002\\rI> '

It is done with the code (snippet):

while ser.in_waiting > 0:
    output = ser.read(ser.in_waiting)
    print(output)

So I expect to print it as text in the form like:

S
SN 00
SC 00
FC 00
RI 00
MF 00006643
TS 0000BA39
TB 00000000
CB FFFFFFFF
CL 002
I>

But when I try to decode it with print(output.decode()) or print(output.decode('ascii')) I get only part of all (84) characters:

I> 002FFFFF

What is wrong? How to get all the decoded text?

The carriage return characters '\\r' move to the start of the line without going to the next line, so the lines are getting overwritten. Simply replace the carriage returns with newlines:

print(output.decode().replace('\r', '\n'))

I'm assuming you're using Unix/Linux - not sure if it's different on Windows.

Your string has embedded carriage returns, which your terminal interprets as an instruction to move the cursor back to the beginning of the current line, causing the subsequent text to overwrite the previous text.

You are seeing the I> from the last line, followed by the 002 from the previous line, and the FFFFF from the line before that (shorter sequences don't completely overwrite what is currently on the line).

The solution (which I won't repeat here; wjandrea already posted it) is to replace the carriage returns with proper line feeds.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM