print "33c"
works on my system.
You could also cache the clear-screen escape sequence produced by clear
command:
import subprocess
clear_screen_seq = subprocess.check_output('clear')
then
print clear_screen_seq
any time you want to clear the screen.
tput clear
command that produces the same sequence is defined in POSIX.
You could use curses
, to get the sequence:
import curses
import sys
clear_screen_seq = b''
if sys.stdout.isatty():
curses.setupterm()
clear_screen_seq = curses.tigetstr('clear')
The advantage is that you don't need to call curses.initscr()
that is required to get a window object which has .erase()
, .clear()
methods.
To use the same source on both Python 2 and 3, you could use os.write()
function:
import os
os.write(sys.stdout.fileno(), clear_screen_seq)
clear
command on my system also tries to clear the scrollback buffer using tigetstr("E3")
.
Here's a complete Python port of the clear.c
command:
#!/usr/bin/env python
"""Clear screen in the terminal."""
import curses
import os
import sys
curses.setupterm()
e3 = curses.tigetstr('E3') or b''
clear_screen_seq = curses.tigetstr('clear') or b''
os.write(sys.stdout.fileno(), e3 + clear_screen_seq)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…