Open In App

How to clear screen in python?

Last Updated : 21 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

When working in the Python interactive shell or terminal (not a console), the screen can quickly become cluttered with output. To keep things organized, you might want to clear the screen. In an interactive shell/terminal, we can simply use

ctrl+l

But, if we want to clear the screen while running a python script, there's no built-in keyword or function/method to clear the screen. So, we do it on our own as shown below:

Clearing Screen in Windows

1. Using cls

You can use the cls command to clear the screen in Windows. This can be done by running the following command via os.system() or subprocess.

Python
import os

# Clearing the Screen
os.system('cls')

Output

Initially:

clearScreen1
Before cls

After clearing screen:

clearScreen2
After cls

2. Using os.system('clear')

You can also only "import os" instead of "from os import system" but with that, you have to change system('clear') to os.system('clear'). 

Python
from os import system, name
from time import sleep

if name == 'nt':
    _ = system('cls')
else:
    _ = system('clear')

print('hello geeks\n'*10)

sleep(2)

Explanation:

  • if name == 'nt' checks if the operating system is Windows ('nt' stands for Windows).
  • system('cls') is used to clear the screen in Windows.
  • else: If the system is macOS or Linux (where os.name is 'posix'), it uses system('clear') to clear the screen.

3. Using subprocess.call()

Another way to clear the screen is by using the subprocess module, which allows you to execute system commands. This method can be used to invoke either cls or clear based on the operating system.

Python
from subprocess import call
from time import sleep
import os

print('hello geeks\n'*10)

sleep(2)

_ = call('clear' if os.name == 'posix' else 'cls')

Explanation:

  • call(): This function from the subprocess module runs the specified command in the terminal.
  • os.name == 'posix': Checks if the operating system is macOS or Linux. If it is, it runs clear to clear the terminal screen.
  • 'cls': If the system is Windows, it runs cls to clear the screen.

Clearing Screen in Linux

In this example, we used the time module and os module to clear the screen in Linux os.

Python
import os
from time import sleep

# some text
print("a")
print("b")
print("c")
print("d")
print("e")
print("Screen will now be cleared in 5 Seconds")

# Waiting for 5 seconds to clear the screen
sleep(5)

# Clearing the Screen
os.system('clear')

Next Article

Similar Reads