How to Clear the Terminal in Python?

Estimated read time 1 min read

To clear the terminal in Python and remove all the previous output, you can make use of the os module along with appropriate commands for different operating systems. Here’s an example that works on various platforms:

import os

def clear_terminal():
    os.system('cls' if == 'nt' else 'clear')

# Example usage

In this example, the clear_terminal() function uses the os.system() function to execute a command that clears the terminal. The command used is 'cls' for Windows ('nt' stands for NT kernel) and 'clear' for Unix-based systems (including Linux and macOS).

By calling the clear_terminal() function, the terminal screen will be cleared, removing all previous output and providing a clean slate for further interaction.

Note: The os.system() function is used here for simplicity. However, it’s worth mentioning that executing shell commands through os.system() may have security implications, so exercise caution when using this approach, especially with untrusted input.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply