Clear screen in Python

In this tutorial, we are going to learn how to clear screen in Python. There are various methods to clear screen in Python is to use control+L. But we are going to discuss method to clear the screen while we are running the Python script.

There are two processes for doing that first one is using os library and another one using subprocess module now we are going to discuss os than we will discuss the subprocess.

Os Clear Method to clear console screen in Python

For os library process these are the steps to be followed: –

  1. Firstly from the os library we will import system and name so that we can differentiate between windows and mac.
  2. Then we define a function.
  3. For windows, we pass the argument cls whereas for mac or Linux we will pass clear.
  4. Now we will store this value under any variable we take it as _ (underscore) because last output of Python shell is always _(underscore).
  5. We will use sleep function to wait before our output disappears and then we call our function.

Code : –

from os import system, name 

from time import sleep # importing sleep so that our output does not disappear and wait

# defining our function 

def clearScreen(): 
  
    # for windows os
    if name == 'nt': 
        _ = system('cls') 
  
    # for mac and linux os(The name is posix)
    else: 
        _ = system('clear') 
  

print('So the text is going to be cleared') 

sleep(5) # sleep for 5 seconds after printing output 

clearScreen()  # now we can call our function

Output :-

So the text is going to be cleared

Subprocess Method

Firstly we import call method from the subprocess module than we will define the function.

Code: –

from subprocess import call

from time import sleep # importing sleep so that our output does not disappear and wait

# defining our function

def clearScreen(): 
     _ = call('cls' if os.name=='nt' else 'clear') #Call depending on the os

print('So the text is going to be cleared')

sleep(5) # sleep for 5 seconds after printing output

clearScreen() # now we can call our function

This is how we can clear screen in Python.

Also Read : –

getch() and clrscr() functions in C++

Leave a Reply

Your email address will not be published. Required fields are marked *