Most of the time, while working with Python interactive shell/terminal (not a console), we end up with a messy output and want to clear the screen for some reason. In an interactive shell/terminal, we can simply use
ctrl+l
But, what if we want to clear the screen while running a python script? Unfortunately, there’s no built-in keyword or function/method to clear the screen. So, we do it on our own.
Clearing Screen in windows Operating System
Method 1: Clear screen in Python using cls
You can simply “cls” to clear the screen in windows.
Python3
import os # Clearing the Screen os.system( 'cls' ) |
Example 2: Clear screen in Python using clear
You can also only “import os” instead of “from os import system” but with that, you have to change system(‘clear’) to os.system(‘clear’).
Python3
# import only system from os from os import system, name # import sleep to show output for some time period from time import sleep # define our clear function def clear(): # for windows if name = = 'nt' : _ = system( 'cls' ) # for mac and linux(here, os.name is 'posix') else : _ = system( 'clear' ) # print out some text print ( 'hello Lazyroar\n' * 10 ) # sleep for 2 seconds after printing output sleep( 2 ) # now call function we defined above clear() |
Example 3: Clear screen in Python using call
Another way to accomplish this is using the subprocess module.
Python3
# import call method from subprocess module from subprocess import call # import sleep to show output for some time period from time import sleep # define clear function def clear(): # check and make call for specific operating system _ = call( 'clear' if os.name = = 'posix' else 'cls' ) print ( 'hello Lazyroar\n' * 10 ) # sleep for 2 seconds after printing output sleep( 2 ) # now call function we defined above clear() |
Clearing Screen in Linux Operating System
In this example, we used the time module and os module to clear the screen in Linux os.
Python3
import os from time import sleep # some text print ( "a" ) print ( "b" ) print ( "c" ) print ( "d" ) print ( "e" ) print ( "Screen will now be cleared in 5 Seconds" ) # Waiting for 5 seconds to clear the screen sleep( 5 ) # Clearing the Screen os.system( 'clear' ) |