W3docs

How to clear the interpreter console?

There are a few ways to clear the interpreter console in Python, depending on the specific environment you are using.

There are a few ways to clear the interpreter console in Python, depending on the specific environment you are using. Here are a few examples:

  1. Using the os module:

Clear console with os module

import os
os.system('cls' if os.name == 'nt' else 'clear')

This code uses the os.system() function to clear the console. The command used to clear the console depends on the operating system; cls is used for Windows, and clear is used for Mac and Linux.

  1. Using the subprocess module:

Clear console with subprocess module

import os
import subprocess
subprocess.run('cls' if os.name == 'nt' else 'clear', shell=True)

This code uses the subprocess.run() function to clear the console. The command used to clear the console is the same as in the previous example.

  1. Using the clear_output() function from the IPython.display module:

Clear console with IPython.display module

from IPython.display import clear_output
clear_output()

This code uses the clear_output() function from the IPython.display module. This method works only in IPython or Jupyter Notebook environments.

Please note that the above code snippets will work on most platforms, but might not work in all environments. So, it's always better to check the compatibility of the code snippet with the platform you are working on before using it.

Note: Clearing the console only removes the visible output from the terminal. It does not reset Python variables, execution history, or the interpreter state.