1

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 withprint(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?

2
  • BTW, pprint.pprint might help with debugging problems like this. In this case, from pprint import pprint; pprint(output.decode()) -> shows the whole string, in a readable format. Commented Aug 22, 2019 at 16:54
  • Thanks, that is really nice tool Commented Aug 22, 2019 at 16:56

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

3 Comments

For windows, use output.decode().replace('\r', '\r\n')
Stupid me... for some reasone I took \r for new line... <facepalm>
@WaketZheng ah, of course. So the cross-platform option is ...replace('\r', os.linesep)
2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.