Does any standard "comes with batteries" method exist to clear the terminal screen from a Python script, or do I have to go curses (the libraries, not the words)?
-
I'd check for Windows and use 'cls' and just unconditionally do a `clear` for everything because that would be likely to cover the most cases. See related question [How to clear python interpreter console?](http://stackoverflow.com/questions/517970/how-to-clear-python-interpreter-console). – martineau Jan 26 '11 at 20:30
-
1related: [Python - Clearing the terminal screen more elegantly](http://stackoverflow.com/q/34388390/4279) – jfs Mar 05 '16 at 15:15
-
1Related http://stackoverflow.com/questions/4810537/how-to-clear-the-screen-in-python – tale852150 Jun 12 '16 at 17:11
27 Answers
A simple and cross-platform solution would be to use either the cls
command on Windows, or clear
on Unix systems. Used with os.system
, this makes a nice one-liner:
import os
os.system('cls' if os.name == 'nt' else 'clear')

- 369,085
- 72
- 557
- 602
-
46@allyourcode The code in my answer is *explicitly safe* from injections because there is no user input involved there. All the strings that could be passed to `os.system` are fixed. – poke Mar 26 '16 at 00:10
-
3The code is explicitly wrong, because you run a whole process when all you need is to print out some newlines (which is what both `clear` and `cls` do): `print("\n" * 100) ` – jsbueno Jun 02 '16 at 05:23
-
41@jsbueno I can’t tell about Unix right now, but `cls` on Windows does *not* just print empty lines. It explicitly clears the console buffer, so it is *not* equivalent to printing any amount of whitespace. Also, the code works surprisingly well for something that is “explicitly wrong”. You may dislike it, but that does not make it wrong (not to mention that `cls` on Windows is not a process but a functionality of the console host, e.g. cmd.exe or PowerShell). – poke Jun 02 '16 at 06:36
-
So, that implies that `cls` and `clear` are inherently different - as `clear` is an external process and does not clear the buffer - which makes the solution inconsistent besides inefficient `cls` may be a shell builtin in Windows - but the `system` call will run a new shell nonetheless. "The system function passes command to the command interpreter, which executes the string as an operating-system command. system uses the COMSPEC and PATH environment variables to locate the command-interpreter file CMD.exe. " #https://msdn.microsoft.com/en-us/library/277bwbdz.aspx – jsbueno Jun 02 '16 at 14:49
What about escape sequences?
print(chr(27) + "[2J")

- 40,873
- 40
- 203
- 237

- 19,961
- 13
- 71
- 88
-
1
-
26Note that this is not portable across all terminal types... not that you'll run into too many odd types these days... – Ignacio Vazquez-Abrams Jan 18 '10 at 07:44
-
13This technique brings the cursor down. Try Ctrl+L, the effect is different. I think the script should reset the cursor location to the top of the line. – Peter Feb 19 '13 at 13:15
-
1This comment will clear the screen but not reset the cursor position. I wanted the cursor position reset as well. The [answer](http://stackoverflow.com/questions/2084508/clear-terminal-in-python#2084560) provided by DaveKirby and edited by @tzot was exactly what I was looking for. – Preston Jul 28 '13 at 01:05
-
5
-
5
-
-
2
-
1Hmm it looks like the bash `clear` command is actually doing `print(chr(27) + "[H" + chr(27) + "[J")`. This works for me when I need to do multiple clear screens (after the first, yours won't scroll my terminal for some reason). – scohe001 Mar 19 '18 at 22:43
-
27Sorry guys but I couldn't resist: https://imgs.xkcd.com/comics/real_programmers.png – Pitto Apr 09 '18 at 08:37
-
1
-
1
-
1`print("\033c\033[3J\033[2J\033[0m\033[H")` - Performs a terminal reset, buffer clearance, clear the window, set back to default colours etc... and places prompt at the top. - [source](https://www.unix.com/os-x-apple-/279401-means-clearing-scroll-buffer-osx-terminal.html) – Michael David Woolweaver Jan 28 '21 at 19:39
Why hasn't anyone talked about just simply doing Ctrl+L in Windows or Cmd+L in Mac. Surely the simplest way of clearing screen.

- 2,597
- 1
- 29
- 39

- 2,533
- 2
- 20
- 23
-
1
-
4This is the best answer so far. Also do you know how can i scroll up my python console , because when the screen gets filled I have to write on the last line and it doesn't scroll up. – PG1 Jun 08 '15 at 15:00
-
3I am on Ubuntu and I was using `os.system('clear')` but I think your answer is the simplest way. Upvoted! :) – serenesat Aug 25 '15 at 12:42
-
127@ParagGangil Not the best answer for those that want to _programmatically_ clear the screen. – Eric Wilson Oct 01 '15 at 22:49
-
2
-
2That works at the command line, have you actually tried doing it in Python? – Edward Falk Jul 22 '16 at 07:18
-
10It doesn't work. Just typing ^L in command (Python console in Windows 10) – Alexander Kuzin Feb 07 '17 at 19:45
-
1I m using Ubuntu and tap "ctrl+L" worked to clean terminal screen, but how can i accomplish this programatically, as the question author asked? – Valentoni Apr 19 '17 at 12:22
-
1ctrl+L usually works for all consoles(chrome developer tools console) – Kartik Chauhan Apr 04 '18 at 19:23
-
If this is what the OP was asking the question would be off-topic here and would belong on [Super User](https://superuser.com/) instead. – Charles Duffy Oct 30 '21 at 02:08
As for me, the most elegant variant:
import os
os.system('cls||clear')

- 36,322
- 27
- 84
- 93

- 955
- 6
- 13
-
-
4This is actually a really interesting solution - I didn't realize that that was particularly possible... – SirJames Feb 15 '17 at 13:04
-
2@SirJames, really easy. Windows accept "cls" and ignore other and Unix run function which know, ignore "cls" – Vasiliy Rusin Feb 15 '17 at 20:07
-
Yeah, I'm aware of the functionality that cmd prompt and bash can do... But it just didn't click that I could do that in Python just as easily. – SirJames Feb 17 '17 at 11:52
-
1
For Windows, Mac and Linux, you can use the following code:
import subprocess, platform
if platform.system()=="Windows":
if platform.release() in {"10", "11"}:
subprocess.run("", shell=True) #Needed to fix a bug regarding Windows 10; not sure about Windows 11
print("\033c", end="")
else:
subprocess.run(["cls"])
else: #Linux and Mac
print("\033c", end="")
jamesnotjim tested print("\033c", end="")
for Mac, and I tested it on Linux and Windows (it doesn't work for Windows, hence the other code that calls cls
). I don't remember who it was I first saw use print("\033c")
and/or the printf version: subprocess.run("printf '\033c'", shell=True)
.
rolika pointed out that end=""
will prevent it from printing a new line afterward.
Note that newer versions of Ubuntu will clear the screen just fine (not just scroll down so it seems cleared) with clear
, unlike the older versions.
Note that resetting the terminal with ESC c ("\033c") will make the cursor underlined and blinking. If you don't want that, you can use these codes to change it to another style (tested on GNOME Terminal 3.44.0 using VTE 0.68.0 +BIDI +GNUTLS +ICU +SYSTEMD):
- underscore blinking: "\033[0 q"
- block blinking: "\033[1 q"
- block: "\033[2 q"
- underscore blinking: "\033[3 q"
- underscore: "\033[4 q"
- thin bar blinking: "\033[5 q"
- thin bar: "\033[6 q" (numbers above 6 seem to do this, too)
Also note that you can do any of these things to clear the screen on Linux:
- print("\033c", end=""):
- print("\u001bc", end="")
- print("\U0000001bc", end="")
- print("\x1bc", end="")
- subprocess.run(["clear"]) #This doesn't reset the whole terminal
- subprocess.run('echo -ne "\033c"', shell=True)
- subprocess.run('echo -ne "\ec"', shell=True)
- subprocess.run('echo -ne "\u001bc"', shell=True)
- subprocess.run('echo -ne "\U0000001bc"', shell=True)
- subprocess.run('echo -ne "\x1bc"', shell=True)
- subprocess.run("printf '\033c'", shell=True)
- subprocess.run("printf '\ec'", shell=True)
- subprocess.run("printf '\u001bc'", shell=True)
- subprocess.run("printf '\U0000001bc'", shell=True)
- subprocess.run("printf '\x1bc'", shell=True)
I believe the following code is supposed to clear the content that you have to scroll up to see (but it's difficult to use in conjunction with another command without issues):
- print("\033[3J")
This can do the same thing that clear
used to do (so you can scroll up to see what was deleted, except it doesn't raise the cursor to the top):
- print("\033[2J")

- 4,387
- 4
- 34
- 56
-
9This works for me too (using print("\033c"))and I think this is the best solution. No need to import os when comparing against os.system('clear'). It also clears without scrollback. – Ross Jan 14 '15 at 23:06
-
1Just sending the terminal command to clear screen as described here is in fact a great way of doing it. If you want (much) more elaborate terminal stuff, you can use a library such as [blessings](https://github.com/erikrose/blessings) – Fred Mar 02 '16 at 18:02
-
3
-
1@AbyW \033 is the octal number for ESC the escape sequence in ASCII, equivalent to \x1b in hexadecimal.
c is an escape sequence to reset all terminal settings to default. – Kronen Jan 31 '18 at 20:53 -
4
-
1`print("\033c", end="")` worked nicely with OS X (El Capitan, 10.11.6) running Python 3.7.2. The `subprocess.call()` version worked as well, but the `print()` version is simpler and easier to remember. Thanks for the help! – jamesnotjim Jan 23 '19 at 21:04
-
-
Trying this in python 3.7.2 and it does clear the screen. However, when I have more than one page worth of content in the terminal, it only clears all the content available to the current screen. However if you scroll back up, the old content is still there from previous screens. Is there a way to fix this – Razor Storm May 08 '20 at 19:05
-
@AbyW It should be **FF (Form Feed)** of [C0 control codes](https://en.wikipedia.org/wiki/ANSI_escape_code#C0_control_codes). – hata Dec 10 '22 at 07:15
If you are on a Linux/UNIX system then printing the ANSI escape sequence to clear the screen should do the job. You will also want to move cursor to the top of the screen. This will work on any terminal that supports ANSI.
import sys
sys.stderr.write("\x1b[2J\x1b[H")
This will not work on Windows unless ANSI support has been enabled. There may be an equivalent control sequence for Windows, but I do not know.

- 92,761
- 29
- 141
- 204

- 25,806
- 5
- 67
- 84
-
3Since your answer implied that you're using Python 2.x, and since 2.x `print` (without `softspace` tuning and/or `sys.stdout.flush()`) can't *ever* leave the cursor at the top-left corner of the screen, I edited your answer to something that can be used in both Python 2.x and 3.x – tzot Feb 20 '11 at 16:36
-
4For anyone wondering, the string is a series of [ANSI escape codes](http://en.wikipedia.org/wiki/ANSI_escape_code). \x1b[ is a control sequence introducer (hex 0x1B). Code 2J clears the entire screen. Code H sets the cursor position, and without arguments defaults to the top left corner. – Preston Jul 28 '13 at 00:57
-
3Can you explain why are you writing to stderr instead of stdout, please? – Aaron Feb 11 '14 at 23:40
-
I can confirm this works with the Linux programs screen and minicom. – gbmhunter Feb 20 '14 at 22:46
-
1@Aaron My guess would be to prevent the output being buffered. Usually (it might even be in a standard) stderr output is determined to appear imediately. – w4etwetewtwet Apr 07 '14 at 16:21
-
2I can confirm that stderr is buffered on *my* machine running Arch Linux, zsh, and Python3 inside of tmux (over ssh) - requiring me to run `sys.stderr.flush()`. `print()` actually works just as well. – Wayne Werner Nov 06 '14 at 01:04
-
4`import colorama; colorama.init()` makes `"\x1b[2J\x1b[H"` sequence work on Windows too. – jfs Mar 05 '16 at 21:00
-
1Calling `os.system('')` makes this work on windows, no external dependencies needed – mousetail Oct 17 '20 at 09:30
Just use:
print("\033c")
This will clear the terminal window.

- 5,396
- 14
- 39
- 46

- 1,125
- 5
- 19
- 35
-
9also, `print("\033c", end="")` does not inject a newline when clearing console. – GG_Python Nov 02 '19 at 17:26
-
2How does this differ from [this](https://stackoverflow.com/a/23075152/1667423) answer? – user76284 Jun 28 '20 at 02:50
-
1@user76284 it is simpler (also this answer is like two years old :o) – Alex Hawking Jun 28 '20 at 23:14
Came across this some time ago
def clearscreen(numlines=100):
"""Clear the console.
numlines is an optional argument used only as a fall-back.
"""
# Thanks to Steven D'Aprano, http://www.velocityreviews.com/forums
if os.name == "posix":
# Unix/Linux/MacOS/BSD/etc
os.system('clear')
elif os.name in ("nt", "dos", "ce"):
# DOS/Windows
os.system('CLS')
else:
# Fallback for other operating systems.
print('\n' * numlines)
Then just use clearscreen()

- 119
- 1
- 3
You could try to rely on clear but it might not be available on all Linux distributions. On windows use cls as you mentionned.
import subprocess
import platform
def clear():
subprocess.Popen( "cls" if platform.system() == "Windows" else "clear", shell=True)
clear()
Note: It could be considered bad form to take control of the terminal screen. Are you considering using an option? It would probably be better to let the user decide if he want to clear the screen.

- 52,748
- 3
- 38
- 55
-
-
1@TryPyPy My mistake. subprocess is intented to replace os.system, I should be using it instead. OP was right. – Rod Jan 26 '11 at 18:13
-
4I'd use `subprocess.call()` for something as simple as this call though. – ThiefMaster Oct 28 '13 at 16:03
This will be work in Both version Python2 OR Python3
print (u"{}[2J{}[;H".format(chr(27), chr(27)))

- 15,498
- 5
- 79
- 71
-
3`print (u"{}[2J{}[;H".format(chr(27), chr(27)), end="")` for removing the newline. – Emma Labbé Feb 06 '19 at 13:24
So just thought I would throw my two cents in here...
No one has provided a true answer to OP question it seems, everyone either responds with 'NO DONT USE os.system() it's evil!!!' without explanation or provides a solution that relies on printing new lines.
For those that need to clear the terminal screen and scroll back, for whatever reason, you can use the following code:
import os
def clear():
'''
Clears the terminal screen and scroll back to present
the user with a nice clean, new screen. Useful for managing
menu screens in terminal applications.
'''
os.system('cls' if os.name == 'nt' else 'echo -e \\\\033c')
print('A bunch of garbage so we can garble up the screen...')
clear()
# Same effect, less characters...
def clear():
'''
Clears the terminal screen and scroll back to present
the user with a nice clean, new screen. Useful for managing
menu screens in terminal applications.
'''
os.system('cls||echo -e \\\\033c')
This has the OP's desired effect. It does use the os.system() command so if that's evil and someone knows a way of implementing this using subprocess.call() please comment as I would also prefer to use subprocess but am not familiar with it at all.

- 332
- 1
- 2
- 10

- 133
- 1
- 9
-
1This one works for me on Raspberry Pi. Joril's answer does not reset the cursor to the top of screen. – besimple Jan 05 '18 at 09:25
-
You might want to check out: https://stackoverflow.com/questions/18937058/clear-screen-in-shell/20247284#20247284 – Xantium Mar 06 '18 at 14:31
-
1@Simon, your reference is not cross-platform as OP requested but instead targets Darwin devices. Yes `'clear'` works in some nix environments but not all, whereas `'cls'` is windows specific and `'echo -e \\\\033c'` works in all Bash environments – OpticalMagician May 22 '18 at 01:21
-
OK, sorry about that. Admittedly I run on Windows and sometimes Ubuntu, so I don't know much about the different environments. – Xantium May 22 '18 at 07:51
-
`echo -e` is a non-POSIX extension -- it isn't guaranteed to be supported at all, and even when your shell is 100% guaranteed to be bash it's able to be turned off (run `set -o posix; shopt -s xpg_echo`, and then `echo -e` will print `-e` on output). See [the POSIX specification for `echo`](https://pubs.opengroup.org/onlinepubs/9699919799/utilities/echo.html), which explicitly recommends using `printf` instead when you need to print escape sequences. – Charles Duffy Oct 30 '21 at 02:09
A Pure Python solution.
Does not rely on either ANSI, or external commands.
Only your terminal has to have the ability to tell you how many lines are in view.
from shutil import get_terminal_size
print("\n" * get_terminal_size().lines, end='')
Python version >= 3.3.0

- 1,460
- 2
- 13
- 15
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 = ('\033[1A' + ' ' * 30 if calling_line else '') + linesep * rows
else:
s = '\033[{}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 + '\033[{}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
.

- 189
- 2
- 3
In Windows you can use:
>>> import os
>>> clear = lambda: os.system('cls')
>>> clear()

- 235,170
- 19
- 170
- 241
If you wish to clear your terminal when you are using a python shell. Then, you can do the following to clear the screen
import os
os.system('clear')

- 1,687
- 2
- 15
- 24
You could tear through the terminfo database, but the functions for doing so are in curses
anyway.

- 776,304
- 153
- 1,341
- 1,358
python -c "from os import system; system('clear')"

- 26,716
- 22
- 73
- 82

- 8,753
- 4
- 39
- 64
-
15
-
3
-
6
-
6http://support.microsoft.com/kb/99261 - it's less terrible than win32api :) – Dale Reidy Jan 18 '10 at 08:44
-
I hope os.system fans don't write code that accepts any kind of user-entered data (i.e. the vast majority of applications)... – allyourcode Mar 25 '16 at 23:45
-
3@allyourcode Aren't they all suggesting it in cases where the commands are fixed strings? Then we'd better not recommend removing a file in bash with `rm file` either - as someone could misunderstand it and execute `rm -rf /` as root instead. – steinar Apr 12 '17 at 20:35
-
when it's down voted to 0. i will delete it. it's interesting that the most upvoted answer is about the same thing. ;-) – Dyno Fu Jan 09 '19 at 21:05
You can use call()
function to execute terminal's commands :
from subprocess import call
call("clear")

- 5,297
- 5
- 39
- 59
This will clear 25 new lines:
def clear():
print(' \n' * 25)
clear()
I use eclipse with pydev. I like the newline solution better than the for num in range . The for loop throws warnings, while the print newline doesn't. If you want to specify the number of newlines in the clear statement try this variation.
def clear(j):
print(' \n' * j)
clear(25)

- 638
- 3
- 7
- 16
-
125 lines is hardly a standard today - 70 lines are more guaranteed to scroll up all the lines one will be using in a serious terminal (window's various DOS shell remakes not being considered serious, mainly due to UI limitations) – jsbueno Jun 02 '16 at 05:25
you can make your own. this will not be dependent on your terminal, or OS type.
def clear(num):
for i in range(num): print
clear(80)
print "hello"

- 327,991
- 56
- 259
- 343
-
1... You don't need the empty string literal there. ... What? I'm trying to stay *positive* here! – Ignacio Vazquez-Abrams Jan 18 '10 at 08:05
-
1
If all you need is to clear the screen, this is probably good enough. The problem is there's not even a 100% cross platform way of doing this across linux versions. The problem is the implementations of the terminal all support slightly different things. I'm fairly sure that "clear" will work everywhere. But the more "complete" answer is to use the xterm control characters to move the cursor, but that requires xterm in and of itself.
Without knowing more of your problem, your solution seems good enough.

- 47,727
- 41
- 151
- 191
For Windows, on the interpreter command line only (not the GUI)! Simply type: (Remember to use proper indentation with python):
import os
def clear():
os.system('cls')
Every time you type clear()
on the shell (command line), it will clear the screen on your shell. If you exit the shell, then you must redo the above to do it again as you open a new Python (command line) shell.
Note: Does not matter what version of Python you are using, explicitly (2.5, 2.7, 3.3 & 3.4).

- 11,201
- 10
- 62
- 89

- 35
- 1
- 9
-
3This way can be combined with platform.system() to get "Windows", "Linux" or other systems platforms info then set clear command per OS. I have mine with cls() name as follow `def cls(): if platform.system() == "Linux": os.system("clear") elif platform.system() == "Windows": os.system("cls")` – m3nda Aug 28 '15 at 03:32
I would do it in this way to make it look more like bash:
Just create a file named .pythonstartup at Home directory and use poke's answer in a function
On Linux:
echo "from subprocess import call
def clear(int=None):
call('clear')
if int == 0:
exit()
clear()" >> $HOME/.pythonstartup ; export PYTHONSTARTUP=$HOME/.pythonstartup ; python
You can add export PYTHONSTARTUP=$HOME/.pythonstartup
to your ./bashrc
file
Since what I care about is space; a call to the function will not display the python interpreter description at startup, but you can remove clear()
to retain it.
Using it like a normal function should do the trick without printing the exit status:
>>> clear()
If you pass the argument 0 to the function it will clear the screen and exit successfully so you can continue using the shell in a clean screen
>>> clear(0)

- 11,201
- 10
- 62
- 89

- 311
- 2
- 11
A perhaps cheesy way to clear the screen, but one that will work on any platform I know of, is as follows:
for i in xrange(0,100):
print ""

- 17
- 1
-
It will leave the cursor at the end of the window. It also leaves the possibility to scroll back to what was previously there. Might be a good thing or not. Also, you might want to put a greater number since some user could be using more than 100 lines...;) – Rod Jan 26 '11 at 18:32
-
5You could also write `print ('\n' * 100)` which will work in Python 2.x and 3.x while being faster. – Noctis Skytower May 30 '12 at 15:17
The accepted answer is a good solution. The problem with it is that so far it only works on Windows 10, Linux and Mac. Yes Windows (known for it lack of ANSI support)! This new feature was implemented on Windows 10 (and above) which includes ANSI support, although you have to enable it. This will clear the screen in a cross platform manner:
import os
print ('Hello World')
os.system('')
print ("\x1B[2J")
On anything below Windows 10 however it returns this:
[2J
This is due to the lack of ANSI support on previous Windows builds. This can however, be solved using the colorama module. This adds support for ANSI characters on Windows:
ANSI escape character sequences have long been used to produce colored terminal text and cursor positioning on Unix and Macs. Colorama makes this work on Windows, too, by wrapping stdout, stripping ANSI sequences it finds (which would appear as gobbledygook in the output), and converting them into the appropriate win32 calls to modify the state of the terminal. On other platforms, Colorama does nothing.
So here is a cross platform method:
import sys
if sys.platform == 'win32':
from colorama import init
init()
print('Hello World')
print("\x1B[2J")
Or print(chr(27) + "[2J")
used instead of print("\x1B[2J")
.
@poke answer is very insecure on Windows, yes it works but it is really a hack. A file named cls.bat
or cls.exe
in the same dictionary as the script will conflict with the command and execute the file instead of the command, creating a huge security hazard.
One method to minimise the risk could be to change the location of where the cls
command is called:
import os
os.system('cd C:\\Windows|cls' if os.name == 'nt' else 'clear')
This will change the Currant Dictionary to C:\Window
(backslash is important here) then execute. C:\Windows
is always present and needs administration permissions to write there making it a good for executing this command with minimal risk. Another solution is to run the command through PowerShell instead of Command Prompt since it has been secured against such vulnerabilities.
There are also other methods mentioned in this question: Clear screen in shell which may also be of use.

- 11,201
- 10
- 62
- 89
By default, os.system("clear")
/os.system("cls")
will return an int type as 0.
We can completely clear the screen by assigning it to a variable and deleting that.
def clear():
if (os.name == 'nt'):
c = os.system('cls')
else:
c = os.system('clear')
del c # can also omit c totally
#clear()

- 218,210
- 55
- 464
- 476

- 23
- 5
-
2duplicate of answer given more than 2 years ago... longer and less elegent. See @poke answer with most votes for this question – Joop Aug 08 '13 at 15:20
This works on all platforms and it does work in both Python 2 and 3.
def clear(number):
for i in range(number):
print(" ")
Then to clear just type clear(numberhere)
.

- 342
- 3
- 16

- 24
- 3
-
1Bad. For loops are slower than just `print(""*100)`. Also no need to print the space. – Remigiusz Schoida Aug 24 '18 at 19:04
-
1