Table of Contents
Why do we need to clear the screen?
When you are using Python in a terminal or interactive shell, you might want to clear the screen when you get a messy output.
One simple way to clear the terminal or interactive shell is:
ctrl+l
But what if you want to clear the screen programmatically while running the python script based on the amount of the output the program generates. Python doesn’t provide any in-built function or methods to clear the screen, so we are on our own.
We achieve this with the ANSI escape sequence, but these are not portable and might not produce the expected results.
print(chr(27)+'[2j') print('\033c') print('\x1bc')
Clean screen with System module in Python script:
We are going to add some commands to the Python script which will clear the screen when needed. In our script we are going to:
- Import system() and name from OS.
- Define your own function to clear the screen.
- Call the system() with ‘clear’ as a parameter for Linux and ‘cls’ as a parameter in windows.
- Store the return value to another variable or underscore. An underscore is preferred because of Python stores the output of the last expression in the underscore.
- Call the function we defined.
Script:
from os import system,name #importing sleep to show output for some time from time import sleep #defining our function def clear_screen(): #for windows if name=='nt': _=system('cls') #for mac and linux, os.name is posix else: _=system('clear') print('Random gibberish text to use in web pages'*7) #sleep for 5 seconds after printing the output sleep(5) #call the function clear_screen()
Output:
Running the above code generates the below output and the screen gets cleared automatically 5 seconds.
Random gibberish text to use in web pagesRandom gibberish text to use in web pagesRandom gibberish text to use in web pagesRandom gibberish text to use in web pagesRandom gibberish text to use in web pagesRandom gibberish text to use in web pagesRandom gibberish text to use in web pages
Clear screen with subprocess module:
There is an alternative way to clear the screen with the subprocess module.
from subprocess import call from os import name #importing sleep to show output for some time from time import sleep #defining our function def clear_screen(): #for windows if name=='nt': _=call('cls',shell=True) #for mac and linux, os.name is posix else: _=call('clear',shell=True) print('Random gibberish text to use in web pages'*7) #sleep for 5 seconds after printing the output sleep(5) #call the function clear_screen()