11

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.

Alex
  • 599
  • 1
  • 5
  • 14

4 Answers4

17

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

TkTech
  • 4,729
  • 1
  • 24
  • 32
2

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
TheClockTwister
  • 819
  • 8
  • 21
  • I'm not sure why this was down voted. I wouldn't say it is more efficient, but it would clear the screen... – Reedinationer Mar 16 '19 at 01:48
  • @Reedinationer I've just tried it in Jupyternotebook, didn't work. It returned 0. And it didn't clear anything. Besides, I don't want to clear everything. – Alex Mar 16 '19 at 02:07
  • @Alex Oh OK. I think you are supposed to leave comments when you downvote so the poster can know what was wrong and possibly edit it to fix the post. Plus people that visit the site in the future can read what the issues were with a certain piece of code :) – Reedinationer Mar 16 '19 at 02:52
  • @Reedinationer It wasn't me, sorry. I am a newcomer and I'm not allowed to vote. Thank you anyway. – Alex Mar 16 '19 at 02:56
  • While the solution is simple, it is not generally applicable. A typical use case for clearing the line is showing progress (e.g. percent complete and a description of the current task) without littering the terminal. (One would typically want to leave only something like "Task X completed successfully.".) In contrast, clearing the whole terminal would also remove messages of more lasting interest, such as warnings. @Alex That is because Jupyter notebook prints to a cell on a webpage, not to the Windows command terminal. See https://stackoverflow.com/a/24818304/4071801 . – Elias Hasle May 11 '21 at 09:16
  • Yea, that's true, you could also use `print(..., end="\r")` or similar, when only a single line should be cleared... :) – TheClockTwister May 13 '21 at 12:03
0

Alternative to print on a single line

I have a script that prints the x, y coordinates of the mouse as such:

import pyautogui
import time
while True:
    x, y = pyautogui.position()
    position_string = "X: {} Y: {}".format(str(x).rjust(4), str(y).rjust(4))
    print(position_string, end='')
    print('\b' * len(position_string), end='', flush=True)
    time.sleep(1)

Where I will point out that you can print the backspace character ('\b') the amount of times that there are characters on the screen (len(position_string)), and when used with the end='' and flush=True options this will constantly print on a single line within your console. I should also note that this does not work in IDLE, but only on an actual command line! In IDLE the backspace characters are actually printed as some weird square shape...

Community
  • 1
  • 1
Reedinationer
  • 5,661
  • 1
  • 12
  • 33
  • Nice trick, but you have keep track of how much you printed so you later press enough back spaces to erase them. A headache if you are in a hurry. – Alex Mar 16 '19 at 00:07
0

This is called ANSI escape code . 2K is the name for Erase in Line. Quote from the link:

Erases part of the line. If n is 0 (or missing), clear from cursor to the end of the line. If n is 1, clear from cursor to beginning of the line. If n is 2, clear entire line. Cursor position does not change.

You can also try echo -e '\x1b[2k' in the terminal for better understanding.

X. W
  • 331
  • 2
  • 14