Clearing the screen in a Python script depends on the operating system you’re using.
Here’s how to do it for macOS, Linux and Windows:
For macOS and Linux
You can use the os.system() method to execute the clear command in macOS and Linux.
Example
import os
from time import sleep
# Printing some text
print("1")
print("2")
print("3")
print("Screen will now be cleared in 3 seconds")
# Waiting for 3 seconds before clearing the screen
sleep(3)
# Clearing the Screen
os.system('clear')
Output
Before clearing
After 3 seconds
For Windows
On windows, the clear screen command is cls.
Example
import os
from time import sleep
# Printing some text
print("1")
print("2")
print("3")
print("Screen will now be cleared in 3 seconds")
# Waiting for 3 seconds before clearing the screen
sleep(3)
# Clearing the Screen
os.system('cls')
It will clear the screen.
Cross-Platform Solution
Method 1: Using os.system()
If you want a solution that works across different operating systems, you can check the operating system and execute the appropriate command:
Example
import os
from time import sleep
def welcome_message():
print("Welcome to the cross-platform screen clearing program!")
def clear_screen():
print("1")
print("2")
print("3")
print("Screen will now be cleared in 3 seconds")
sleep(3)
# Clear the screen based on the operating system
os.system('cls' if os.name == 'nt' else 'clear')
welcome_message()
clear_screen()
Output
Before clearing
After 3 seconds
Method 2: Using the subprocess module
This is a more secure alternative to using os.system() as it avoids shell injection vulnerabilities.
Example
import subprocess, os
from time import sleep
def clear_screen():
print("A")
print("B")
print("C")
print("D")
print("Screen will now be cleared in 4 seconds")
sleep(4)
# For macOS and Linux
if os.name == 'posix':
_ = subprocess.call('clear')
# Windows
elif os.name == 'nt':
_ = subprocess.call('cls')
clear_screen()
Output
Before clearing
After 4 seconds
Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.