How to clear Python shell

Clearing the Python shell doesn’t have a built-in direct command like “clear,” but you can achieve it depending on the environment you’re using. Here’s a detailed explanation:

1. Clearing Python Shell in the Terminal or Command Prompt

If you are running Python in a terminal or command prompt, you can use commands specific to the operating system to clear the screen:

For Windows:

  1. Import the os module:
import os

2. Use the system function with the command cls:

os.system('cls')

For macOS/Linux:

  1. Import the os module:
import os

2. Use the system function with the command clear:

os.system('clear')

Code Example for Cross-Platform Compatibility:

import os
import platform

def clear_screen():
    if platform.system() == "Windows":
        os.system('cls')
    else:
        os.system('clear')

clear_screen()

2. Clearing Python Interactive Environment (IDLE)

The Python IDLE shell does not support commands like cls or clear. Instead:

  • Manually close and reopen the shell.
  • Alternatively, restart the shell using Shell > Restart Shell from the menu.

3. Clearing a Jupyter Notebook Cell Output

In Jupyter Notebook:

  • You cannot directly clear the entire screen, but you can clear the output of specific cells:
  1. Click Cell > All Output > Clear in the menu.
  2. Programmatically clear the cell output using:
from IPython.display import clear_output
clear_output(wait=True)

4. Using Libraries for Enhanced Interactivity

If you’re using interactive tools like IPython, you can use the magic command:

%clear

Notes:

  • Clearing the screen does not erase the variables or the state of the program. If you want to erase everything, close the interpreter.
  • Select the appropriate method based on your environment, for example, terminal, IDLE, or Jupyter.