Use the OS module to Clear the screen in Python, if we want to clear the screen while running a Python script. You have to use different commands for different platforms like Windows and Linux.
To clear the screen in the cell prompt can do this by pressing Control + l.
ctrl+l
Example Clear screen in Python
Simple example code clears the screen after 5 seconds. In the example use the ‘_’ variable which is used to hold the value of the last expression in the interpreter.
Make a system call with ‘clear’ in Linux and ‘cls’ in Windows as an argument.
import os
from time import sleep
# The screen clear function
def screen_clear():
# for mac and linux(here, os.name is 'posix')
if os.name == 'posix':
_ = os.system('clear')
else:
# for windows platfrom
_ = os.system('cls')
# print out some text
print("The platform is: ", os.name)
print("big output\n" * 5)
# wait for 5 seconds to clear screen
sleep(5)
# now call function we defined above
screen_clear()
Output:
Another example
import os
def clear_screen():
if os.name == 'posix': # For UNIX/Linux/Mac systems
_ = os.system('clear')
elif os.name == 'nt': # For Windows systems
_ = os.system('cls')
clear_screen()
Note: Using the os.system
function to execute shell commands might not be the most platform-independent or secure way to clear the screen, but it should work for most cases. If you’re building a more complex application, you might want to look into libraries like curses
(for UNIX-like systems) or third-party cross-platform libraries that provide terminal manipulation capabilities.
Do comment if you have any doubts or suggestions on this Python topic.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.