Home » Programming » Python » How to Clear the Terminal/Screen in Python

How to Clear the Terminal/Screen in Python

This tutorial will show you several ways to clear the terminal/screen in your Python scripts, with code examples that you can copy and paste into your own project.

Clearing the screen will remove all text from the screen, blanking/resetting it. This is useful to hide output from the command line or previous Python statements so that you can more easily see newly added output, and keep your command line apps looking tidy.

There are a few ways to achieve this, so here they are:

Clearing the Screen in Python Using the ‘os’ Library in Linux

This is the best way of clearing the screen in Python. It uses the built-in os library to the system to clear the screen:

import os

os.system('clear')

Above, the os library is imported so that it can be used. It is then used to issue the ‘clear’ command to the system. Easy! Your screen is now cleared!

Clearing the Screen in Python Using the ‘os’ Library in Windows

We’re a Linux blog, but when writing scripts that others will use you need to consider that they might be running on a lesser operating system. The ‘clear’ command doesn’t work on the Windows CLI, so you’ll need to instead issue the ‘cls’ command:

import os

os.system('cls')

This otherwise behaves exactly the same as the previous example – the screen is cleared of all text output.

Using ‘subprocess’ to Clear the Screen

Depending on your use case, you may wish to avoid using the os.system() function to execute code – for example if you are concerned that a user may be able to inject their own code into your script if you are accepting and executing user input, or your script will be running with restricted permissions. In this case, the subprocess module can be used instead

import subprocess

subprocess.call('clear' if os.name == 'posix' else 'cls')

Above, subprocess.call is used to call the ‘clear’ command if running on a POSIX system (Linux, BSD, or MacOS), or the ‘cls’ command if running on a non-POSIX system (which we can assume is probably Windows).

Clearing the Screen the Hacky Way

If you just want an empty screen and don’t care how you do it, you can always just print 100 blank lines:

print('\n' * 100)   

It’s a brute-force method, but if for some reason you can’t use os or subprocess, it does the job!

SHARE:
Photo of author
Author
I'm Brad, and I'm nearing 20 years of experience with Linux. I've worked in just about every IT role there is before taking the leap into software development. Currently, I'm building desktop and web-based solutions with NodeJS and PHP hosted on Linux infrastructure. Visit my blog or find me on Twitter to see what I'm up to.

Leave a Comment