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.


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


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.

Updated on: 08-Aug-2019

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started