How to clear cmd/terminal while running a python script


I keep seeing ways to clear the shell while running a script, however is there a way to clear the screen while running a script in the CMD?
My current method works like this:

import title
def clear():
    print('n' * 25)

from engine import clear
print(Fore.CYAN + Style.BRIGHT + "--------------------------------")

However this method isn’t really reliable as some cmd sizes are different on all computers, nor have I tried it on OSx.

Asked By: dawsondiaz



Your best bet is probably to use the colorama module to enable ANSI escape sequences in the Windows terminal, and then use the ANSI sequence to clear the screen:

import colorama

This should work on all common platforms.

Answered By: Sven Marnach

Here’s another way, that handles Windows cases as well as Unix-like systems (Linux, OSX, etc.):

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

The clear command works in all Unix-like systems (ie, OSX, Linux, etc.). The Windows equivalent is cls.

Answered By: sgarza62

import os
os.system(‘cls’ if == ‘nt’ else ‘clear’)

Answered By: user21314167
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.