How to clear the screen in Python easily?

How can I clear the screen in Python?

I’m writing a program in Python and need to clear the screen during execution. I know how to use the commands to clear the screen in both Windows and Linux, but I’m unsure how to do this specifically in Python.

How can I implement clear screen python?

Hey @Punamhans

One way to clear the screen is by using the os module, which lets you call system commands depending on the operating system. Here’s an example:

import os  
  
def clear_screen():  
    # For Windows  
    if os.name == 'nt':  
        os.system('cls')  
    # For Linux or macOS  
    else:  
        os.system('clear')  
  
clear_screen()  

This works seamlessly across platforms!

Hey All! Hope you all are doing great!

That’s a great approach, @charity-majors ! Another option is to use the subprocess module, which is a bit more versatile for running system commands. Here’s how you could do it:

import subprocess  
  
def clear_screen():  
    subprocess.call('cls' if os.name == 'nt' else 'clear', shell=True)  
  
clear_screen()  

It’s pretty concise and avoids directly interacting with the OS module.

Both of those solutions are solid, but if you want to avoid system-specific dependencies entirely, you can simulate clearing the screen by simply printing a lot of newlines. It’s not as elegant, but it works!

def clear_screen():  
    print("\n" * 100)  
  
clear_screen()  

This method is super lightweight and works regardless of the operating system!