Python Clear Screen
In Python, you can clear the screen to provide a cleaner output or improve the user experience in a terminal or command prompt. There are multiple ways to achieve this depending on your operating system and requirements. Here are some common methods to clear the screen:
- Using
os
module (cross-platform solution):
import os
def clear_screen():
os.system(‘cls’ if os.name == ‘nt’ else ‘clear’)
# Call the function to clear the screen
clear_screen()
The os.system()
function is used to execute a shell command. The cls
command is used on Windows, while clear
is used on Unix-based systems (Linux, macOS).
- Using ANSI escape codes (works on Unix-based systems and Windows with some limitations):
import sys
def clear_screen():
if sys.platform.startswith(‘win’):
os.system(‘cls’)
else:
print(‘\033c’, end=”)
# Call the function to clear the screen
clear_screen()
The ANSI escape code '\033c'
is used to clear the screen on Unix-based systems. However, it might not work as expected on all Windows terminals.
Please note that using os.system()
to execute shell commands can have security implications if you are accepting user input. In such cases, consider using platform-specific libraries like subprocess
instead.
Python Training Demo Day 1
Conclusion:
Unogeeks is the No.1 IT Training Institute for Python Training. Anyone Disagree? Please drop in a comment
You can check out our other latest blogs on Python here – Python Blogs
You can check out our Best In Class Python Training Details here – Python Training
Follow & Connect with us:
———————————-
For Training inquiries:
Call/Whatsapp: +91 73960 33555
Mail us at: info@unogeeks.com
Our Website ➜ https://unogeeks.com
Follow us:
Instagram: https://www.instagram.com/unogeeks
Facebook: https://www.facebook.com/UnogeeksSoftwareTrainingInstitute
Twitter: https://twitter.com/unogeeks