Clear Console in Python

  1. Use the os Module to Clear Interpreter Console in Python
  2. Print Multiple New Lines to Clear Interpreter Console in Python

This tutorial will demonstrate how to clear the interpreter console using the Python code.

Use the os Module to Clear Interpreter Console in Python

The os module provides a solution to clear the console using tools that control the operating system and contains functions that can write console commands.

The os module has a function system() that accepts a string parameter and will process that string into a console command into the local machine’s interpreter.

Since the objective is to clear the console, then the string to be passed as a parameter should be cls or clear, depending on what operating system the machine is running on (cls for Windows and DOS and clear for Linux, OSX and POSIX machines).

import os

def clearConsole():
    command = 'clear'
    if os.name in ('nt', 'dos'):  # If Machine is running on Windows, use cls
        command = 'cls'
    os.system(command)

clearConsole()

A way to make this function more concise is to use a ternary operator and declare a lambda function.

import os

clearConsole = lambda: os.system('cls' if os.name in ('nt', 'dos') else 'clear')

clearConsole()

Both solutions will clear the console instance that runs the Python code.

This is a more brute force approach to clear the console, but it’s just as effective. Declare a function that will print out multiple newlines (\n), which is a way to mock clearing the console.

Use a lambda function again to shorten the code and multiply the new line symbol \n to the number of lines you want the console screen to go up. In this example, we’ll multiply it by 150.

clearConsole = lambda: print('\n' * 150)

clearConsole()

The output will look like this:















localhost:~ user$ 

This solution isn’t the most optimal, but it does clear the contents of the console.

In summary, using the system() method of the os module can clear the console within Python code by passing the clear command as the parameter, depending on what OS the machine is running on. Another solution is to print multiple newlines within Python to mock the console’s clear command, which is not the best solution but will get the job done.

Contribute
DelftStack is a collective effort contributed by software geeks like you. If you like the article and would like to contribute to DelftStack by writing paid articles, you can check the write for us page.