Skip to content Skip to sidebar Skip to footer

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

Solution 1:

print"\033c"

works on my system.

You could also cache the clear-screen escape sequence produced by clear command:

importsubprocessclear_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
importsysclear_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 osos.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') orb''
clear_screen_seq = curses.tigetstr('clear') orb''
os.write(sys.stdout.fileno(), e3 + clear_screen_seq)

Solution 2:

You can use the Python interface to ncurses, specifically window.erase and window.clear.

https://docs.python.org/3.5/library/curses.html

Solution 3:

I use 2 print statements to clear the screen.

Clears the screen:

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

Moves cursor to begining row 1 column 1:

print(chr(27) + "[1;1f")

I like this method because you can move the cursor anywhere you want by [<row>;<col>f

The chr(27) is the escape character and the stuff in quotes tells the terminal what to do.

Post a Comment for "Python - Clearing The Terminal Screen More Elegantly"