I’m new to coding and am using VS Code to learn Python.
Is there a way to only clear a section or part of the screen?
I know how to clear the whole screen, but I want to leave part of it alone.
I want to have the program title and initial instructions printed at the top of the screen, with some user input instructions lower down. I want the user input instructions to change in response to the input, while leaving the top alone.
Is there a way to do this, without a while loop constantly re-printing the whole screen each time?
I’ve searched all over and can’t seem to find a solution!
I’ve tried:
import os
os.system('cls')
but this clears the whole screen and I only want to clear part of it, say from line 5 onwards.
Matthew Keeble is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
7
First of all: if you’ve learned Python’s “print” and “input” and now intend to make more sophisticated programs, you might want to learn how to create a proper GUI with tkinter, or a local web app with Flask. Proper terminal based programs can be hard to master.
That said, you would be better using a proper terminal library. The “way” you know to clear the screen, though very spread in the internet is more or less infamous: it requires running an entire program, besides your own Python code – just to do the same that printing a four character sequence (using proper control characters) do.
“ncurses” is one such lib which comes pre-installed with Python – but it won’t work on the windows cmd (it might work if you use the “windows terminal” app, though).
There is a version of curses for Windows on Pypi, and also there are textual, terminedia and other libs which can give you more control over the terminal without having to use raw ctrl characters – known as ANSI sequences.
If you are on Linux, Mac, or a proper terminal program in Windows,
These work by printing sequences starting by "<ESC>["
and ending with a command. The special character “ESC” is printed using its codepoint "x1b"
(or some prefer the "33"
octal form).
So, print("x1b[2J", end="", flush=True)
will erase the entire screen (without running another entire process). And changing the “2” in this sequence to “0” or “1” will erase from the cursor position to the end of the screen, or from the cursor position to the start of the screen. – a Partial erase, as you want. But you have to combine that with cursor movement sequences.
So, to move the cursor up 8 lines, and erase from there to the end of the screen you can do, for example: print("x1b[8Ax1b[0J", end="", flush=True)
(note that the named “end” and “flush” arguments to print will avoid it placing an extra new-line which would forward the cursor one line bellow where it’s positioned)
Also, if you are on Windows and these sequences are not working, one way is to use the colorama
package – it emulates ANSI chars even on windows cmd.