How to Clear Screen in Python 3
In an interactive shell/terminal, we can use the following command to clear the screen.
ctrl+l
There are many cases where the console becomes messy due to many lines of output. It will be beneficial if we can clear the screen at some time.
But what if we want to clear the screen using Python Script. When you are working with large programs in Python, there are some scenarios when we have to clear the screen programmatically depending on the amount of output from the program and how we want to format the output.
Unfortunately, Python does not have any function to do clear the screen. We can use ANSI escape sequences, but these are not portable and might not produce the desired output.
In that case, we have to put some commands in the python script, which will run and clear the screen as needed by the program.
How to Clear Screen in Python 3
To clear the screen using Python script, use the system() from the OS module. For different platforms like MacOS, Windows, and Linux, we have to pass different commands.
Let’s write a code that will identify the OS, and based on that, and it will clear the screen.
import os from time import sleep def clear_screen(): # It is for MacOS and Linux(here, os.name is 'posix') if os.name == 'posix': _ = os.system('clear') else: # It is for Windows platfrom _ = os.system('cls') # print out some text print("The platform is: ", os.name) print("Homer simpson says: Yello") # wait for 2 seconds to clear screen sleep(2) # Calling the clear_screen() function clear_screen()
Output
The platform is: posix Homer simpson says: Yello
I am using MacOS, which is why it returns posix. When you run the program, it will return the provided Home text, and after 1 second, it will clear the screen.
Clear Screen using Subprocess module
You can also use the call() function of the Python subprocess module and pass the clear command to clean the screen.
import os from subprocess import call from time import sleep def clear_screen(): _ = call('clear' if os.name == 'posix' else 'cls') # print out some text print("The platform is: ", os.name) print("Homer Simpson says: Yello") # wait for 2 seconds to clear screen sleep(2) # Calling the clear_screen() function clear_screen()
Output
The platform is: posix Homer simpson says: Yello
And you will get the same output. We use the sleep() function that suspends (waits) execution of the current thread for a given number of seconds.
That is it for the clear screen in Python.