. Advertisement .
..3..
. Advertisement .
..4..
Our topic today: How to clear console in Python.
A console is instrumental in executing Python commands and jumping script lines quickly. Kind of a backlog.
However, the visible console becomes cluttered after running many test commands. You might end up scrolling the screen repeatedly and even accidentally re-running the same commands.
It is time to clear your Python console!
We have several methods to complete this easy task, depending on your platform and preference.
Install OS Module First
We use the os module to clear the console in Python.
This module in Python includes portable functions for creating and deleting a directory. Then, it is easy to fetch the contents, adjust and identify the current directory.
It is built-in with the Python3 version, or you can install the OS here, and import the module to your underlying operating system.
How to Clear Console in Python? – Four Easy Ways
Once the OS module is checked, pass the string cls or clear as a parameter to remove the console.
The cls command
The cls (short for the clear screen) is a command on DOS, Microsoft Windows, Digital Research FlexOS, ReactOS, and IBM OS/2 operating systems.
import os
def clear_console():
command = 'cls'
os.system(command)
clear_console()
The clear command
The clear command, meanwhile, is for Linux operating system and OSX and POSIX machines.
import os
def clear_console():
command = 'clear'
os.system(command)
clear_console()
The cross-platform command
We also have a quick-hack command useful on almost all operating systems. For example, we use the cls command for Microsoft Windows (nt) otherwise, use the clear command.
import os
def clear_console():
os.system('cls' if os.name=='nt' else 'clear')
clear_console()
Lamda function
The cls and clear commands allow clearing all the consoles in Python.
Clear a single line
If you only desire to clear a single line or a specific number of command lines, use the Lamda function instead.
+ The cls command
import os
clear_console = lambda: os.system('cls')
clear_console()
+ The clear command
import os
clear_console = lambda: os.system('clear')
clear_console()
+ The cross-platform command
import os
clear_console = lambda: os.system('cls' if os.name in 'nt' else 'clear')
clear_console()
Clear multiple lines
Just add a new line symbol \n to multiply the number of lines for the console screen to clear up.
For example, we clear 100 lines.
import os
clear_console = lambda: os.system('cls' if os.name in 'nt' else 'clear')
print('\n' * 100)
clear_console()
Wrapping Up
There are also other ways to clear console in Python. Yet, the commands mentioned above are the most common and easiest to use. You can develop new commands from the samples according to your platform or even create advanced links for cross-platforms.
Feel free to drop a line here if you have any concerns, and also share your commands here for others’ reference.
Leave a comment