How to clear the interpreter console?

Viewed 863061

Like most Python developers, I typically keep a console window open with the Python interpreter running to test commands, dir() stuff, help() stuff, etc.

Like any console, after a while the visible backlog of past commands and prints gets to be cluttered, and sometimes confusing when re-running the same command several times. I'm wondering if, and how, to clear the Python interpreter console.

I've heard about doing a system call and either calling cls on Windows or clear on Linux, but I was hoping there was something I could command the interpreter itself to do.

Note: I'm running on Windows, so Ctrl+L doesn't work.

30 Answers

As you mentioned, you can do a system call:

For Windows:

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

For Linux it would be:

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

here something handy that is a little more cross-platform

import os

def cls():
    os.system('cls' if os.name=='nt' else 'clear')

# now, to clear the screen
cls()

Well, here's a quick hack:

>>> clear = "\n" * 100
>>> print clear
>>> ...do some other stuff...
>>> print clear

Or to save some typing, put this file in your python search path:

# wiper.py
class Wipe(object):
    def __repr__(self):
        return '\n'*1000

wipe = Wipe()

Then you can do this from the interpreter all you like :)

>>> from wiper import wipe
>>> wipe
>>> wipe
>>> wipe

This is the simplest thing you can do and it doesn't require any additional libraries. It clears the screen and returns >>> to the top left corner.

print("\033[H\033[J", end="")

UPDATE 1:

Since this answer gets some attention, you might want to know how it works. The command above prints ANSI escape codes:

  • \033 stands for ESC (ANSI value 27).

  • \033[ is a special escape sequence called Control Sequence Introducer (CSI).

  • \033[H command moves the cursor to the top left corner of the screen.

  • \033[J clears the screen from the cursor to the end of the screen.

Optional parameter end="" avoids printing newline character after executing these commands, so >>> stays in the topmost row.

UPDATE 2:

You may want to extend the above command with one additional parameter - x (before J):

print("\033[H\033[xJ", end="")
  • If x is 1, it will clear from cursor to beginning of the screen.
  • If x is 2, it will clear entire screen and move cursor to upper left.
  • If x is 3, it will clear entire screen and delete all lines saved in the scrollback buffer.

So, this command will clear everything, including buffer:

print("\033[H\033[3J", end="")

COMMAND LINE:

To clear screen in a shell (console / terminal) you can use the same command. To clear entire screen and delete all lines saved in the scrollback buffer put 3 before J:

printf "\033[H\033[3J"

or create an alias:

alias cls='printf "\033[H\033[3J"'

The perfect cls, also compatible with Python2 (in .pythonrc file):

from __future__ import print_function
cls = lambda: print("\033c", end='')

and can be called from the terminal in this way:

cls()

Or directly:

print("\033c", end='')

\033[H\033[J only clears the visible screen, exactly the same as the clear command up to Ubuntu 18.10. It doesn't clear the scrollback buffer. Scrolling up will reveal the history.

To simulate this behavior, insert some terminal lines, then press Ctrl+L and insert more. After executing print("\033[H\033[J", end=""), only the screen lines inserted after pressing "Ctrl + L" will be deleted.

\033c clears everything.

\x1bc may not give the same result as \033c as the hex escape is not clearly length limited.

Here's a cross platform (Windows / Linux / Mac / Probably others that you can add in the if check) version snippet I made combining information found in this question:

import os
clear = lambda: os.system('cls' if os.name=='nt' else 'clear')
clear()

Same idea but with a spoon of syntactic sugar:

import subprocess   
clear = lambda: subprocess.call('cls||clear', shell=True)
clear()

Wiper is cool, good thing about it is I don't have to type '()' around it. Here is slight variation to it

# wiper.py
import os
class Cls(object):
    def __repr__(self):
        os.system('cls')
        return ''

The usage is quite simple:

>>> cls = Cls()
>>> cls # this will clear console.

Use idle. It has many handy features. Ctrl+F6, for example, resets the console. Closing and opening the console are good ways to clear it.

>>> ' '*80*25

UPDATE: 80x25 is unlikely to be the size of console windows, so to get the real console dimensions, use functions from pager module. Python doesn't provide anything similar from core distribution.

>>> from pager import getheight
>>> '\n' * getheight()

Arch Linux (tested in xfce4-terminal with Python 3):

# Clear or wipe console (terminal):
# Use: clear() or wipe()

import os

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

def wipe():
    os.system("clear && printf '\e[3J'")

... added to ~/.pythonrc

  • clear() clears screen
  • wipe() wipes entire terminal buffer

EDIT: I've just read "windows", this is for linux users, sorry.


In bash:

#!/bin/bash

while true; do
    clear
    "$@"
    while [ "$input" == "" ]; do
        read -p "Do you want to quit? (y/n): " -n 1 -e input
        if [ "$input" == "y" ]; then
            exit 1
        elif [ "$input" == "n" ]; then
            echo "Ok, keep working ;)"
        fi
    done
    input=""
done

Save it as "whatyouwant.sh", chmod +x it then run:

./whatyouwant.sh python

or something other than python (idle, whatever). This will ask you if you actually want to exit, if not it rerun python (or the command you gave as parameter).

This will clear all, the screen and all the variables/object/anything you created/imported in python.

In python just type exit() when you want to exit.

If you use vim keybindings in your .inputrc:

set editing-mode vi

It's:

ESC Ctrl-L
Related