This function works in gnome-terminal because, by default, it recognizes ANSI escape sequences. It gives you a CLEAN PROMPT rows_max
distance from the bottom of the terminal, but also precisely from where it was called. Gives you complete control over how much to clear.
def clear(rows=-1, rows_max=None, *, calling_line=True, absolute=None,
store_max=[]):
"""clear(rows=-1, rows_max=None)
clear(0, -1) # Restore auto-determining rows_max
clear(calling_line=False) # Don't clear calling line
clear(absolute=5) # Absolutely clear out to 5 rows up"""
from os import linesep
if rows_max and rows_max != -1:
store_max[:] = [rows_max, False]
elif not store_max or store_max[1] or rows_max == -1 or absolute:
try:
from shutil import get_terminal_size
columns_max, rows_max = get_terminal_size()
except ImportError:
columns_max, rows_max = 80, 24
if absolute is None:
store_max[:] = [rows_max, True]
if store_max:
if rows == -1:
rows = store_max[0]
elif isinstance(rows, float):
rows = round(store_max[0] * rows)
if rows > store_max[0] - 2:
rows = store_max[0] - 2
if absolute is None:
s = ('33[1A' + ' ' * 30 if calling_line else '') + linesep * rows
else:
s = '33[{}A'.format(absolute + 2) + linesep
if absolute > rows_max - 2:
absolute = rows_max - 2
s += (' ' * columns_max + linesep) * absolute + ' ' * columns_max
rows = absolute
print(s + '33[{}A'.format(rows + 1))
Implementation:
clear() # Clear all, TRIES to automatically get terminal height
clear(800, 24) # Clear all, set 24 as terminal (max) height
clear(12) # Clear half of terminal below if 24 is its height
clear(1000) # Clear to terminal height - 2 (24 - 2)
clear(0.5) # float factor 0.0 - 1.0 of terminal height (0.5 * 24 = 12)
clear() # Clear to rows_max - 2 of user given rows_max (24 - 2)
clear(0, 14) # Clear line, reset rows_max to half of 24 (14-2)
clear(0) # Just clear the line
clear(0, -1) # Clear line, restore auto-determining rows_max
clear(calling_line=False) # Clear all, don't clear calling line
clear(absolute=5) # Absolutely clear out to 5 rows up
Parameters: rows
is the number of clear text rows to add between prompt and bottom of terminal, pushing everything up. rows_max
is the height of the terminal (or max clearing height) in text rows, and only needs to be set once, but can be reset at any time. *,
in the third parameter position means all following parameters are keyword only (e.g., clear(absolute=5)). calling_line=True
(default) works better in Interactive mode. calling_line=False
works better for text-based, terminal applications. absolute
was added to try to fix glitchy gap problems in Interactive mode after reducing size of terminal, but can also be used for terminal applications. store_max
is just for secret, «persistent» storage of rows_max
value; don’t explicitly use this parameter. (When an argument is not passed for store_max
, changing the list contents of store_max
changes this parameter’s default value. Hence, persistent storage.)
Portability: Sorry, this doesn’t work in IDLE, but it works >> VERY COOL << in Interactive mode in a terminal (console) that recognizes ANSI escape sequences. I only tested this in Ubuntu 13.10 using Python 3.3 in gnome-terminal. So I can only assume portability is dependant upon Python 3.3 (for the shutil.get_terminal_size()
function for BEST results) and ANSI recognition. The print(...)
function is Python 3. I also tested this with a simple, text-based, terminal Tic Tac Toe game (application).
For use in Interactive mode: First copy and paste the copy(...)
function in Interactive mode and see if it works for you. If so, then put the above function into a file named clear.py . In the terminal start python, with ‘python3’. Enter:
>>> import sys
>>> sys.path
['', '/usr/lib/python3.3', ...
Now drop the clear.py file into one of the path
directories listed so that Python can find it (don’t overwrite any existing files). To easily use from now on:
>>> from clear import clear
>>> clear()
>>> print(clear.__doc__)
clear(rows=-1, rows_max=None)
clear(0, -1) # Restore auto-determining rows_max
clear(calling_line=False) # Don't clear calling line
clear(absolute=5) # Absolutely clear out to 5 rows up
For use in a terminal application: Put the copy(...)
function into a file named clear.py in the same folder with your main.py file. Here is a working abstract (skeleton) example from a Tic Tac Toe game application (run from terminal prompt: python3 tictactoe.py):
from os import linesep
class TicTacToe:
def __init__(self):
# Clear screen, but not calling line
try:
from clear import clear
self.clear = clear
self.clear(calling_line=False)
except ImportError:
self.clear = False
self.rows = 0 # Track printed lines to clear
# ...
self.moves = [' '] * 9
def do_print(self, *text, end=linesep):
text = list(text)
for i, v in enumerate(text[:]):
text[i] = str(v)
text = ' '.join(text)
print(text, end=end)
self.rows += text.count(linesep) + 1
def show_board(self):
if self.clear and self.rows:
self.clear(absolute=self.rows)
self.rows = 0
self.do_print('Tic Tac Toe')
self.do_print(''' | |
{6} | {7} | {8}
| |
-----------
| |
{3} | {4} | {5}
| |
-----------
| |
{0} | {1} | {2}
| |'''.format(*self.moves))
def start(self):
self.show_board()
ok = input("Press <Enter> to continue...")
self.moves = ['O', 'X'] * 4 + ['O']
self.show_board()
ok = input("Press <Enter> to close.")
if __name__ == "__main__":
TicTacToe().start()
Explanation: do_print(...)
on line 19 is a version of print(...)
needed to keep track of how many new lines have been printed (self.rows
). Otherwise, you would have to self.rows += 1
all over the place where print(...)
is called throughout the entire program. So each time the board is redrawn by calling show_board()
the previous board is cleared out and the new board is printed exactly where it should be. Notice self.clear(calling_line=False)
on line 9 basically pushes everything up RELATIVE to the bottom of the terminal, but does not clear the original calling line. In contrast, self.clear(absolute=self.rows)
on line 29 absolutely clears out everything self.rows
distance upward, rather than just pushing everything upward relative to the bottom of the terminal.
Ubuntu users with Python 3.3: Put #!/usr/bin/env python3
on the very first line of the tictactoe.py file. Right click on the tictactoe.py file => Properties => Permissions tab => Check Execute: Allow executing file as program. Double click on the file => Click Run in Terminal button. If an open terminal’s current directory is that of the tictactoe.py file, you can also start the file with ./tictactoe.py
.
This function works in gnome-terminal because, by default, it recognizes ANSI escape sequences. It gives you a CLEAN PROMPT rows_max
distance from the bottom of the terminal, but also precisely from where it was called. Gives you complete control over how much to clear.
def clear(rows=-1, rows_max=None, *, calling_line=True, absolute=None,
store_max=[]):
"""clear(rows=-1, rows_max=None)
clear(0, -1) # Restore auto-determining rows_max
clear(calling_line=False) # Don't clear calling line
clear(absolute=5) # Absolutely clear out to 5 rows up"""
from os import linesep
if rows_max and rows_max != -1:
store_max[:] = [rows_max, False]
elif not store_max or store_max[1] or rows_max == -1 or absolute:
try:
from shutil import get_terminal_size
columns_max, rows_max = get_terminal_size()
except ImportError:
columns_max, rows_max = 80, 24
if absolute is None:
store_max[:] = [rows_max, True]
if store_max:
if rows == -1:
rows = store_max[0]
elif isinstance(rows, float):
rows = round(store_max[0] * rows)
if rows > store_max[0] - 2:
rows = store_max[0] - 2
if absolute is None:
s = ('33[1A' + ' ' * 30 if calling_line else '') + linesep * rows
else:
s = '33[{}A'.format(absolute + 2) + linesep
if absolute > rows_max - 2:
absolute = rows_max - 2
s += (' ' * columns_max + linesep) * absolute + ' ' * columns_max
rows = absolute
print(s + '33[{}A'.format(rows + 1))
Implementation:
clear() # Clear all, TRIES to automatically get terminal height
clear(800, 24) # Clear all, set 24 as terminal (max) height
clear(12) # Clear half of terminal below if 24 is its height
clear(1000) # Clear to terminal height - 2 (24 - 2)
clear(0.5) # float factor 0.0 - 1.0 of terminal height (0.5 * 24 = 12)
clear() # Clear to rows_max - 2 of user given rows_max (24 - 2)
clear(0, 14) # Clear line, reset rows_max to half of 24 (14-2)
clear(0) # Just clear the line
clear(0, -1) # Clear line, restore auto-determining rows_max
clear(calling_line=False) # Clear all, don't clear calling line
clear(absolute=5) # Absolutely clear out to 5 rows up
Parameters: rows
is the number of clear text rows to add between prompt and bottom of terminal, pushing everything up. rows_max
is the height of the terminal (or max clearing height) in text rows, and only needs to be set once, but can be reset at any time. *,
in the third parameter position means all following parameters are keyword only (e.g., clear(absolute=5)). calling_line=True
(default) works better in Interactive mode. calling_line=False
works better for text-based, terminal applications. absolute
was added to try to fix glitchy gap problems in Interactive mode after reducing size of terminal, but can also be used for terminal applications. store_max
is just for secret, «persistent» storage of rows_max
value; don’t explicitly use this parameter. (When an argument is not passed for store_max
, changing the list contents of store_max
changes this parameter’s default value. Hence, persistent storage.)
Portability: Sorry, this doesn’t work in IDLE, but it works >> VERY COOL << in Interactive mode in a terminal (console) that recognizes ANSI escape sequences. I only tested this in Ubuntu 13.10 using Python 3.3 in gnome-terminal. So I can only assume portability is dependant upon Python 3.3 (for the shutil.get_terminal_size()
function for BEST results) and ANSI recognition. The print(...)
function is Python 3. I also tested this with a simple, text-based, terminal Tic Tac Toe game (application).
For use in Interactive mode: First copy and paste the copy(...)
function in Interactive mode and see if it works for you. If so, then put the above function into a file named clear.py . In the terminal start python, with ‘python3’. Enter:
>>> import sys
>>> sys.path
['', '/usr/lib/python3.3', ...
Now drop the clear.py file into one of the path
directories listed so that Python can find it (don’t overwrite any existing files). To easily use from now on:
>>> from clear import clear
>>> clear()
>>> print(clear.__doc__)
clear(rows=-1, rows_max=None)
clear(0, -1) # Restore auto-determining rows_max
clear(calling_line=False) # Don't clear calling line
clear(absolute=5) # Absolutely clear out to 5 rows up
For use in a terminal application: Put the copy(...)
function into a file named clear.py in the same folder with your main.py file. Here is a working abstract (skeleton) example from a Tic Tac Toe game application (run from terminal prompt: python3 tictactoe.py):
from os import linesep
class TicTacToe:
def __init__(self):
# Clear screen, but not calling line
try:
from clear import clear
self.clear = clear
self.clear(calling_line=False)
except ImportError:
self.clear = False
self.rows = 0 # Track printed lines to clear
# ...
self.moves = [' '] * 9
def do_print(self, *text, end=linesep):
text = list(text)
for i, v in enumerate(text[:]):
text[i] = str(v)
text = ' '.join(text)
print(text, end=end)
self.rows += text.count(linesep) + 1
def show_board(self):
if self.clear and self.rows:
self.clear(absolute=self.rows)
self.rows = 0
self.do_print('Tic Tac Toe')
self.do_print(''' | |
{6} | {7} | {8}
| |
-----------
| |
{3} | {4} | {5}
| |
-----------
| |
{0} | {1} | {2}
| |'''.format(*self.moves))
def start(self):
self.show_board()
ok = input("Press <Enter> to continue...")
self.moves = ['O', 'X'] * 4 + ['O']
self.show_board()
ok = input("Press <Enter> to close.")
if __name__ == "__main__":
TicTacToe().start()
Explanation: do_print(...)
on line 19 is a version of print(...)
needed to keep track of how many new lines have been printed (self.rows
). Otherwise, you would have to self.rows += 1
all over the place where print(...)
is called throughout the entire program. So each time the board is redrawn by calling show_board()
the previous board is cleared out and the new board is printed exactly where it should be. Notice self.clear(calling_line=False)
on line 9 basically pushes everything up RELATIVE to the bottom of the terminal, but does not clear the original calling line. In contrast, self.clear(absolute=self.rows)
on line 29 absolutely clears out everything self.rows
distance upward, rather than just pushing everything upward relative to the bottom of the terminal.
Ubuntu users with Python 3.3: Put #!/usr/bin/env python3
on the very first line of the tictactoe.py file. Right click on the tictactoe.py file => Properties => Permissions tab => Check Execute: Allow executing file as program. Double click on the file => Click Run in Terminal button. If an open terminal’s current directory is that of the tictactoe.py file, you can also start the file with ./tictactoe.py
.
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()
Merouane T.
4961 gold badge9 silver badges11 bronze badges
answered Feb 5, 2009 at 21:25
Ryan DuffieldRyan Duffield
18.2k6 gold badges39 silver badges40 bronze badges
18
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()
rubenvb
73.5k33 gold badges185 silver badges325 bronze badges
answered Mar 26, 2009 at 2:42
popcntpopcnt
4,4291 gold badge16 silver badges14 bronze badges
4
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
answered Feb 5, 2009 at 21:22
Kenan BanksKenan Banks
204k34 gold badges152 silver badges171 bronze badges
8
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("33[H33[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:
-
33
stands forESC
(ANSI value 27). -
33[
is a special escape sequence called Control Sequence
Introducer (CSI). -
33[H
command moves the cursor to the top left corner of the screen. -
33[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("33[H33[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("33[H33[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 "33[H33[3J"
or create an alias:
alias cls='printf "33[H33[3J"'
answered May 28, 2018 at 6:54
Denis RasulevDenis Rasulev
3,5864 gold badges35 silver badges44 bronze badges
14
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()
answered Jun 20, 2016 at 14:46
Vlad BezdenVlad Bezden
79.7k23 gold badges247 silver badges178 bronze badges
2
Although this is an older question, I thought I’d contribute something summing up what I think were the best of the other answers and add a wrinkle of my own by suggesting that you put these command(s) into a file and set your PYTHONSTARTUP environment variable to point to it. Since I’m on Windows at the moment, it’s slightly biased that way, but could easily be slanted some other direction.
Here’s some articles I found that describe how to set environment variables on Windows:
When to use sys.path.append and when modifying %PYTHONPATH% is enough
How To Manage Environment Variables in Windows XP
Configuring System and User Environment Variables
How to Use Global System Environment Variables in Windows
BTW, don’t put quotes around the path to the file even if it has spaces in it.
Anyway, here’s my take on the code to put in (or add to your existing) Python startup script:
# ==== pythonstartup.py ====
# add something to clear the screen
class cls(object):
def __repr__(self):
import os
os.system('cls' if os.name == 'nt' else 'clear')
return ''
cls = cls()
# ==== end pythonstartup.py ====
BTW, you can also use @Triptych’s __repr__
trick to change exit()
into just exit
(and ditto for its alias quit
):
class exit(object):
exit = exit # original object
def __repr__(self):
self.exit() # call original
return ''
quit = exit = exit()
Lastly, here’s something else that changes the primary interpreter prompt from >>>
to cwd+>>>
:
class Prompt:
def __str__(self):
import os
return '%s >>> ' % os.getcwd()
import sys
sys.ps1 = Prompt()
del sys
del Prompt
answered Oct 12, 2010 at 18:36
martineaumartineau
117k25 gold badges161 silver badges290 bronze badges
6
Quickest and easiest way without a doubt is Ctrl+L.
This is the same for OS X on the terminal.
answered Aug 28, 2015 at 21:32
Alex KAlex K
8,1599 gold badges39 silver badges56 bronze badges
2
my way of doing this is to write a function like so:
import os
import subprocess
def clear():
if os.name in ('nt','dos'):
subprocess.call("cls")
elif os.name in ('linux','osx','posix'):
subprocess.call("clear")
else:
print("n") * 120
then call clear()
to clear the screen.
this works on windows, osx, linux, bsd… all OSes.
answered Jun 3, 2015 at 11:44
4
The perfect cls, also compatible with Python2 (in .pythonrc file):
from __future__ import print_function
cls = lambda: print("33c", end='')
and can be called from the terminal in this way:
cls()
Or directly:
print("33c", end='')
33[H33[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("33[H33[J", end="")
, only the screen lines inserted after pressing «Ctrl + L» will be deleted.
33c
clears everything.
x1bc
may not give the same result as 33c
as the hex escape is not clearly length limited.
answered Dec 17, 2020 at 15:29
8
I’m not sure if Windows’ «shell» supports this, but on Linux:
print "33[2J"
https://en.wikipedia.org/wiki/ANSI_escape_code#CSI_codes
In my opinion calling cls
with os
is a bad idea generally. Imagine if I manage to change the cls or clear command on your system, and you run your script as admin or root.
BuZz
15.6k29 gold badges85 silver badges140 bronze badges
answered Jun 28, 2015 at 20:31
1
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()
answered Jun 26, 2018 at 12:51
PittoPitto
8,0033 gold badges41 silver badges50 bronze badges
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.
answered Apr 17, 2009 at 4:58
AmolAmol
852 silver badges4 bronze badges
3
Here’s the definitive solution that merges all other answers. Features:
- You can copy-paste the code into your shell or script.
-
You can use it as you like:
>>> clear() >>> -clear >>> clear # <- but this will only work on a shell
-
You can import it as a module:
>>> from clear import clear >>> -clear
-
You can call it as a script:
$ python clear.py
-
It is truly multiplatform; if it can’t recognize your system
(ce
,nt
,dos
orposix
) it will fall back to printing blank lines.
You can download the [full] file here: https://gist.github.com/3130325
Or if you are just looking for the code:
class clear:
def __call__(self):
import os
if os.name==('ce','nt','dos'): os.system('cls')
elif os.name=='posix': os.system('clear')
else: print('n'*120)
def __neg__(self): self()
def __repr__(self):
self();return ''
clear=clear()
answered Jul 17, 2012 at 16:38
Alba MendezAlba Mendez
4,3611 gold badge37 silver badges55 bronze badges
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.
AndyG
39.2k8 gold badges106 silver badges140 bronze badges
answered Feb 5, 2009 at 23:03
S.LottS.Lott
380k79 gold badges505 silver badges775 bronze badges
2
If it is on mac, then a simple cmd + k
should do the trick.
answered Jul 26, 2015 at 18:37
0
I’m using MINGW/BASH on Windows XP, SP3.
(stick this in .pythonstartup)
# My ctrl-l already kind of worked, but this might help someone else
# leaves prompt at bottom of the window though…
import readline
readline.parse_and_bind(‘C-l: clear-screen’)
# This works in BASH because I have it in .inputrc as well, but for some
# reason it gets dropped when I go into Python
readline.parse_and_bind(‘C-y: kill-whole-line’)
I couldn’t stand typing ‘exit()’ anymore and was delighted with martineau’s/Triptych’s tricks:
I slightly doctored it though (stuck it in .pythonstartup)
class exxxit():
"""Shortcut for exit() function, use 'x' now"""
quit_now = exit # original object
def __repr__(self):
self.quit_now() # call original
x = exxxit()
Py2.7.1>help(x)
Help on instance of exxxit in module __main__:
class exxxit
| Shortcut for exit() function, use 'x' now
|
| Methods defined here:
|
| __repr__(self)
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| quit_now = Use exit() or Ctrl-Z plus Return to exit
answered Nov 8, 2011 at 18:56
AAAfarmclubAAAfarmclub
2,0821 gold badge18 silver badges13 bronze badges
The OS command clear
in Linux and cls
in Windows outputs a «magic string» which you can just print. To get the string, execute the command with popen and save it in a variable for later use:
from os import popen
with popen('clear') as f:
clear = f.read()
print clear
On my machine the string is 'x1b[Hx1b[2J'
.
answered Dec 11, 2011 at 11:19
larsrlarsr
5,41618 silver badges38 bronze badges
3
I’m new to python (really really new) and in one of the books I’m reading to get acquainted with the language they teach how to create this little function to clear the console of the visible backlog and past commands and prints:
Open shell / Create new document / Create function as follows:
def clear():
print('n' * 50)
Save it inside the lib folder in you python directory (mine is C:Python33Lib)
Next time you nedd to clear your console just call the function with:
clear()
that’s it.
PS: you can name you function anyway you want. Iv’ seen people using «wiper» «wipe» and variations.
Kirk
16.1k20 gold badges80 silver badges112 bronze badges
answered Mar 25, 2013 at 19:41
>>> ' '*80*25
UPDATE: 80×25 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()
answered Mar 17, 2012 at 17:08
anatoly techtonikanatoly techtonik
19.4k9 gold badges124 silver badges138 bronze badges
3
just use this..
print 'n'*1000
answered May 19, 2014 at 6:15
user1474157user1474157
1,2692 gold badges10 silver badges12 bronze badges
0
Here are two nice ways of doing that:
1.
import os
# Clear Windows command prompt.
if (os.name in ('ce', 'nt', 'dos')):
os.system('cls')
# Clear the Linux terminal.
elif ('posix' in os.name):
os.system('clear')
2.
import os
def clear():
if os.name == 'posix':
os.system('clear')
elif os.name in ('ce', 'nt', 'dos'):
os.system('cls')
clear()
James Jithin
9,9655 gold badges36 silver badges51 bronze badges
answered Sep 1, 2011 at 2:13
userenduserend
1,7011 gold badge13 silver badges10 bronze badges
3
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 screenwipe()
wipes entire terminal buffer
answered Dec 20, 2019 at 4:42
Victoria StuartVictoria Stuart
4,3762 gold badges41 silver badges36 bronze badges
This should be cross platform, and also uses the preferred subprocess.call
instead of os.system
as per the os.system
docs. Should work in Python >= 2.4.
import subprocess
import os
if os.name == 'nt':
def clearscreen():
subprocess.call("cls", shell=True)
return
else:
def clearscreen():
subprocess.call("clear", shell=True)
return
answered Mar 20, 2011 at 14:51
AcornAcorn
48k26 gold badges129 silver badges172 bronze badges
How about this for a clear
- os.system('cls')
That is about as short as could be!
Bo Persson
89.7k31 gold badges144 silver badges201 bronze badges
answered Nov 2, 2011 at 21:48
2
OK, so this is a much less technical answer, but I’m using the Python plugin for Notepad++ and it turns out you can just clear the console manually by right-clicking on it and clicking «clear». Hope this helps someone out there!
answered Jul 8, 2013 at 21:24
I found the simplest way is just to close the window and run a module/script to reopen the shell.
answered Sep 17, 2013 at 10:00
I am using Spyder (Python 2.7) and to clean the interpreter console I use either
%clear
that forces the command line to go to the top and I will not see the previous old commands.
or I click «option» on the Console environment and select «Restart kernel» that removes everything.
answered Apr 8, 2015 at 16:35
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.
tripleee
170k31 gold badges261 silver badges305 bronze badges
answered Feb 5, 2009 at 23:51
Andrea AmbuAndrea Ambu
37.5k14 gold badges53 silver badges77 bronze badges
Use clear()
from replit:
from replit import clear
clear()
answered Jan 21 at 20:45
JAdelJAdel
1,1905 silver badges20 bronze badges
Иногда, работая с оболочкой Python, мы получали случайный вывод или писали ненужные операторы, и мы хотим очистить экран по какой-то причине.
Как очистить экран оболочки в Python? Для очистки терминала (окна терминала) используются команды «cls» и «clear». Если вы используете оболочку в IDLE, на нее такие команды не повлияют. К сожалению, в IDLE нет возможности очистить экран. Лучшее, что вы могли сделать, – это прокрутить экран вниз на множество строк.
Например –
print("/n" * 100)
Хотя вы можете поместить это в функцию:
def cls(): print("/n" * 100)
А затем при необходимости вызовите его как функцию cls(). Это очистит консоль; все предыдущие команды исчезнут, и экран начнется с самого начала.
Если вы используете Linux, то –
Import os # Type os.system('clear')
Если вы используете Windows-
Import os #Type os.system('CLS')
Мы также можем сделать это с помощью скрипта Python. Рассмотрим следующий пример.
Пример –
# import os module from os import system, name # sleep module to display output for some time period from time import sleep # define the clear function def clear(): # for windows if name == 'nt': _ = system('cls') # for mac and linux(here, os.name is 'posix') else: _ = system('clear') # print out some text print('Hellon'*10) # sleep time 2 seconds after printing output sleep(5) # now call function we defined above clear()
Примечание. Используется переменная подчеркивания, потому что оболочка Python всегда сохраняет свой последний вывод в подчеркивании.
Изучаю Python вместе с вами, читаю, собираю и записываю информацию опытных программистов.
While working on the Python terminal (not a console)/interactive shell, some errors occur in the output. So, we have to clean the screen by pressing Control (Ctrl) and L keys simultaneously.
However, sometimes there are situations when the output has to be formatted properly to eliminate issues.
That’s why clearing the screen is based on the amount of output. In this situation, some commands need to be inserted in Python’s script to clear the screen as and when required.
So in this article, we will consider every possible way to clear the screen in Python without having any trouble or errors.
How to Clear Screen in Python Terminal
If you are working on a terminal, then use commands «cls» and «clear» to clear the terminal like this:
For Windows Users
If you are a Windows user and want to clear the screen in Python, you can easily do it using the "cls" command.
>cls
This command will instantly clear the screen, as you can see in the below image:
For Linux Users
Linux also has a command to clear screen in Python easily, so use the following command to do it:
$ clear
Remember there is no specific function, built-in keywords, etc., available to clear the screen. That’s why users need to clear the screen according to them.
Clear Screen in Python Using Functions
Now let’s consider the functions we can use for clearing the screen in Python and remember that you can use these functions in both Windows and Linux.
Using click library
In this method, you can use click library to create a function, and it can work on both Windows and Linux.
Code:
# Python program to clear screen using click.clear() function
# Import click library
import click
def clrscr():
# Clear screen using click.clear() function
click.clear()
print("Screen Cleared")
clrscr()
Output:
Screen Cleared
Code Explanation:
In the above example, we are using click.clear() function from click library to clear screen.
This function works in Windows, Linux, and Mac operating systems.
Using n (Newline character)
The whole way of not clearing the screen is as different as the answer is different. To remove any further error of the line, the user does not need to run the external process completely so that the screen can be cleared.
To clear the screen, you have to print new numbers which are higher than the height and can print something like this (» n» * 10)
Code:
# Python program to clear the screen using n
# ‘n’ is a newline character
def clrscr():
# Print ‘n’ 10 times
print ("n" * 10)
print("Screen Cleared")
clrscr()
Output:
Screen Cleared
Code Explanation:
In the above example, we need to clear a few lined of the screen so we use “n” with print, this will add a newline character and clear x number of lines.
Clear screen program by using os.system method
There are many OS platforms like Windows, Linux, and macOS, so we need different commands to clear the screen. So as you can see in the below syntax, we have used the ‘_’ variable for holding the value of the last expression in the interpreter.
Now we will describe the os.system method to clear the screen in Python without having any troubles. As you can see in the below syntax, we have used the os.system command because It is a string that tells which command needs to be executed.
Code:
# Python program to clear the screen using os.system
# Import os module
import os
def clrscr():
# Check if Operating System is Mac and Linux or Windows
if os.name == 'posix':
_ = os.system('clear')
else:
# Else Operating System is Windows (os.name = nt)
_ = os.system('cls')
print("Screen Cleared")
clrscr()
Output
Screen Cleared
Code Explanation:
We got «Screen Cleared» as we have printed it using the above syntax in the output.
In the above example first, we are checking if the operating system is Linux or not by checking the value of os.name method.
If the Operating system is Linux or Mac the value of os.name will be ”posix”.
And if the value of os.name is posix then we will run the function os.system('clear') or else we will run function os.system('cls').
Example 2
# Python program to clear screen
# This function is applicable for all operating system like Windows, Linux, and OS-X
# Import Library platform and os
import platform
import os
def clr_scr():
# Check if the platform is Windows or linux
# If Platform is Windows then run command os.system(‘cls’) else os.system(‘clear’)
if(platform.system().lower()=="windows"):
cmdtorun='cls'
else:
cmdtorun='clear'
os.system(cmdtorun)
clr_scr()
Code Explanation:
In the above example first, we check if the platform is Windows or Linux by using platform.system() function.
If the platform is “Windows” then we store the value of a command in the variable “cmdtorun”.
And at the end of the function, we are run the function os.system(cmdtorun) with the variable “cmdtorun”.
Using Subprocess Library
In this example, we have used the subprocess() function to execute an action for clearing the screen in output.
Input:
# Python program to clear the screen using subprocess.call() function
# Import subprocess library
import subprocess
def clrscr():
cls = subprocess.call('cls',shell=True)
print("Screen Cleared")
clrscr()
Output:
Screen Cleared
Conclusion
So this is how you can easily clear the screen in Python using functions or commands in the Syntax. As we have mentioned earlier,
There are many methods to clear the screen in Python without getting any errors. But, in our opinion, a clear screen using a click library is the easiest because it works with both the operating systems Unix, Windows, and macOS. And it doesn’t need checking the OS.
Overview
Python os module is imported to clear the console screen in any operating system. The system() method of the os module with the string cls or clear as a parameter is used to clear the screen in windows and macOS/Linux, respectively.
Scope
- This article will teach us how to clear the console screen in different operating systems.
- We will use the os module and its system() method.
- We will learn about clear and cls commands and how to use them as a string parameter to the system() method.
Introduction to Python Clear Screen
Suppose there is a case where you have given the information of 3 students, and you have to print their details in a way like first there will be information of student 1, then after some time information of student 2 will be displayed and then finally the information of student 3 will be displayed. So, in that case, we will have to clear the python console each time after displaying information about each student.
Image Explanation of the above Example
In an interactive shell/terminal, to clear the python console, we can use the ctrl+l command, but in most cases, we have to clear the screen while running the python script, so we have to do it programmatically.
We can clear screen programmatically, and it helps us to format the output in the way we want. We can also clear the output whenever we want many numbers of times.
How to clear the python console screen?
Clearing the console in python has different methods for different Operating Systems. These are stated below:
- In Windows: For clearing the console in the windows operating system, we will use the system() function from the os module with the ‘cls’ parameter.
Syntax of the system() function: system() function is in the os module, so the os module needs to be imported before using the system() function in Windows.
After importing the os module, the string parameter ‘cls’ is passed inside the system function to clear the screen.
import os os.system('cls')
- In Linux and MacOS: For clearing the console in Linux and Mac operating systems, we will use the system() function from the os module with the ‘clear’ parameter.
Syntax: os module needs to be imported before using the system() function in Linux.
After importing the os module string value parameter ‘clear’ is passed inside the system function to clear the screen.
import os os.system('clear')
- Ctrl+l: This method only works for Linux operating system. In an interactive shell/terminal, we can simply use ctrl+l to clear the screen.
Example of Python Clear Screen
Example 1: Clearing Screen in Windows Operating System
Let’s look at an example of the clear screen in python to clarify our understanding.
We will use the above-stated system() function for clearing the python console.
First, we will print some Output; then we will wait for 4 seconds using the sleep() function to halt the program for 4 seconds, and after that, we will apply os.system(‘cls’) to clear the screen.
Code:
import os from time import sleep # Printing Some Text print("Hello, Welcome to Scaler!!") print("Screen will now be cleared in 4 Seconds") # Waiting for 4 seconds to clear the screen sleep(4) # Clearing the Screen os.system('cls')
Output:
The output window will print the given text first, then the program will sleep for 4 seconds, then the screen will be cleared, and program execution will be stopped.
Example 2: Clearing the screen, then printing some more information in Windows Operating System.
First we will print some Output, then we will wait for 1 second using the sleep() function, and after that, we will apply os.system(‘cls’) to clear the screen.
After that, we will print some more information.
Code:
import os from time import sleep # Printing Some Text print("Name: ABC") print("Roll No: 1") print("Marks: 91") # Waiting for 1 second to clear the screen sleep(1) # Clearing the Screen os.system('cls') # Printing Some Text print("Name: DEF") print("Roll No: 2") print("Marks: 81") # Waiting for 1 second to clear the screen sleep(1) # Clearing the Screen os.system('cls') # Printing Some Text print("Name: GHI") print("Roll No: 3") print("Marks: 93") sleep(1)
Output:
The output window will print the first information, then the program will sleep for 1 second, and the screen will be cleared, and then it will print the second information. Again the program will sleep for 1 second, and at last, the program will be stopped after printing the final batch of information.
Example 3: Clearing Screen in Linux Operating System
We will use the above-stated system() method for clearing the python console.
First, we will print some Output; then we will wait for 5 seconds using the sleep() function, and after that, we will apply os.system(‘clear’) to clear the screen.
Code:
import os from time import sleep # Printing Some Text print(1) print(2) print(3) print(4) print(5) print("Screen will now be cleared in 5 Seconds") # Waiting for 5 seconds to clear the screen sleep(5) # Clearing the Screen os.system('clear')
Output:
1 2 3 4 5 The screen will now be cleared in 5 Seconds
- After 5 seconds, the screen is cleared.
The output window will print the given text first, then the program will sleep for 5 seconds, then the screen will be cleared, and program execution will be stopped.
Example 4: What if we don’t know what OS we are working on?
There can be a case where we must first determine what OS we are working on. So, we will first determine whether the os is Windows, Linux, or Mac.
For Windows, the os name is «nt» and for Linux or mac, the OS name is «posix».
So we will check the os name and then accordingly apply the function.
Code:
import os from time import sleep # Printing the os name print("os name is :", os.name) # Waiting for 2 seconds to clear the screen sleep(2) # Clearing the Screen # posix is os name for Linux or mac if(os.name == 'posix'): os.system('clear') # else screen will be cleared for windows else: os.system('cls')
Output:
For this case, the os name is nt, so windows console will be cleared after 2 seconds of program sleep, and then it will be terminated.
Conclusion
Now that we have seen various examples of how to clear the screen in python let us note down a few points.
- Clearing Screen can be done programmatically, and also it helps us to format the output the way we want.
- For clearing the console in the windows operating system, we will use the system() method from the os module with the ‘cls’ parameter.
- For clearing the console in Linux operating system, we will use the system() method from the os module with the ‘clear’ parameter.
- For windows, the os name is nt, and for Linux, it is posix, so we can also first determine the os and then clear the screen.
Read More
1- What is clear() in Python?
2 — How to install python in linux?
We all must have experienced one common thing while working in any programming language which is messy code and output. It rarely happens that we get the desired output in one go, so there are many hits and trials before that. But it is difficult to work on messy code and outputs so, we need a clear screen. If you have ever worked on c++ the function that helps us to achieve this goal is clrscr().
If we are working on an interactive shell, we can quickly clear the output by simply pressing ‘Ctrl + L.’ But when we are working on IDLE, command prompt, Linux Terminal in a running shell, we need to make our own functions to do so. So, let’s learn how to clear a python shell.
If we are working in a REPL terminal, to clear the output, we can make a function using the os module. An os module helps us to interact with our systems. A REPL terminal also known as read–eval–print loop terminal can be windows command prompt, your Linux terminal, or anaconda prompt. So, let us learn how to make a function to clear the python shell.
How to Clear Python Shell in Windows Command Prompt or Anaconda Prompt?
To clear screen in these terminals, we have first to import the os module using the code – import os.
Code-
import os def clear_screen(): os.system('cls') for i in range(10): print(i) clear_screen()
Output-
Here, instead of importing only the os module, we can import the system submodule with it and use the system function directly.
from os import system system("cls")
How to Clear Python Shell in RedHat/ Ubuntu/ Centos (Linux)?
In Linux to clear the screen we cannot use the above function, so let us know how to clear the python shell.
import os def clear_screen(): os.system('clear') for i in range(10): print(i) clear_screen()
Output-
Note- I am using RedHat version-8. The procedure of starting a python shell inside your terminal may vary from mine.
How to clear Shell in IDLE?
IDLE or (Integrated Development and Learning Environment) is an interactive shell where we can code or write programs in python. There is no such built-in function or way to clear the python shell, but we have a trick by which we achieve our goal.
We cannot use the functions that we used to clear the screen in the windows command prompt in IDLE.
Let’s see how we can do this –
def clear(): print("n"*47) for i in range(20): print(i) clear()
Output-
In the video above, we can clearly see that our function is just moving the prompt 47 lines down and if we scroll up, we can see the previously written code.
Must Read
- How to Convert String to Lowercase in
- How to Calculate Square Root
- User Input | Input () Function | Keyboard Input
- Best Book to Learn Python
Conclusion
We have learned how to clear python shell in the most effective way and most of the operating systems. We have also learned the trick to clear the screen when we do not have any built-in function for it.
Improve Article
Save Article
Improve Article
Save Article
Most of the time, while working with Python interactive shell/terminal (not a console), we end up with a messy output and want to clear the screen for some reason. In an interactive shell/terminal, we can simply use
ctrl+l
But, what if we want to clear the screen while running a python script? Unfortunately, there’s no built-in keyword or function/method to clear the screen. So, we do it on our own.
Clearing Screen in windows Operating System
Method 1: Clear screen in Python using cls
You can simply “cls” to clear the screen in windows.
Python3
import
os
os.system(
'cls'
)
Example 2: Clear screen in Python using clear
You can also only “import os” instead of “from os import system” but with that, you have to change system(‘clear’) to os.system(‘clear’).
Python3
from
os
import
system, name
from
time
import
sleep
def
clear():
if
name
=
=
'nt'
:
_
=
system(
'cls'
)
else
:
_
=
system(
'clear'
)
print
(
'hello geeksn'
*
10
)
sleep(
2
)
clear()
Example 3: Clear screen in Python using call
Another way to accomplish this is using the subprocess module.
Python3
from
subprocess
import
call
from
time
import
sleep
def
clear():
_
=
call(
'clear'
if
os.name
=
=
'posix'
else
'cls'
)
print
(
'hello geeksn'
*
10
)
sleep(
2
)
clear()
Clearing Screen in Linux Operating System
In this example, we used the time module and os module to clear the screen in Linux os.
Python3
import
os
from
time
import
sleep
print
(
"a"
)
print
(
"b"
)
print
(
"c"
)
print
(
"d"
)
print
(
"e"
)
print
(
"Screen will now be cleared in 5 Seconds"
)
sleep(
5
)
os.system(
'clear'
)

This tutorial helps How to Clear Console in Python. There is a number of ways to clear the console based on the operating system. You can also clear the interpreter programmatically.
We’ll use os library, which is a built-in library that comes with Python3 installations.
Import the os module and use its os.system()
function to wipe the console in Python.
Let’s import os module:
import os
Linux system
We’ll use the os.system('clear')
command to clear the console.
The Sample code:
import os def clear_console(): os.system('clear') clear_console()
The screen will be cleared if the above command is entered into your console.
Windows system
For the Windows system, We’ll use the os.system('cls') command to clear the
console.
The Sample code:
import os def clear_console(): os.system('cls') clear_console()
Run the above command in your terminal to clear the screen.
Lambda Function To Clear Console in Python
You can also use the lambda function to clear the python console.
import os def clear_console(): return os.system('clear') clear_console()
The screen will be cleared if the above code will run.
Do you use the Python interpreter console for practicing Python code?
You might have seen, there is no direct way or command to clear Python interpreter console.
No worries. There is indirect way of doing this. Let’s see.
You can clear the Python interpreter console screen using a system call.
System calls to clear the console:
- For the window system,
cls
clear the console. - For the Linux system,
clear
command works.
We can run these system calls through the Python to clear screen. It’s simple.
To call the system calls through the Python console, we need the os
library to be imported. This os
library comes inbuilt with python installation. There is no need to explicitly install it.
Watch this video where I have demonstrated how you can clear the Python shell interpreter console.
Command to clear Python Interpreter Console on Window
Using Python Definition:
import os def clear(): os.system('cls') #on Windows System clear()
If you know the basic Python syntax, this code is self explanatory.
Using Lambda Function:
import os clear = lambda: os.system('cls') #on Windows System clear()
Command to clear Python Interpreter Console on Linux:
Using Python Definition:
import os def clear(): os.system('clear') #on Linux System clear()
Using Lambda Function:
import os clear = lambda: os.system('clear') #on Linux System clear()
Don’t Just Copy Paste the Code:
Why am I saying that?
If you copy-paste the code, I am pretty sure you will forget this code and then tomorrow again you will do a Google Search.
The best way is to understand the code written above. It is pretty simple to remember and write code if you know how it has implemented.
What is Lambda Function here?
Above code is all about lambda function.
The “lambda” keyword in Python is used to define anonymous functions. And these functions are also called as lambda functions.
Learn more about lambda function. You can write many such codes with no more hustle. It is extremely useful.
These commands are tested on Python 3.4 version. It will work for both Python 2.x and 3.x versions.
What’s Next?
You can run a Python program without using the Python interpreter console. Install free text editor for your system (Linux/Windows/Mac). And now you can run the Python program from Windows’s command prompt or Linux’s terminal.
I am a Python developer. I usually keep Python interpreter console opened. Sometimes test command runs over it and creates cluttered print output on python console. These backlog print command needs to be cleared. So use this trick to clear screen in Python.
Related Articles:
- 45+ Interesting Python Project Ideas
- 60+ Interview Coding Questions
Hope you find this quick commands and guide useful for your Python learning. Is there anything I can help you with? Feel free to write in the comment section below.
Happy Pythoning!
Aniruddha Chaudhari
I am complete Python Nut, love Linux and vim as an editor. I hold a Master of Computer Science from NIT Trichy. I dabble in C/C++, Java too. I keep sharing my coding knowledge and my own experience on CSEstack.org portal.
Your name can also be listed here. Got a tip? Submit it here to become an CSEstack author.