How to clear the interpreter console?

782,159

Solution 1

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()

Solution 2

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()

Solution 3

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

Solution 4

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"'

Solution 5

You have number of ways doing it on Windows:

1. Using Keyboard shortcut:

Press CTRL + L

2. Using system invoke method:

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

3. Using new line print 100 times:

cls = lambda: print('\n'*100)
cls()
Share:
782,159
Sami Ahmed Siddiqui
Author by

Sami Ahmed Siddiqui

Updated on July 08, 2022

Comments

  • Sami Ahmed Siddiqui
    Sami Ahmed Siddiqui almost 2 years

    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.

  • Sami Ahmed Siddiqui
    Sami Ahmed Siddiqui over 15 years
    Haha, that's pretty funny. Not exactly what I was looking for, but nice try.
  • Andrea Ambu
    Andrea Ambu over 15 years
    how do you do that on idle? Just close and reopen?
  • Akbar ibrahim
    Akbar ibrahim over 15 years
    Define it in a regular function instead of lambda should not show '0' as the return value will be None.
  • Ryan Duffield
    Ryan Duffield over 15 years
    You could get fancy and use the subprocess module (Popen?), and redirect stdout to subprocess.PIPE if you wanted to totally suppress the output, I think.
  • user1066101
    user1066101 almost 15 years
    What's wrong with using def? Why use a lambda when a def is clearer?
  • ridgerunner
    ridgerunner about 13 years
    No, F6 does not reset the Idle console, however CTRL+F6 does. Unfortunately this does not clear the screen. D'oh! (Python Win32 Idle versions 2.6.2, 2.7.1, 3.2).
  • pythonbeginer
    pythonbeginer almost 13 years
    @Triptych: c = "\n" * 100 usefull, +1 for it. A small comment it clears and brings to the bottom of the shell, i prefer to start from the shell top.
  • Alejandro González
    Alejandro González over 12 years
    I'd name the instance of the class Cls to be cls. cls = Cls()
  • martineau
    martineau over 12 years
    Except that pollutes the initial namespace with two things instead of one...twice as much.
  • Alba Mendez
    Alba Mendez almost 12 years
    Or, if your terminal emulator interprets ANSI, better do: "\x1B[H\x1B[J"
  • Alba Mendez
    Alba Mendez almost 12 years
    If os.name is none of these, why not fall back to printing empty lines?
  • Alba Mendez
    Alba Mendez almost 12 years
    1) That magic string is an ANSI sequence. \x1b[H means "move the cursor to the top-left corner", \x1b[2J means "clear all the screen". 2) In windows, ANSI is not recognized so probably there isn't any magic string.
  • Alba Mendez
    Alba Mendez almost 12 years
    yes, but not multiplatform and you have to retype it every time you want to clear the screen.
  • Alba Mendez
    Alba Mendez almost 12 years
    That rule is there to avoid simply posting code. It tries to make people explain his answer, not just giving code.
  • Alba Mendez
    Alba Mendez almost 12 years
    @Amol I've used yours and others' techniques in my solution. You can do class cls and then cls=cls().
  • aramis
    aramis almost 12 years
    It's not a good answer anyway - it's just printing a string of 80*25 spaces... which only works if the console is 2000 characters or smaller (such as 80x25, or 100x20... but the console often winds up 120x50 on my machine.
  • anatoly techtonik
    anatoly techtonik almost 12 years
    Use pypi.python.org/pypi/pager getwidth/getheight to detect console parameters.
  • Torxed
    Torxed over 11 years
    Great way of going about things, Combine this with the lambda suggestion above to save a row of code, handy as hell! Thank you! :)
  • Kenan Banks
    Kenan Banks over 11 years
    This is probably the best answer - a combination of techniques from other answers. PYTHONSTARTUP + repr + os.system('cls'). Very nice.
  • martineau
    martineau over 11 years
    @Triptych: One interesting side-effect of using __repr__ and/or __str__ this way is that if you type >>> vars() at the interpreter console, it will execute all the commands thusly defined. On my system, for example, it cleared the screen and then exited the console. Took me a while to figure out what the heck was going on....
  • Kenan Banks
    Kenan Banks over 11 years
    interesting. I see this problem also applies to locals() and globals(). A simple decorator around these functions that deletes the name and reassigns it after function invocation is a possible solution...
  • martineau
    martineau over 11 years
    @Triptych: The decorator idea doesn't seem to work, at least with my own attempts. Coming up with an viable alternative is proving to surprising difficult.
  • Kenan Banks
    Kenan Banks over 11 years
    I have a candidate solution that simply munges the result of vars() globals() and locals() calls temporarily: gist.github.com/4172781
  • enpenax
    enpenax about 11 years
    @Akbaribrahim as None will not be printed try this: clear = lambda: os.system('cls') or None
  • enpenax
    enpenax about 11 years
    @Akbaribrahim Sorry this was meant for @technomalogical!
  • Lou
    Lou almost 11 years
    Is there a way to do this that clears the whole console, including the C:/Python> line or whatever an individual might have it set to?
  • iChux
    iChux over 10 years
    If it's Jython then I want you to know that os.name = 'java'
  • martineau
    martineau over 10 years
    @Triptych: Your candidate solution won't work for something like a vars() call which is context sensitive because it executes the the built-in one in a different context (inside that of the dynamic function g()). It also has the key 'clear' hardcoded into it which wouldn't apply to vars, locals, etc. (or even cls for that matter).
  • Savitoj Cheema
    Savitoj Cheema almost 9 years
    How to make this persist over instances of python interpreter? thanks in advance.
  • rsanden
    rsanden almost 9 years
    You might mean os.name in ('linux','osx'), and might also want to add 'posix' as well.
  • MartinUbuntu
    MartinUbuntu almost 9 years
    @rsanden 'linux' and 'osx' covers pretty much all the OS's people ACTUALLY use.
  • rsanden
    rsanden almost 9 years
    I am running Ubuntu 15.04, and os.name == 'posix' in both python 2.7.9 and 3.4.3
  • MartinUbuntu
    MartinUbuntu almost 9 years
    @rsanden added posix.
  • wittrup
    wittrup over 8 years
    @XavitojCheema See this: stackoverflow.com/questions/5837259/…
  • Chris22
    Chris22 over 8 years
    I tried this solution using upper or lowercase "L" with the ctrl key on windows 8.1. It doesn't work for me. I just open and close the shell window to clear it.
  • Andrew Franklin
    Andrew Franklin about 8 years
    On OS X, Ctrl+L will pad the terminal until the display is clear. You can still scroll up to see the history. Use Cmd+K to clear the display and printout history. A more complete list of OS X terminal hotkeys
  • jsbueno
    jsbueno about 8 years
    Despite people laughing, printing a lot of newlines is exactly what the external processes clear and cls do. This is the way to do it. (just a print, or a function with the print call, not assigining to a "clear" string, of course)
  • James Grey
    James Grey almost 8 years
    import os os.system('cls')
  • Luke
    Luke over 7 years
    All these ways are pretty... naff. cls will only work on windows and make your program hard to be cross platform, printing 100 newlines is just... eww? And a keyboard shortcut is not used in the program.
  • Luke
    Luke over 7 years
    Looks good, does this mean that the program can become cross platform?
  • mja
    mja over 7 years
    or import os; cls = os.system("tput reset"); cls()
  • DenMark
    DenMark almost 7 years
    Cool! Also, for python3 print('\x1b[H\x1b[2J', end=''); can help avoid the new line in front.
  • Kellen Stuart
    Kellen Stuart over 6 years
    Funny, at that point it is quicker to exit() then cls then python again
  • Max
    Max over 6 years
    with Python 3.6 they must've updated from cls to clear, because my lambda function only works if I replace with the later string
  • Mr. Nun.
    Mr. Nun. over 6 years
    os.system is deprecated. use subprocess.call instead
  • Anonymous
    Anonymous about 6 years
    It's nice, although you can just scroll up to see the input.
  • kfrncs
    kfrncs almost 6 years
    @KolobCanyon Ctrl + D, Ctrl + L, python. even quicker if you set python to just py or pyt
  • spectras
    spectras almost 6 years
    @jsbueno no it's not. Well maybe on windows (though I doubt it, it has APIs to clear the console). On all other systems, clear outputs a directive that clears the screen. Without trashing the scrollback buffer. On my system, it outputs this control sequence: \33[3J\33[H\33[2J. That is: [erase scrollback] [reset cursor position] [erase screen]. The [erase scrollback] can be omitted using clear -x.
  • Brian Stork
    Brian Stork over 5 years
    I think the desire is to clear off the text AND put the cursor at the top, left, like a clean, new terminal. Your solution does not do that. Your solution keeps existing text in the scroll buffer. I think the desire is to completely remove the scroll buffer.
  • DevPlayer
    DevPlayer over 5 years
    The magic string worked on Microsoft Windows 10 console with Python 3.6 for me. I plussed for the string sequence not the use of with open.
  • Jonathan
    Jonathan about 5 years
    TERM environment variable not set.
  • Graham G
    Graham G about 4 years
    This has the advantage that it also works in Spyder.
  • silviot
    silviot about 4 years
    I agree cls is not ideal in this case, and an ANSI escape sequence is better. In particular using os to invoke a new process is quite a pricy operation, compared to pushing a few bytes to stdout.
  • Mario Palumbo
    Mario Palumbo over 3 years
    cls = lambda: print("\033c\033[3J", end='') and then cls(), or directly print("\033c\033[3J", end='')
  • Youssof H.
    Youssof H. over 3 years
    May I ask what is this?
  • Denis Rasulev
    Denis Rasulev over 3 years
    @YoussofH., did you ask about Spyder? If so, then here it is: Spyder IDE
  • Youssof H.
    Youssof H. over 3 years
    Oh I wasn't clear. I meant print("\033[H\033[J") how does this method work, what is it its name!?
  • Denis Rasulev
    Denis Rasulev over 3 years
    Ok, here is the explanation: stackoverflow.com/a/55672830/4440387
  • BlueStaggo
    BlueStaggo over 3 years
    cls = lambda: os.system('cls' if os.name=='nt' else 'clear')
  • Ahmad
    Ahmad over 3 years
    This one was really the best solution. Simple and multi-platform.
  • throws_exceptions_at_you
    throws_exceptions_at_you over 3 years
    This is the only real solution to the problem
  • Someone_who_likes_SE
    Someone_who_likes_SE about 3 years
    What about Linux? It throws "cls command not found"
  • TheEagle
    TheEagle about 3 years
    This should be the accepted and most upvote answer - firstly, it's an overkill IMO to import os and run an external command just to get the screen clear, and secondly, it's much faster (this, of course, only matters if you have to do it a zillion times in a row)
  • Debashis
    Debashis almost 3 years
    Control + L works on Mac out of the box. Using python3.
  • Valdas Stonkus
    Valdas Stonkus over 2 years
    It did not worked for me in win 10
  • Denis Rasulev
    Denis Rasulev over 2 years
    @ValdasStonkus, did you enter it at the Python interpreter invitation ('>>>')? I mean this command is so basic and platform independent that it works anywhere... Also, what was error message you got?
  • Minek Po1
    Minek Po1 over 2 years
    I have found this solution to be magnitudes faster
  • Mugabo
    Mugabo over 2 years
    @enpenax thanks for the 'or None' addition. Beautifully elegant solution to a pesky little side effect.
  • not2qubit
    not2qubit over 2 years
    Why are you using lambda here?
  • not2qubit
    not2qubit over 2 years
    Some info on ESC-c: "Triggers a full reset of the terminal to its original state.[20] This may include (if applicable): reset graphic rendition, clear tabulation stops, reset to default font, and more."
  • Mario Palumbo
    Mario Palumbo over 2 years
    @not2qubit It is a quick way to implement a function, this short way is not mandatory, the standard one is also excellent.
  • Mario Palumbo
    Mario Palumbo over 2 years
    \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.
  • not2qubit
    not2qubit over 2 years
    Personally I prefer HEX codes and not OCT, so that ESC = \033 = \x1b.
  • Mario Palumbo
    Mario Palumbo over 2 years
    Minor: "\x1bc" may not give the same result as "\033c" as the hex escape is not clearly length limited.
  • Mario Palumbo
    Mario Palumbo over 2 years
    Ok, I edited the answer for the umpteenth time (hopefully it's the last).
  • tripleee
    tripleee about 2 years
    For completeness, note that this assumes you are connected to a terminal which understands ANSI control codes. There are situations where this isn't true, such as when you are running a pseudo-TTY of some sort, or standard output isn't a terminal at all. Probably at least check for the latter before emitting this, as it tends to generate junk output and new questions on our site.
  • tripleee
    tripleee about 2 years
    (TIL that older versions of Windows also don't support proper ANSI codes.)
  • tripleee
    tripleee about 2 years
    Hex escapes with \x are by definition always two hex digits long. \x1b is perfectly equivalent to \033.
  • Denis Rasulev
    Denis Rasulev about 2 years
    Good point, @tripleee! I would point to this answer, which might be helpful here: stackoverflow.com/a/63913131/4440387
  • Manu mathew
    Manu mathew about 2 years
    Though I agree this is a smart thought, the cursor will still be at the bottom of the screen if you clear the console this way. Most of the time I will be clearing the screen to start typing from the top again.