How to clear screen in python?

When working with Python programs, you may need to clear the terminal screen programmatically to improve output readability. While you can manually clear the screen with Ctrl + L, Python provides ways to clear the screen automatically within your script.

Python uses the os.system() function to execute system commands for clearing the screen. The command differs between operating systems: 'clear' for Unix/Linux/macOS and 'cls' for Windows.

Basic Screen Clearing Function

Here's how to create a cross-platform screen clearing function ?

import os

def clear_screen():
    # For Unix/Linux/macOS (os.name is 'posix')
    if os.name == 'posix':
        os.system('clear')
    else:
        # For Windows
        os.system('cls')

# Test the function
print("This text will be cleared in 3 seconds...")
import time
time.sleep(3)
clear_screen()
print("Screen cleared! This is new content.")
Screen cleared! This is new content.

Alternative Method Using subprocess

A more secure approach uses the subprocess module instead of os.system() ?

import subprocess
import platform

def clear_screen_safe():
    system = platform.system().lower()
    if system == 'windows':
        subprocess.run('cls', shell=True)
    else:
        subprocess.run('clear', shell=True)

# Example usage
print("Content before clearing...")
print("Line 1")
print("Line 2") 
print("Line 3")

# Clear after 2 seconds
import time
time.sleep(2)
clear_screen_safe()
print("Screen cleared using subprocess!")
Screen cleared using subprocess!

Practical Example with Menu System

Here's a practical example showing screen clearing in a simple menu system ?

import os
import time

def clear_screen():
    os.system('cls' if os.name == 'nt' else 'clear')

def display_menu():
    clear_screen()
    print("=== MAIN MENU ===")
    print("1. Show current time")
    print("2. Display message")
    print("3. Exit")
    print("==================")

def show_time():
    clear_screen()
    print("Current time:", time.strftime("%H:%M:%S"))
    time.sleep(2)

def show_message():
    clear_screen()
    print("Hello from Python!")
    time.sleep(2)

# Simulate menu navigation
display_menu()
time.sleep(1)
show_time()
display_menu()
=== MAIN MENU ===
1. Show current time
2. Display message
3. Exit
==================

Comparison of Methods

Method Security Platform Support Best For
os.system() Lower All platforms Simple scripts
subprocess.run() Higher All platforms Production code

Key Points

  • Use os.name to detect the operating system
  • Windows uses 'cls', Unix-like systems use 'clear'
  • The subprocess module is safer than os.system()
  • Screen clearing is useful for creating clean, interactive programs

Conclusion

Use os.system() with platform detection for simple screen clearing in Python scripts. For better security in production code, prefer subprocess.run() over os.system().

---
Updated on: 2026-03-15T17:04:16+05:30

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements