Oskar Persson
Oskar Persson

Reputation: 6735

Completely clearing the terminal window using Python

How can I in Python (v 2.7.2) completely clear the terminal window?

This doesn't work since it just adds a bunch of new lines and the user can still scroll up and see earlier commands

import os
os.system('clear')

Upvotes: 3

Views: 11614

Answers (8)

ideasman42
ideasman42

Reputation: 47968

Adding for completeness, if you want to do this without launching an external command, do:

print('\x1bc')

Only tested on Linux.

Upvotes: 0

Babak D
Babak D

Reputation: 41

I am using Linux and I found it much easier to just use

import os

in the header of the code and

os.system('clear')

in the middle of my script. No lambda or whatever was needed to get it done. What I guess is important to pay attention to, is to have the import os in the header of the code, the very beginning where all other import commands are being written...

Upvotes: 0

user5673930
user5673930

Reputation: 9

No need of importing any libraries. Simply call the cls function.

cls()

Upvotes: 0

Alea Kootz
Alea Kootz

Reputation: 919

for windows:

import os
def clear(): os.system('cls')

for linux:

import os
def clear(): os.system('clear')

then to clear the terminal simply call:

clear()

Upvotes: 0

Oskar Persson
Oskar Persson

Reputation: 6735

Found here that the correct command to use was tput reset

import os

clear = lambda : os.system('tput reset')
clear()

Upvotes: 4

Adrien
Adrien

Reputation: 1

On Windows:

import os
os.system('cls')

On Linux:

import os
os.system('clear')

Upvotes: 0

Nafiul Islam
Nafiul Islam

Reputation: 82440

I've tried this and it works:

>>> import os
>>> clear = lambda : os.system('clear')
>>> clear()

BEFORE

Before

AFTER clear()

After

Upvotes: 0

Mattias
Mattias

Reputation: 461

You can not control the users terminal. That's just how it works.

Think of it like write only.

Upvotes: -1

Related Questions