How to Clear the Terminal Screen in Python?

Estimated read time 1 min read

To clear the terminal screen in Python, you can make use of the os module and issue the appropriate command based on the operating system you are using. Here’s an example that works on different platforms:

import os

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

# Example usage

In this example, the clear_screen() function uses the os.system() function to execute a command that clears the terminal screen. 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_screen() function, the terminal screen will be cleared, providing a clean slate for further output.

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