How to clear screen in python?


In Python sometimes we have link the output and we want to clear the screen in the cell prompt we can clear the screen by pressing Control + l . But there are situations when we need to clear the screen programmatically depending on the amount of output from the program and how we want to format the output. In such case we need to put some commands in the python script which will clear the screen as and when needed by the program.

We need the system() from the OS module of python to clear up the screen. For different platforms like windows and Linux we need to pass different commands as shown in the example below. Also we use the ‘_’ variable which is used to hold the value of last expression in interpreter.

Example

import os
from time import sleep
# The screen clear function
def screen_clear():
   # for mac and linux(here, os.name is 'posix')
   if os.name == 'posix':
      _ = os.system('clear')
   else:
      # for windows platfrom
      _ = os.system('cls')
   # print out some text
print("The platform is: ", os.name)
print("big output\n"* 5)
# wait for 5 seconds to clear screen
sleep(5)
# now call function we defined above
screen_clear()

Output

Running the above code gives us the following result −

The platform is: nt
big output
big output
big output
big output
big output

The above output gets cleared after 5 seconds from the result window.

raja
Published on 08-Aug-2019 10:08:47
Advertisements