Member Avatar

Hi, all.

I am trying to clear the console window without using the "os" library.
This seems like the only way to do it:

from os import system
import time
print "I will clear the screen in 2 seconds"
print "*Cleared Screen*"

But the problem is, this only works for Windows, so if I wanted to do it for linux i must change line 5 to system("clear") any way it could work for all operating systems without using os?

Gribouillis commented: good question +13

Recommended Answers

All 3 Replies

In linux, you can clear the screen with

def clear():


This uses the ANSI escape sequences which work in a linux terminal. This may work in windows too if you import module colorama which implements ansi sequences for all OSes

from colorama import init

it will also allow you to print in colors.

You can also browse colorama's source code to see how it uses module ctypes and windows libraries to clear the screen. The drawback of clearing the screen is that it usually doesn't work in the various python IDE's. Ideally, your code should check if it is running in a terminal.

By the way, the statement SystemExit() does nothing significant. You probably meant raise SystemExit.

A little bit more univeral:

def clear_screen():
    clear the screen in the command shell
    works on windows (nt, xp, Vista) or Linux
    import os
    os.system(['clear','cls'][ == 'nt'])

You could also use a more 'Python' way to clear screens-

print('\n' *100)
#prints 100 newlines

Although it seems messy, it works cross platform. You could also consider Tkinter as a way to develop your programs because there's a built in clear screen command.


Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.