Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does this mean in Python '\x1b[2K'?

I've just learnt that to clear a line that you printed in Python, do this: sys.stdout.write('\x1b[2K')

Why is it so complicated? what does that weird code mean? and is there any alternative in print command?

Print does offer "end" option that allows to go back and forth in lines, but no way to clear what you printed. Overwriting via \r doesn't always work especially if the new line is shorter than the old one. You will get traces from the old line, so I need clearing first. Thanks.

like image 279
Alex Avatar asked Mar 15 '19 23:03

Alex


2 Answers

\x1b[2K is what's known as an ANSI terminal control sequence. They are a legacy of the 1970s and still used today (but vastly extended) to control terminal emulators.

\x1b is the ASCII for ESCAPE (literally the ESC key on your keyboard). [2K is the command "erase the current line".

There are many libraries in Python for working with the terminal, such as Urwid. These libraries will hide the inner workings of the terminal from you and give you higher-level constructs to create TUIs.

like image 197
TkTech Avatar answered Oct 07 '22 13:10

TkTech


However, there is a much more efficient way of doing this: You can use the print() command as usual, and delete the screen using

os.system("cls") # For Windows

or

os.system("clear") # For Linux
like image 36
TheClockTwister Avatar answered Oct 07 '22 14:10

TheClockTwister