How To Clear The Console In Python

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:

For Linux or macOS, we will use the ‘clear’ command:

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:

For Linux or macOS, using ‘subprocess’ with the ‘clear’ command:

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).

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

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.