How to clean the console in Python?


I'm an Ubuntu Operating System user and when I want to clean the Terminal, I use the clear command.

>>> clear

However, in Python , how could I be able to clean the terminal when I use it from the command line?

Is there any simple way to do this?


Simply press ctrl + L (works in the shell too – you don't even need to type clear ).

This in the terminal. In a program, you can simply print a number of blank lines greater than the terminal size: print("\n" * 130) , or, if you are on Linux or Mac, print the ANSI sequence that erases the screen: print("\x1b[2J") . See more details below.

CTRL + L clears the screen if you're on some Linux terminal – and maybe one or another of the Windows interactive environments – but not on Idle, and other Python prompts built into IDE's – and it's certainly not appropriate if you want to erase the screen from within a program (you cannot ask the user to type "ctrl + L" to clear the screen 🙂 )

The reason why there is no simple function call in the Python standard library is that the standard inputs and outputs are not thought of, in a generic programming language, always as a "terminal" – they represent a stream of input data, and two outbound (stdout and stderr). But the language itself "does not know" that it is running in the terminal when some program is executed. For programs made specifically for the terminal that want more sophisticated interaction (including the mouse), the Python standard library includes the curses module (see below).

The solution by calling the external command – be it cls on windows or clear on Linux/Mac OS, with os.system works -but it has a basic problem: it's an external program – a whole external process in the operating system, find the file in disk, create the process, to make an API call to the terminal. In terms of resource usage it 's the same as calling a locksmith to open and lock the door again each time you leave the house .

Well – these "screen blank" programs – both Unix clear and DOS "cls", as well as "clear" and CTRL + L itself, don't do much more than simply print several blank lines , so that the contents of the current screen scroll up.

To do this in Python, just print a single string with a sufficient number of "linefeeds" (the character represented by '\n' – whose decimal code is "10").

A little more annoying is knowing the exact number of linefeeds needed to clear the screen exactly and no more linefeeds. If that's not a concern, a number like 130 blank lines is more than enough to scroll a full HD terminal with font size 4 – then simply:

print ("\n" * 130) 

It's guaranteed to erase any terminal, regardless of OS type, without having to run another process outside the Python interpreter just for that.

Of course, it's more elegant to print a number of blank lines just equal to the number of lines in the terminal – and no more. Among other things, a user used to using the terminal might expect to be able to scroll up to see the previous screen in the lines immediately preceding the first line of the blank screen (although the clear command resets this history as well).

For this, as of Python 3.3, there is the get_terminal_size function in the Python OS module. For those who are writing a program that will work in several versions of Python, the functionality can be encapsulated in a function like:

def clear():
        import os
        lines = os.get_terminal_size().lines
    except AttributeError:
        lines = 130
    print("\n" * lines)

But in Python 3.3 or above, just do:

import os
print("\n" * os.get_terminal_size().lines)

Also, on Unixes, and perhaps some Windows terminal/prompt programs, " ANSI strings " are recognized – that is, the terminal itself recognizes special character strings representing commands such as clearing the screen, changing the color of the screen. font, cursor position -etc – They are a very interesting "toy" – and much simpler than Python's curses module (which I talk about below). To erase the screen on any Linux terminal or on most Unixes (I don't know if it works directly on Mac OS X) – just print the sequence "\x1b[2J" – (the "\x1b" is the character <ESC> o same code that is generated by the key with that name). The <ESC>[ sequence starts multiple ANSI sequences. To see the exact strings supported by your terminal, run the infocmp command in the shell.

By this technique, erasing the screen, and positioning the cursor in the first row and first column can be done like this:


(The print command prints by default a "\n" – if in Python 3 use print("\x1b[2J\x1b[1;1H", end="") to avoid getting stuck on the second line – in Python2, it's worth putting a from __future__ import print_function at the beginning of the file and doing the same.)

Remembering that – and from what I understand from the context of this question – if the idea is to just erase the screen while in Python interactive mode – in this case, the "ctrl + L" will do just fine.

For those who want to make a complex program with interaction through the terminal, my tip is always the following: if you're at this point, it's time to think about escaping from the terminal. Python allows interaction with various graphical libraries to create an application in its own window – which is much more comfortable for the end user. Users accustomed to the command line interface will be happy to call the program from the system command line, passing options directly in it – for that consult the argparse module of the standard library.

If even so, if the author prefers to create an interactive interface in the terminal, the tip is to use the curses module – also from the standard library – with it you get a "window" (text) type object in the terminal, where you can position the cursor in exact places, erasing the screen, changing colors, etc… And with some work (not a little) you can make an application with a really professional face – since users of this program have been frozen in time since the 1990s. for that purpose, erasing the screen with print("\n" * 130) is enough.

With curses, you can erase the screen by doing:

import curses
window = curses.initscr()

However, the terminal will be in this "application" mode where "print" and "input" can have different results than what happens in a normal terminal. In particular, it is important to position the cursor at the desired position on the screen before each print by calling the window.move(line, col) . When terminating the program, it is vital to return the terminal to its normal state by calling the curses.endwin() function.

Scroll to Top