How to Clear Python Shell?

What is Python Shell?

Python shell allows us to interact Python interpreter. It is used to execute single-line Python commands and display the output. While we can write Python code directly in the shell each line of code is treated as a single Python command and each line is executed one by one. 

When we install Python, it provide us with the shell to interact with Python interpreter. 

Python Shell
Image: Python Shell

We can also use the "cmd" or Windows PowerShell as the Python shell. This shell is sometimes referred to as the terminal in different IDEs. Occasionally, there is a need to clear the screen of the shell. Here we will understand different methods to accomplish this task.

How to Clear Python Shell or terminal?

We can clear the screen of the Python shell or terminal using the 'os' module in Python. Let's look at the commands to clear the shell in different operating systems -

In Windows

Clearing Python Shell in Windows
GIF: Clearing Python Shell in Windows 11
First, import the 'os' module using the command "import os". Then, use "os.system('cls')" command to clear the screen of the shell/ terminal. Alternatively, you can also use "os.system('CLS')". 

import os
os.system('cls')

In Linux/ MacOS

Similarly, import the 'os' module using the command "import os". Then, use the "os.system('clear')" command to clear the screen of the shell/ terminal.

import os
os.system('clear')

For Any Operating System

The Following code snippet can be used to clear the screen of the python shell or terminal -
import os
def clear_screen():
os.system('cls' if os.name == 'nt' else 'clear')

# Call the function to clear the screen
clear_screen()

The "os.name" attribute identifies the name of the operating system dependent module imported. If it's 'nt', it's a Windows system; otherwise, it's assumed to be a Unix-like system.
The "os.system" function is then used to execute the appropriate clear command.

Advertisements

Useful Resources:

Comments