Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent terminal character set switch on data printing

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.

like image 331
petr Avatar asked Jan 25 '26 00:01

petr


1 Answers

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.)

like image 65
unutbu Avatar answered Jan 26 '26 16:01

unutbu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!