Computer >> Computer tutorials >  >> Programming >> Python

How to clear screen using python?


When we work with python interactive shell/terminal, we continuously get the output and the window looks very much clumsy, not to see any output clearly, most of the time we use ctrl+lto clear the screen.

But if we want to clear the screen while running a python script we have to do something for that because there’s no built-in keyword or function/method to clear the screen. So, we have to write some code for that.

So, we have to follow some steps

Step 1 − First we have to write from os import system.
Step 2 − Next Define a function.
Step 3 − Then make a system call with 'clear' in Linux and 'cls' in Windows as an argument.
Step 4 − Next we have to store the returned value in an underscore or whatever variable we want (an underscore is used because python shell always stores its last output in an underscore).
Step 6 − Lastly call the function.

Example code

from os import system, name
from time import sleep
# define our clear function
def screen_clear():
   if name == 'nt':
      _ = system('cls')
   # for mac and linux(here, os.name is 'posix')
   else:
      _ = system('clear')
# print out some text
print('Hi !! I am Python\n'*10)
sleep(2)
# now call function we defined above
screen_clear()

Output

Hi !! I am Python
Hi !! I am Python
Hi !! I am Python
Hi !! I am Python
Hi !! I am Python
Hi !! I am Python
Hi !! I am Python
Hi !! I am Python
Hi !! I am Python
Hi !! I am Python

Using subprocess module.

Example

import os
from subprocess import call
from time import sleep
def screen_clear():
   _ = call('clear' if os.name =='posix' else 'cls')
print('Hi !! I am Python\n'*10)
# sleep for 2 seconds after printing output
sleep(2)
# now call the function we defined above
screen_clear()

Output

Hi !! I am Python
Hi !! I am Python
Hi !! I am Python
Hi !! I am Python
Hi !! I am Python
Hi !! I am Python
Hi !! I am Python
Hi !! I am Python
Hi !! I am Python
Hi !! I am Python