3

I am running a console application that takes data coming from various sensors around the house. Sometimes the transmission is interrupted and thus the packet does not make sense. When that happens, the contents of the packet is output to a terminal session. However, what has happened is that while outputting the erroneous packet, it has contained characters that changed character set of the current terminal window, rendering any text (apart from numbers) as unreadable gibberish.

What would be the best way to filter the erroneous packets before their display while retaining most of the special characters? What exactly are sequences that can change behaviour of the terminal?

I would also like to add that apart from scrambled output, the application still works as it should.

Ryan Haining
  • 35,360
  • 15
  • 114
  • 174
petr
  • 2,554
  • 3
  • 20
  • 29

3 Answers3

2

Your terminal may be responding to ANSI escape codes. To prevent the data from inadvertently affecting the terminal, you could print the repr of the data, rather than the data itself:

For example,

good = 'hello'
bad = '\033[41mRED'

print('{!r}'.format(good))
print('{!r}'.format(bad))

yields

'hello'
'\x1b[41mRED'

whereas

print(good)
print(bad)

yields

enter image description here

(Btw, typing reset will reset the terminal.)

unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677
1

You can convert all characters outside of the ASCII range which should eliminate any stray escape sequences that will change the state of your terminal.

print s.encode('string-escape')
Mark Ransom
  • 299,747
  • 42
  • 398
  • 622
0

When you get a packet check it for validity before outputting it. One possibility is to check that each character in the packet is printable, that is, in the range of 32-127 decimal, before output. Or add checksums to the packets and reject any with bad checksums.

James Thiele
  • 393
  • 3
  • 9