Like most Python developers, I typically keep a console window open with the Python interpreter running to test commands,
help() stuff, etc.
Like any console, after a while the visible backlog of past commands and prints gets to be cluttered, and sometimes confusing when re-running the same command several times. I’m wondering if, and how, to clear the Python interpreter console.
I’ve heard about doing a system call and either calling
cls on Windows or
clear on Linux, but I was hoping there was something I could command the interpreter itself to do.
Note: I’m running on Windows, so
Ctrl+L doesn’t work.
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
As you mentioned, you can do a system call:
>>> import os >>> clear = lambda: os.system('cls') >>> clear()
For Linux it would be:
>>> import os >>> clear = lambda: os.system('clear') >>> clear()
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.
EDIT: I’ve just read "windows", this is for linux users, sorry.
#!/bin/bash while true; do clear "[email protected]" 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:
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.
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()
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.
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
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
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
Here are two nice ways of doing that:
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')
import os def clear(): if os.name == 'posix': os.system('clear') elif os.name in ('ce', 'nt', 'dos'): os.system('cls') clear()
How about this for a clear
That is about as short as could be!
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…
# This works in BASH because I have it in .inputrc as well, but for some
# reason it gets dropped when I go into Python
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
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
>>> ' '*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()
Here’s the definitive solution that merges all other answers. Features:
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
posix) 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()
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:
PS: you can name you function anyway you want. Iv’ seen people using “wiper” “wipe” and variations.
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!
I found the simplest way is just to close the window and run a module/script to reopen the shell.
just use this..
I am using Spyder (Python 2.7) and to clean the interpreter console I use either
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.
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
clear() to clear the screen.
this works on windows, osx, linux, bsd… all OSes.
I’m not sure if Windows’ “shell” supports this, but on Linux:
print " 33[2J"
In my opinion calling
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.
If it is on mac, then a simple
cmd + k should do the trick.
Quickest and easiest way without a doubt is Ctrl+L.
This is the same for OS X on the terminal.
You have number of ways doing it on Windows:
Press CTRL + L
import os cls = lambda: os.system('cls') cls()
cls = lambda: print('n'*100) cls()
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.