Clear terminal in Python

Viewed 542758

Does any standard "comes with batteries" method exist to clear the terminal screen from a Python script, or do I have to go curses (the libraries, not the words)?

27 Answers

A simple and cross-platform solution would be to use either the cls command on Windows, or clear on Unix systems. Used with os.system, this makes a nice one-liner:

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

What about escape sequences?

print(chr(27) + "[2J")

If you are on a Linux/UNIX system then printing the ANSI escape sequence to clear the screen should do the job. You will also want to move cursor to the top of the screen. This will work on any terminal that supports ANSI.

import sys
sys.stderr.write("\x1b[2J\x1b[H")

This will not work on Windows unless ANSI support has been enabled. There may be an equivalent control sequence for Windows, but I do not know.

Just use:

print("\033c")

This will clear the terminal window.

You could try to rely on clear but it might not be available on all Linux distributions. On windows use cls as you mentionned.

import subprocess
import platform

def clear():
    subprocess.Popen( "cls" if platform.system() == "Windows" else "clear", shell=True)

clear()

Note: It could be considered bad form to take control of the terminal screen. Are you considering using an option? It would probably be better to let the user decide if he want to clear the screen.

This will be work in Both version Python2 OR Python3

print (u"{}[2J{}[;H".format(chr(27), chr(27)))

You could tear through the terminfo database, but the functions for doing so are in curses anyway.

python -c "from os import system; system('clear')"

you can make your own. this will not be dependent on your terminal, or OS type.

def clear(num):
    for i in range(num): print 

clear(80)
print "hello"

If all you need is to clear the screen, this is probably good enough. The problem is there's not even a 100% cross platform way of doing this across linux versions. The problem is the implementations of the terminal all support slightly different things. I'm fairly sure that "clear" will work everywhere. But the more "complete" answer is to use the xterm control characters to move the cursor, but that requires xterm in and of itself.

Without knowing more of your problem, your solution seems good enough.

A perhaps cheesy way to clear the screen, but one that will work on any platform I know of, is as follows:

for i in xrange(0,100):
    print ""
Related