Clearing the terminal in Python is simplest with either ANSI escape codes (fast, no subprocess) or by invoking the OS command (cls on Windows, clear on Unix-like systems). Some IDE consoles need extra settings, and Python 3.13’s new interactive shell also provides a built-in clear command. Pick the method that fits your terminal and environment.
Method 1 — Clear using ANSI escape codes (fast and cross-platform terminals)
ANSI control sequences move the cursor and erase the display without launching a subprocess. They work in most terminals, including modern Windows terminals, but not in IDLE.
print("\033[H\033[2J", end="") # Home, then clear screen.
print("\033[H\033[3J", end="") # Home, clear screen, clear scrollback.
print("\033c", end="") # Reset terminal (clears everything).
Reference: See the ECMA-48 control functions for cursor positioning and erasing display (standards body spec).
Join readers who trust AllThings.How
Add us as a preferred source on Google so our practical guides show up first next time you search.
Add to Google Preferences →Method 2 — Call the OS clear command from Python
This mirrors what you would type in a shell: cls on Windows, clear elsewhere. It’s reliable in real terminals; some IDE consoles need a terminal emulation setting.
import os
import subprocess
def clear_console():
cmd = "cls" if os.name == "nt" else "clear"
# subprocess.call returns the command's exit code.
subprocess.call(cmd, shell=True)
clear_console()
import os
os.system("cls" if os.name == "nt" else "clear")
References: os.system, subprocess.call, os.name.
Open Run/Debug configuration → enable “Emulate terminal in output console.” This setting makes the console behave like a real terminal so clear commands take effect.
PyCharm Run/Debug configuration
Method 3 — Use the built‑in clear command in Python 3.13’s interactive shell
Python 3.13’s new REPL supports a native clear command (part of the redesigned shell).
Reference: PEP 762.
Method 4 — Use terminal keyboard shortcuts (manual)
Shortcuts are instant when you’re working interactively, but they don’t apply inside a running script.
Method 5 — Push output off-screen with newlines (last resort)
This works almost everywhere, including constrained IDE consoles, but it only scrolls the old output away and leaves scrollback intact.
print("\n" * 100)
import shutil
lines = shutil.get_terminal_size(fallback=(80, 24)).lines
print("\n" * lines, end="")
Environment notes
IDEs and shells vary. The IDLE shell typically ignores both ANSI sequences and cls/clear; clearing there often requires restarting the shell. In PyCharm, enabling “Emulate terminal in output console” lets cls/clear work from your script (see the PyCharm link above).
Pick ANSI codes for speed and zero subprocess overhead, or call cls/clear for OS parity; adjust IDE settings when needed to make clearing behave like a real terminal.






