[Tutor] Clearing the screen from the terminal

Alan Gauld alan.gauld at yahoo.co.uk
Sun Oct 18 15:18:04 EDT 2020


On 18/10/2020 19:36, Cranky Frankie wrote:
> Is there a way, before I run my Python program in command/terminal mode (no
> GUI), to clear the screen before the program starts? If so, can it be done
> while the program is running as well?

The problem is that there are literally hundreds of terminals
(and terminal emulators) out there and they all use different
control codes to clear the screen.
There are two easy ways to do this:

import os
def clear():
    os.system('clear')  # if its a *nix based system

OR

def clearscreen(size = 25):
    print '\n' * size

Fast enough for normal human use.
The first leaves your cursor at the top.
The second it's at the bottom.

The "correct" way of doing screen control in a terminal
(as used by vim and the top commands etc) is to use the
curses module. Curses provides screen and cursor control
regardless of terminal type. But that introduces a
whole extra layer of complexity (along with power).
For example regular print() and input() fuctions won't
work, you need to use curses own equivalents.

A minimal curses program to clear the screen is:

import curses

def main(win):   # win refers to the terminal screen.
   win.clear()
   # your program here....

curses.wrapper(main)

See my tutorial topic on "Event Driven Programming"
for a little more info on curses (and read the
official docs of course).

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list