Skip to main content
How to Clear Console in Python

How to Clear Console in Python

This tutorial helps How to Clear the Console in Python. There is a number of ways to clear the console based on the operating system. You can also clear the interpreter programmatically.

There are several methods for clearing the console in Python, depending on the operating system you are using.

Here, we’ll go over the most popular Python techniques for clearing the console in this article. We’ll use os the library, which is a built-in library that comes with Python3 installations.

You can also checkout other python tutorials:

Method 1: Using the os module

Import the os module and use its os.system() function to wipe the console in Python.

Let’s import os module:

import os

Clear Console in Linux system

We’ll use the os.system('clear') command to clear the console.

The Sample code:

import os

def clear_console():
    os.system('clear')

clear_console()

The screen will be cleared if the above command is entered into your console.

Clear Console in Windows system

For the Windows system, We’ll use the os.system('cls') command to clear the console.

The Sample code:

import os

def clear_console():
    os.system('cls')

clear_console()

Run the above command in your terminal to clear the screen.

Method 2: Using the subprocess module

The subprocess module provides a way to run shell commands from within your Python code. To clear the console in Python.

import subprocess

# For Windows
subprocess.call('cls', shell=True)

# For Linux/Unix
subprocess.call('clear', shell=True)

Method 3: Using ANSI escape codes

You can also clear the console using the ANSI escape codes, The ANSI escape codes are sequences of characters that control formatting, color, and other visual effects in the console.

print('\033c', end='')

The majority of terminals, including the Windows Command Prompt, Git Bash, and terminal emulators for Linux and macOS, are compatible with this method.

Lambda Function To Clear Console in Python

You can also use the lambda function to clear the python console.

import os
def clear_console(): return os.system('clear')

clear_console()

The screen will be cleared if the above code will run.

Conclusion

We have learned different ways to clear the console in python. Clearing the console in Python is a simple task that can be done using the os module, the subprocess module, or ANSI escape codes.

Leave a Reply

Your email address will not be published. Required fields are marked *