Python Clear Screen Function

Have you wondered how to clear the screen of your python interpreter?

Create a function that can be called to do this.

>>> import os

>>> def clear():

… os.system(‘cls’ if os.name == ‘nt’ else ‘clear’)

Microsoft Windows uses cls and Linux uses clear command.

Tip:

If you import inspect module you can see the code inside a function.

>>> import inspect

>>> print(inspect.getsource(clear))

The output will look like this:

def clear():

os.system(‘cls’ if os.name == ‘nt’ else ‘clear’)

Now to try clearing the screen.

Type clear() and the screen will clear…

>>>

Type dir() shows the three modules installed like ‘clear’, ‘inspect’ and ‘os’ in our session above amongst others.

Leave a comment