Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

shell - Python - Clearing the terminal screen more elegantly

I know you can clear the shell by executing clear using os.system, but this way seems quite messy to me since the commands are logged in the history and are litterally interpreted as commands run as the user to the OS.

I'd like to know if there is a better way to clear the output in a commandline script?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...