96

How do you clear the screen in shell?

I've seen ways like:

import os
os.system('cls')

This just opens the Windows cmd, clears the screen and closes but I want the shell window to be cleared.

I'm using version 3.3.2 of Python.

Gino Mempin
  • 25,369
  • 29
  • 96
  • 135
josh
  • 1,205
  • 4
  • 14
  • 14

20 Answers20

91

What about the shortcut CTRL+L?

It works for all shells e.g. Python, Bash, MySQL, MATLAB, etc.

Stefan van den Akker
  • 6,661
  • 7
  • 48
  • 63
Hafiz Muhammad Shafiq
  • 8,168
  • 12
  • 63
  • 121
68
import os

os.system('cls')  # For Windows
os.system('clear')  # For Linux/OS X
Rajan Mandanka
  • 2,003
  • 21
  • 13
  • Also, `os.system('clear')` for Mac OS X terminals (confirmed to work with the default shell, `bash`, and also for `csh`). – jvriesem Nov 07 '14 at 17:00
  • You can also define a function to run this, like: def cls(): os.system('cls') (hit enter twice). Then you can just type cls() to clear the screen. –  Jun 23 '16 at 20:57
  • The question was about how to do this in the shell. – Kyle Delaney Dec 20 '16 at 22:37
  • 1
    @KyleDelaney while inefficient, it works in the shell. Also many people found this useful because that's what they were looking for. – Gaspa79 Jul 22 '18 at 19:44
65

For macOS/OS X, you can use the subprocess module and call 'cls' from the shell:

import subprocess as sp
sp.call('cls', shell=True)

To prevent '0' from showing on top of the window, replace the 2nd line with:

tmp = sp.call('cls', shell=True)

For Linux, you must replace cls command with clear

tmp = sp.call('clear', shell=True)
Macintosh Fan
  • 355
  • 1
  • 4
  • 18
GalHai
  • 666
  • 6
  • 8
  • 4
    I am using Mac OS X, and I tried this `import subprocess as sp sp.call('clear',shell=True)` which works, except there is a `0` at the top of the terminal window. – Daniel Dropik Apr 06 '14 at 03:43
  • 0 is the return value of the 'cls' command call from shell. i edited the answer to get rid of that as well, by simply storing that value in a variable. – GalHai Apr 09 '14 at 14:51
  • 9
    Try this `ctrl+L` – Sai Ram May 08 '16 at 05:05
  • That works on the command line. Question was how to do it in Python. – Edward Falk Jul 22 '16 at 07:21
  • Thanks for the solution, I was missing shell=True. to prevent the 0 from showing up you can also add a semicolon to the end of the statement. ``sp.call('cls', shell=True);`` – Waylon Walker Apr 18 '17 at 14:44
15

Here are some options that you can use on Windows

First option:

import os
cls = lambda: os.system('cls')

>>> cls()

Second option:

cls = lambda: print('\n' * 100)

>>> cls()

Third option if you are in Python REPL window:

Ctrl+L
Vlad Bezden
  • 83,883
  • 25
  • 248
  • 179
12

The sort of thing that you are looking for is to be found in the curses module.

i.e.

import curses  # Get the module
stdscr = curses.initscr()  # initialise it
stdscr.clear()  # Clear the screen

Important Note

The important thing to remember is before any exit, you need to reset the terminal to a normal mode, this can be done with the following lines:

curses.nocbreak()
stdscr.keypad(0)
curses.echo()
curses.endwin()

If you don't you will get all sort of strange behaviour. To ensure that this is always done I would suggest using the atexit module, something like:

import atexit

@atexit.register
def goodbye():
    """ Reset terminal from curses mode on exit """
    curses.nocbreak()
    if stdscr:
        stdscr.keypad(0)
    curses.echo()
    curses.endwin()

Will probably do nicely.

Steve Barnes
  • 27,618
  • 6
  • 63
  • 73
  • Can you be more specific? – josh Sep 21 '13 at 20:30
  • 1
    I'm running Mac OS X 10.7.5 and iTerm 2 for my terminal. Using Python2.7, the `stdscr = curses.initscr()` works to clear the screen, and the `stdscr.clear()` does nothing. Using Python3.4, the `stdscr = curses.initscr()` does clear the screen, but takes away the terminal's ability to process newlines. When I press enter repeatedly, it gives the following: `>>> >>> >>> >>> ` and so on. I can still type commands, but they don't show up. Also, this behavior persists even when I `exit()` Python. AVOID USE! – jvriesem Nov 07 '14 at 17:05
  • @jvriesem the curses module has been in use for a long time and has been used by a lot of people - I would suggest that you see if you can replicate the behaviour in a short, (20 lines or so), example and either post it as a stack overflow question or on the developer mailing list. – Steve Barnes Nov 08 '14 at 09:47
  • Good idea -- that's a better response than my "AVOID USE!" statement. The first two lines of this answer were the two lines that replicate the problem for me. Do you know if there's any reason the `curses` module might have compatibility issues (Windows vs. Mac vs. Linux)? I can confirm that this issue happens on two different Mac terminals, at least. The behavior persists in BASH but not CSH. Hmm.... Do you think I should contact the curses developer, the shell developer, or just ask the SO community? Thanks again! – jvriesem Nov 09 '14 at 18:54
  • @jvriesem - I have updated my answer to include how to reset your terminal to standard mode once you have finished, including on any exit. – Steve Barnes Nov 09 '14 at 20:14
9

In addition to being an all-around great CLI library, click also provides a platform-agnostic clear() function:

import click
click.clear()
Martin Valgur
  • 5,793
  • 1
  • 33
  • 45
7

This function works in any OS (Unix, Linux, macOS, and Windows)
Python 2 and Python 3

import platform    # For getting the operating system name
import subprocess  # For executing a shell command

def clear_screen():
    """
    Clears the terminal screen.
    """

    # Clear command as function of OS
    command = "cls" if platform.system().lower()=="windows" else "clear"

    # Action
    return subprocess.call(command) == 0

In windows the command is cls, in unix-like systems the command is clear.
platform.system() returns the platform name. Ex. 'Darwin' for macOS.
subprocess.call() performs a system call. Ex. subprocess.call(['ls','-l'])

ePi272314
  • 12,557
  • 5
  • 50
  • 36
6

An easier way to clear a screen while in python is to use Ctrl + L though it works for the shell as well as other programs.

Ram
  • 3,092
  • 10
  • 40
  • 56
BioinfoNerd
  • 69
  • 1
  • 3
4

If you are using linux terminal to access python, then cntrl+l is the best solution to clear screen

Hafiz Muhammad Shafiq
  • 8,168
  • 12
  • 63
  • 121
4

I am using a class that just uses one of the above methods behind the scenes... I noticed it works on Windows and Linux... I like using it though because it's easier to type clear() instead of system('clear') or os.system('clear')

pip3 install clear-screen

from clear_screen import clear

and then when you want to clear the shell:

clear()
3

using windows 10 and pyhton3.5 i have tested many codes and nothing helped me more than this:

First define a simple function, this funtion will print 50 newlines;(the number 50 will depend on how many lines you can see on your screen, so you can change this number)

def cls(): print ("\n" * 50)

then just call it as many times as you want or need

cls()
sami.almasagedi
  • 153
  • 1
  • 5
3

Rather than importing all of curses or shelling out just to get one control character, you can simply use (on Linux/macOS):

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

(Source: Clear terminal in Python)

CharlesL
  • 265
  • 5
  • 21
2

Subprocess allows you to call "cls" for Shell.

import subprocess
cls = subprocess.call('cls',shell=True)

That's as simple as I can make it. Hope it works for you!

Seth Connell
  • 867
  • 1
  • 9
  • 12
2

Command+K works fine in OSX to clear screen.

Shift+Command+K to clear only the scrollback buffer.

Ayer
  • 120
  • 2
  • 6
1
import curses
stdscr = curses.initscr()
stdscr.clear()
sl1ng5h0t
  • 54
  • 3
1
  1. you can Use Window Or Linux Os

    import os
    os.system('cls')
    os.system('clear')
    
  2. you can use subprocess module

    import subprocess as sp
    x=sp.call('cls',shell=True)
    
Pang
  • 9,564
  • 146
  • 81
  • 122
1

os.system('cls') works fine when I open them. It opens in cmd style.

Xantium
  • 11,201
  • 10
  • 62
  • 89
Phich
  • 11
  • 1
0

Here's how to make your very own cls or clear command that will work without explicitly calling any function!

We'll take advantage of the fact that the python console calls repr() to display objects on screen. This is especially useful if you have your own customized python shell (with the -i option for example) and you have a pre-loading script for it. This is what you need:

import os
class ScreenCleaner:
    def __repr__(self):
        os.system('cls')  # This actually clears the screen
        return ''  # Because that's what repr() likes

cls = ScreenCleaner()

Use clear instead of cls if you're on linux (in both the os command and the variable name)!

Now if you just write cls or clear in the console - it will clear it! Not even cls() or clear() - just the raw variable. This is because python will call repr(cls) to print it out, which will in turn trigger our __repr__ function.

Let's test it out:

>>> df;sag
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'df' is not defined
>>> sglknas
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'sglknas' is not defined
>>> lksnldn
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'lksnldn' is not defined
>>> cls

And the screen is clear!

To clarify - the code above needs to either be imported in the console like this

from somefile import cls

Or pre load directly with something like:

python -i my_pre_loaded_classes.py
Ofer Sadan
  • 11,391
  • 5
  • 38
  • 62
0

That's the best way:

>>>import os
>>>def cls(): os.system('cls')
>>>cls()
0

For the Python IDLE 3.8.1 you can restart the Shell

CTRL + F6

On the menu Click on the Shell menu. Then click on the Restart Shell option.