How to clear the interpreter console?
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 forESC
(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()
Sami Ahmed Siddiqui
Updated on July 08, 2022Comments
-
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 orclear
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 over 15 yearsHaha, that's pretty funny. Not exactly what I was looking for, but nice try.
-
Andrea Ambu over 15 yearshow do you do that on idle? Just close and reopen?
-
Akbar ibrahim over 15 yearsDefine it in a regular function instead of lambda should not show '0' as the return value will be None.
-
Ryan Duffield over 15 yearsYou 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 almost 15 yearsWhat's wrong with using
def
? Why use alambda
when adef
is clearer? -
ridgerunner about 13 yearsNo,
F6
does not reset the Idle console, howeverCTRL+F6
does. Unfortunately this does not clear the screen. D'oh! (Python Win32 Idle versions 2.6.2, 2.7.1, 3.2). -
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 over 12 yearsI'd name the instance of the
class Cls
to becls
.cls = Cls()
-
martineau over 12 yearsExcept that pollutes the initial namespace with two things instead of one...twice as much.
-
Alba Mendez almost 12 yearsOr, if your terminal emulator interprets ANSI, better do:
"\x1B[H\x1B[J"
-
Alba Mendez almost 12 yearsIf os.name is none of these, why not fall back to printing empty lines?
-
Alba Mendez almost 12 years1) 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 almost 12 yearsyes, but not multiplatform and you have to retype it every time you want to clear the screen.
-
Alba Mendez almost 12 yearsThat rule is there to avoid simply posting code. It tries to make people explain his answer, not just giving code.
-
Alba Mendez almost 12 years@Amol I've used yours and others' techniques in my solution. You can do
class cls
and thencls=cls()
. -
aramis almost 12 yearsIt'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 almost 12 yearsUse pypi.python.org/pypi/pager getwidth/getheight to detect console parameters.
-
Torxed over 11 yearsGreat 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 over 11 yearsThis is probably the best answer - a combination of techniques from other answers. PYTHONSTARTUP + repr + os.system('cls'). Very nice.
-
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 over 11 yearsinteresting. I see this problem also applies to
locals()
andglobals()
. A simple decorator around these functions that deletes the name and reassigns it after function invocation is a possible solution... -
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 over 11 yearsI have a candidate solution that simply munges the result of vars() globals() and locals() calls temporarily: gist.github.com/4172781
-
enpenax about 11 years@Akbaribrahim as None will not be printed try this:
clear = lambda: os.system('cls') or None
-
enpenax about 11 years@Akbaribrahim Sorry this was meant for @technomalogical!
-
Lou almost 11 yearsIs 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 over 10 yearsIf it's Jython then I want you to know that os.name = 'java'
-
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 functiong()
). It also has the key'clear'
hardcoded into it which wouldn't apply tovars
,locals
, etc. (or evencls
for that matter). -
Savitoj Cheema almost 9 yearsHow to make this persist over instances of python interpreter? thanks in advance.
-
rsanden almost 9 yearsYou might mean
os.name in ('linux','osx')
, and might also want to add'posix'
as well. -
MartinUbuntu almost 9 years@rsanden 'linux' and 'osx' covers pretty much all the OS's people ACTUALLY use.
-
rsanden almost 9 yearsI am running Ubuntu 15.04, and
os.name == 'posix'
in both python 2.7.9 and 3.4.3 -
MartinUbuntu almost 9 years@rsanden added posix.
-
wittrup over 8 years@XavitojCheema See this: stackoverflow.com/questions/5837259/…
-
Chris22 over 8 yearsI 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 about 8 yearsOn 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 about 8 yearsDespite people laughing, printing a lot of newlines is exactly what the external processes
clear
andcls
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 almost 8 years
import os
os.system('cls')
-
Luke over 7 yearsAll these ways are pretty... naff.
cls
will only work on windows and make your program hard to be cross platform, printing 100newlines
is just... eww? And a keyboard shortcut is not used in the program. -
Luke over 7 yearsLooks good, does this mean that the program can become cross platform?
-
mja over 7 yearsor
import os; cls = os.system("tput reset"); cls()
-
DenMark almost 7 yearsCool! Also, for python3 print('\x1b[H\x1b[2J', end=''); can help avoid the new line in front.
-
Kellen Stuart over 6 yearsFunny, at that point it is quicker to
exit()
thencls
thenpython
again -
Max over 6 yearswith Python 3.6 they must've updated from
cls
toclear
, because my lambda function only works if I replace with the later string -
Mr. Nun. over 6 yearsos.system is deprecated. use subprocess.call instead
-
Anonymous about 6 yearsIt's nice, although you can just scroll up to see the input.
-
kfrncs almost 6 years@KolobCanyon Ctrl + D, Ctrl + L, python. even quicker if you set python to just py or pyt
-
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 usingclear -x
. -
Brian Stork over 5 yearsI 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 over 5 yearsThe 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 about 5 yearsTERM environment variable not set.
-
Graham G about 4 yearsThis has the advantage that it also works in Spyder.
-
silviot about 4 yearsI 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 over 3 years
cls = lambda: print("\033c\033[3J", end='')
and thencls()
, or directlyprint("\033c\033[3J", end='')
-
Youssof H. over 3 yearsMay I ask what is this?
-
Denis Rasulev over 3 years@YoussofH., did you ask about Spyder? If so, then here it is: Spyder IDE
-
Youssof H. over 3 yearsOh I wasn't clear. I meant
print("\033[H\033[J")
how does this method work, what is it its name!? -
Denis Rasulev over 3 yearsOk, here is the explanation: stackoverflow.com/a/55672830/4440387
-
BlueStaggo over 3 years
cls = lambda: os.system('cls' if os.name=='nt' else 'clear')
-
Ahmad over 3 yearsThis one was really the best solution. Simple and multi-platform.
-
throws_exceptions_at_you over 3 yearsThis is the only real solution to the problem
-
Someone_who_likes_SE about 3 years
What about Linux? It throws "cls command not found"
-
TheEagle about 3 yearsThis 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 almost 3 yearsControl + L works on Mac out of the box. Using python3.
-
Valdas Stonkus over 2 yearsIt did not worked for me in win 10
-
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 over 2 yearsI have found this solution to be magnitudes faster
-
Mugabo over 2 years@enpenax thanks for the 'or None' addition. Beautifully elegant solution to a pesky little side effect.
-
not2qubit over 2 yearsWhy are you using lambda here?
-
not2qubit over 2 yearsSome 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 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 over 2 years
\033[H\033[J
only clears the visible screen, exactly the same as theclear
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 pressCtrl+L
and insert more. After executingprint("\033[H\033[J", end="")
, only the screen lines inserted after pressing "Ctrl + L" will be deleted.\033c
clears everything. -
not2qubit over 2 yearsPersonally I prefer HEX codes and not OCT, so that
ESC = \033 = \x1b
. -
Mario Palumbo over 2 yearsMinor: "\x1bc" may not give the same result as "\033c" as the hex escape is not clearly length limited.
-
Mario Palumbo over 2 yearsOk, I edited the answer for the umpteenth time (hopefully it's the last).
-
tripleee about 2 yearsFor 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 about 2 years(TIL that older versions of Windows also don't support proper ANSI codes.)
-
tripleee about 2 yearsHex escapes with
\x
are by definition always two hex digits long.\x1b
is perfectly equivalent to\033
. -
Denis Rasulev about 2 yearsGood point, @tripleee! I would point to this answer, which might be helpful here: stackoverflow.com/a/63913131/4440387
-
Manu mathew about 2 yearsThough 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.