Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to clear Python shell?
Python provides a python shell which is used to execute a single Python command and display the result. It is also called REPL. REPL stands for Read, Evaluate, Print and Loop. The command is read, then evaluated, afterwards the result is printed and looped back to read the next command.
Sometimes after executing so many commands and getting haphazard output or having executed some unnecessary commands, we may need to clear the python shell. If the shell is not cleared, we will need to scroll the screen too many times which is inefficient. Thus, it is required to clear the python shell.
The commands used to clear the terminal or Python shell are cls and clear.
Basic Clear Commands
Windows
import os
os.system('cls')
Linux/Mac
import os
os.system('clear')
Cross-Platform Clear Function
Let us create a function that works on both Windows and Unix-based systems. The following example shows output for a few seconds and then clears the shell ?
from os import system, name
from time import sleep
def clear():
# for windows
if name == 'nt':
_ = system('cls')
# for mac and linux
else:
_ = system('clear')
print("Hi Learner!!")
sleep(5)
clear()
The output of the above code is ?
Hi Learner!! (screen clears after 5 seconds)
How It Works
Import
osandsleepDefine a function where the commands to clear the shell are specified,
clsfor windows andclearfor linuxPrint some output
Let the screen sleep for few seconds
Call the function to clear the screen
Alternative Methods
Using subprocess
import subprocess
import os
def clear_screen():
if os.name == 'nt': # Windows
subprocess.run('cls', shell=True)
else: # Linux/Mac
subprocess.run('clear', shell=True)
clear_screen()
Using ANSI Escape Codes
def clear_with_ansi():
print('\033[2J\033[H', end='')
clear_with_ansi()
Conclusion
Use os.system('cls') for Windows and os.system('clear') for Linux/Mac to clear the Python shell. Create a cross-platform function using os.name to detect the operating system and apply the appropriate clear command.
