tags:

views:

221

answers:

7

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) ?

+2  A: 

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

Ignacio Vazquez-Abrams
+5  A: 

What about escape sequences?

print chr(27) + "[2J"
Joril
this is according to ANSI. makes sense...
Stefano Borini
Note that this is not portable across all terminal types... not that you'll run into too many odd types these days...
Ignacio Vazquez-Abrams
+1  A: 

python -c "from os import system; system('clear')"
Dyno Fu
Please, no. Thats terrible.
Yann Ramin
well, it works. A bit aggressive though.
Stefano Borini
`system('clear')` is terrible? I disagree.
Nick D
http://support.microsoft.com/kb/99261 - it's less terrible than win32api :)
gridzbi
+1  A: 

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.

print "\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.

Dave Kirby
A: 

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"
ghostdog74
... You don't need the empty string literal there. ... What? I'm trying to stay *positive* here!
Ignacio Vazquez-Abrams
you are pedantic, but i will give it to you
ghostdog74
+8  A: 
import os
os.system( [ 'clear', 'cls' ][ os.name == 'nt' ] )

Works on unix and Windows.

poke
os.system('cls' if os.name=='nt' else 'clear')
Teddy
Is basically the same, yes.
poke
only it takes twice the time to understand
Idan K
Which one? I can understand Teddy's version without thinking.
Tim Pietzcker
Idan: Yes, but once you understand how the code works, you can see the potential in it and use it for a lot more things.
poke
A: 

The answer provided by @poke should work.

Also, another easy way to achieve this is you can press Ctrl+l to clear the python shell history (just like any unix shell), if you are using *nix or Mac OS X.

abhiomkar