Clear screen Python | Example code

  • by

Use OS module to Clear screen in Python, if we want to clear the screen while running a python script. You have to use different commands for different platforms like Windows and Linux.

To clear the screen in the cell prompt can do this by pressing Control + l.

ctrl+l

Example Clear screen in Python

Simple example code clear screen after 5 seconds. In the example use the ‘_’ variable which is used to hold the value of the last expression in the interpreter.

Make a system call with ‘clear’ in Linux and ‘cls’ in Windows as an argument.

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:

Clear screen Python

Do comment if you have any doubts or suggestions on this Python topic.

Note: IDE: PyCharm 2021.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.