In this tutorial, we will learn how to clear the console in Python. Clearing the console helps remove the unwanted output and keeps the screen clean while running your Python program.
There might be cases where you want to refresh the console screen and display only the recent output data. We will look into different ways to clear the console in your Python script for both Windows and Linux environments.
Using the ‘os’ module
Python’s ‘os’ module provides a simple and efficient way to communicate with the operating system. We can use the ‘os’ module to clear the console in Python by calling the ‘system()’ function with appropriate command arguments.
For Windows, we will use the ‘cls’ command:
1 2 |
import os os.system('cls') |
For Linux or macOS, we will use the ‘clear’ command:
1 2 |
import os os.system('clear') |
Using the ‘subprocess’ module
Another method to clear the console in Python is by using the ‘subprocess’ module. This module is helpful in accessing system commands and piping them in a similar way as ‘os’, but provides a better interface.
For Windows, using the ‘subprocess’ with the ‘cls’ command look like this:
1 2 |
import subprocess subprocess.call('cls', shell=True) |
For Linux or macOS, using ‘subprocess’ with the ‘clear’ command:
1 2 |
import subprocess subprocess.call('clear', shell=True) |
Using ANSI escape sequences
Using ANSI escape sequences allows us to manipulate the console output by sending special characters that perform certain actions. This method works on most modern terminals, including Linux, macOS, and Windows (in the Windows terminal or VSCode terminal).
1 |
print("\033[2J\033[H", end="") |
The ‘\033[2J’ is the escape sequence to clear the screen, and ‘\033[H’ is the escape sequence to move the cursor to the top-left position of the screen.
Full Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
import os import platform import subprocess # Function to clear the console def clear_console(): # Detect the current operating system current_os = platform.system() # Clear the console based on the detected operating system if current_os == 'Windows': os.system('cls') # For Windows elif current_os == 'Linux' or current_os == 'Darwin': os.system('clear') # For Linux / macOS else: print("\033[2J\033[H", end="") # For other environments, use ANSI escape sequences # Example Usage print("Hello, World!") input("Press Enter to clear the console...") clear_console() print("Console Cleared!") |
Output:
Hello, World! Press Enter to clear the console... (console clears) Console Cleared!
Conclusion
In this tutorial, we discussed three different ways to clear the console in Python, using the ‘os’ module, the ‘subprocess’ module, and ANSI escape sequences. Depending on your operating system and environment, you can choose the best method that suits your requirements to keep your console output clean and organized.