How do you clear the console mid program in python? [duplicate] - python

Like most Python developers, I typically keep a console window open with the Python interpreter running to test commands, dir() stuff, help() stuff, etc.
Like any console, after a while the visible backlog of past commands and prints gets to be cluttered, and sometimes confusing when re-running the same command several times. I'm wondering if, and how, to clear the Python interpreter console.
I've heard about doing a system call and either calling cls on Windows or clear on Linux, but I was hoping there was something I could command the interpreter itself to do.
Note: I'm running on Windows, so Ctrl+L doesn't work.

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

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

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

This is the simplest thing you can do and it doesn't require any additional libraries. It clears the screen and returns >>> to the top left corner.
print("\033[H\033[J", end="")
UPDATE 1:
Since this answer gets some attention, you might want to know how it works. The command above prints ANSI escape codes:
\033 stands for ESC (ANSI value 27).
\033[ is a special escape sequence called Control Sequence
Introducer (CSI).
\033[H command moves the cursor to the top left corner of the screen.
\033[J clears the screen from the cursor to the end of
the screen.
Optional parameter end="" avoids printing newline character after executing these commands, so >>> stays in the topmost row.
UPDATE 2:
You may want to extend the above command with one additional parameter - x (before J):
print("\033[H\033[xJ", end="")
If x is 1, it will clear from cursor to beginning of the screen.
If x is 2, it will clear entire screen and move cursor to
upper left.
If x is 3, it will clear entire
screen and delete all lines saved in the scrollback buffer.
So, this command will clear everything, including buffer:
print("\033[H\033[3J", end="")
COMMAND LINE:
To clear screen in a shell (console / terminal) you can use the same command. To clear entire screen and delete all lines saved in the scrollback buffer put 3 before J:
printf "\033[H\033[3J"
or create an alias:
alias cls='printf "\033[H\033[3J"'

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

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

Quickest and easiest way without a doubt is Ctrl+L.
This is the same for OS X on the terminal.

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.

The perfect cls, also compatible with Python2 (in .pythonrc file):
from __future__ import print_function
cls = lambda: print("\033c", end='')
and can be called from the terminal in this way:
cls()
Or directly:
print("\033c", end='')
\033[H\033[J only clears the visible screen, exactly the same as the clear command up to Ubuntu 18.10. It doesn't clear the scrollback buffer. Scrolling up will reveal the history.
To simulate this behavior, insert some terminal lines, then press Ctrl+L and insert more. After executing print("\033[H\033[J", end=""), only the screen lines inserted after pressing "Ctrl + L" will be deleted.
\033c clears everything.
\x1bc may not give the same result as \033c as the hex escape is not clearly length limited.

I'm not sure if Windows' "shell" supports this, but on Linux:
print "\033[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.

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

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.

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

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.

If it is on mac, then a simple cmd + k should do the trick.

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

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[H\x1b[2J'.

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:\Python33\Lib)
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.

>>> ' '*80*25
UPDATE: 80x25 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()

just use this..
print '\n'*1000

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

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 screen
wipe() wipes entire terminal buffer

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

How about this for a clear
- os.system('cls')
That is about as short as could be!

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.

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.

Magic strings are mentioned above - I believe they come from the terminfo database:
http://www.google.com/?q=x#q=terminfo
http://www.google.com/?q=x#q=tput+command+in+unix
$ tput clear| od -t x1z
0000000 1b 5b 48 1b 5b 32 4a >.[H.[2J<
0000007

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.

Use clear() from replit:
from replit import clear
clear()

Related

How to clear screen/terminal in python [duplicate]

This question already has answers here:
How to clear the interpreter console?
(31 answers)
Closed 4 years ago.
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)?
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')
What about escape sequences?
print(chr(27) + "[2J")
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.
As for me, the most elegant variant:
import os
os.system('cls||clear')
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")
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.
Just use:
print("\033c")
This will clear the terminal window.
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.
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()
This will be work in Both version Python2 OR Python3
print (u"{}[2J{}[;H".format(chr(27), chr(27)))
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
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.
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.
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')
In Windows you can use:
>>> import os
>>> clear = lambda: os.system('cls')
>>> clear()
You could tear through the terminfo database, but the functions for doing so are in curses anyway.
python -c "from os import system; system('clear')"
You can use call() function to execute terminal's commands :
from subprocess import call
call("clear")
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"
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)
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.
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 ""
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)
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).
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.
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()
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).

pythonrc in interactive code

I have a .pythonrc in my path, which gets loaded when I run python:
python
Loading pythonrc
>>>
The problem is that my .pythonrc is not loaded when I execute files:
python -i script.py
>>>
It would be very handy to have tab completion (and a few other things) when I load things interactively.
From the Python documentation for -i:
When a script is passed as first argument or the -c option is used, enter interactive mode after executing the script or the command, even when sys.stdin does not appear to be a terminal. The PYTHONSTARTUP file is not read.
I believe this is done so that scripts run predictably for all users, and do not depend on anything in a user's particular PYTHONSTARTUP file.
As Greg has noted, there is a very good reason why -i behaves the way it does. However, I do find it pretty useful to be able to have my PYTHONSTARTUP loaded when I want an interactive session. So, here's the code I use when I want to be able to have PYTHONSTARTUP active in a script run with -i.
if __name__ == '__main__':
#do normal stuff
#and at the end of the file:
import sys
if sys.flags.interactive==1:
import os
myPythonPath = os.environ['PYTHONSTARTUP'].split(os.sep)
sys.path.append(os.sep.join(myPythonPath[:-1]))
pythonrcName = ''.join(myPythonPath[-1].split('.')[:-1]) #the filename minus the trailing extension, if the extension exists
pythonrc = __import__(pythonrcName)
for attr in dir(pythonrc):
__builtins__.__dict__[attr] = getattr(pythonrc, attr)
sys.path.remove(os.sep.join(myPythonPath[:-1]))
del sys, os, pythonrc
Note that this is fairly hacky and I never do this without ensuring that my pythonrc isn't accidentally clobbering variables and builtins.
Apparently the user module provides this, but has been removed in Python 3.0. It is a bit of a security hole, depending what's in your pythonrc...
In addition to Chinmay Kanchi and Greg Hewgill's answers, I'd like to add that IPython and BPython work fine in this case. Perhaps it's time for you to switch? :)

How can I add a command to the Python interactive shell?

I'm trying to save myself just a few keystrokes for a command I type fairly regularly in Python.
In my python startup script, I define a function called load which is similar to import, but adds some functionality. It takes a single string:
def load(s):
# Do some stuff
return something
In order to call this function I have to type
>>> load('something')
I would rather be able to simply type:
>>> load something
I am running Python with readline support, so I know there exists some programmability there, but I don't know if this sort of thing is possible using it.
I attempted to get around this by using the InteractivConsole and creating an instance of it in my startup file, like so:
import code, re, traceback
class LoadingInteractiveConsole(code.InteractiveConsole):
def raw_input(self, prompt = ""):
s = raw_input(prompt)
match = re.match('^load\s+(.+)', s)
if match:
module = match.group(1)
try:
load(module)
print "Loaded " + module
except ImportError:
traceback.print_exc()
return ''
else:
return s
console = LoadingInteractiveConsole()
console.interact("")
This works with the caveat that I have to hit Ctrl-D twice to exit the python interpreter: once to get out of my custom console, once to get out of the real one.
Is there a way to do this without writing a custom C program and embedding the interpreter into it?
Edit
Out of channel, I had the suggestion of appending this to the end of my startup file:
import sys
sys.exit()
It works well enough, but I'm still interested in alternative solutions.
You could try ipython - which gives a python shell which does allow many things including automatic parentheses which gives you the function call as you requested.
I think you want the cmd module.
See a tutorial here:
http://wiki.python.org/moin/CmdModule
Hate to answer my own question, but there hasn't been an answer that works for all the versions of Python I use. Aside from the solution I posted in my question edit (which is what I'm now using), here's another:
Edit .bashrc to contain the following lines:
alias python3='python3 ~/py/shellreplace.py'
alias python='python ~/py/shellreplace.py'
alias python27='python27 ~/py/shellreplace.py'
Then simply move all of the LoadingInteractiveConsole code into the file ~/py/shellreplace.py Once the script finishes executing, python will cease executing, and the improved interactive session will be seamless.

Any way to clear python's IDLE window?

I know there's a similar topic about python console, but I do not know if they are the same. I tried system("clear") and it didn't work here.
How do I clear python's IDLE window?
The "cls" and "clear" are commands which will clear a terminal (ie a DOS prompt, or terminal window). From your screenshot, you are using the shell within IDLE, which won't be affected by such things. Unfortunately, I don't think there is a way to clear the screen in IDLE. The best you could do is to scroll the screen down lots of lines, eg:
print ("\n" * 100)
Though you could put this in a function:
def cls(): print ("\n" * 100)
And then call it when needed as cls()
os.system('clear') works on linux. If you are running windows try os.system('CLS') instead.
You need to import os first like this:
import os
Most of the answers, here do clearing the DOS prompt screen, with clearing commands, which is not the question. Other answers here, were printing blank lines to show a clearing effect of the screen.
The simplest answer of this question is
It is not possible to clear python IDLE shell without some external module integration. If you really want to get a blank pure fresh shell just close the previous shell and run it again
ctrl + L clears the screen on Ubuntu Linux.
An extension for clearing the shell can be found in Issue6143 as a "feature request". This extension is included with IdleX.
>>> import os
>>>def cls():
... os.system("clear")
...
>>>cls()
That does is perfectly. No '0' printed either.
There does not appear to be a way to clear the IDLE 'shell' buffer.
The way to execute commands in Python 2.4+ is to use the subprocess module. You can use it in the same way that you use os.system.
import subprocess
subprocess.call("clear") # linux/mac
subprocess.call("cls", shell=True) # windows
If you're executing this in the python console, you'll need to do something to hide the return value (for either os.system or subprocess.call), like assigning it to a variable:
cls = subprocess.call("cls", shell=True)
I like to use:
import os
clear = lambda : os.system('cls') # or clear for Linux
clear()
File -> New Window
In the new window**
Run -> Python Shell
The problem with this method is that it will clear all the things you defined, such as variables.
Alternatively, you should just use command prompt.
open up command prompt
type "cd c:\python27"
type "python example.py" , you have to edit this using IDLE when it's not in interactive mode. If you're in python shell, file -> new window.
Note that the example.py needs to be in the same directory as C:\python27, or whatever directory you have python installed.
Then from here, you just press the UP arrow key on your keyboard. You just edit example.py, use CTRL + S, then go back to command prompt, press the UP arrow key, hit enter.
If the command prompt gets too crowded, just type "clr"
The "clr" command only works with command prompt, it will not work with IDLE.
"command + L" for MAC OS X.
"control + L" for Ubuntu
Clears the last line on the interactive session
It seems like there is no direct way for clearing the IDLE console.
One way I do it is use of exit() as the last command in my python script (.py). When I run the script, it always opens up a new console and prompt before exiting.
Upside : Console is launched fresh each time the script is executed.
Downside : Console is launched fresh each time the script is executed.
As mark.ribau said, it seems that there is no way to clear the Text widget in idle. One should edit the EditorWindow.py module and add a method and a menu item in the EditorWindow class that does something like:
self.text.tag_remove("sel", "1.0", "end")
self.text.delete("1.0", "end")
and perhaps some more tag management of which I'm unaware of.
None of these solutions worked for me on Windows 7 and within IDLE. Wound up using PowerShell, running Python within it and exiting to call "cls" in PowerShell to clear the window.
CONS: Assumes Python is already in the PATH variable. Also, this does clear your Python variables (though so does restarting the shell).
PROS: Retains any window customization you've made (color, font-size).
It seems it is impossible to do it without any external library.
An alternative way if you are using windows and don't want to open and close the shell everytime you want to clear it is by using windows command prompt.
Type python and hit enter to turn windows command prompt to python idle (make sure python is installed).
Type quit() and hit enter to turn it back to windows command prompt.
Type cls and hit enter to clear the command prompt/ windows shell.
The best way to do it on windows is using the command prompt 'cmd' and access python directory the command prompt could be found on the start menu >run>cmd
C:\>cd Python27
C:\Python27>python.exe
Python 2.7.3 (default, Apr 10 2012, 23:24:47) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>>import os
>>>os.system('cls') #This will clear the screen and return the value 0
You can make an AutoHotKey script.
To set ctrl-r to a hotkey to clear the shell:
^r::SendInput print '\n' * 50 {Enter}
Just install AutoHotKey, put the above in a file called idle_clear.ahk, run the file, and your hotkey is active.
I would recommend you to use Thonny IDE for Python. It's shell has "Clear Shell" option and you can also track variables created in a separate list. It's debugging is very good even comparing with modern IDEs. You can also write code in python file along with access to shell at the same place.
And its lightweight!
use this
for num in range(1,100):
print("\n")
Turtle can clear the screen.
#=====================================
import turtle
wn = turtle.Screen()
wn.title("Clear the Screen")
t = turtle.Turtle()
t.color('red', 'yellow')
t.speed(0)
#=====================================
def star(x, y, length, angle):
t.penup()
t.goto(x, y)
t.pendown()
t.begin_fill()
while True:
t.forward(length)
t.left(angle)
if t.heading() == 0: #===============
break
t.end_fill()
#=====================================
# ( x, y, length, angle)
star(-360, 0, 150, 45)
t.clear()
#=====================================
This answer is for IDLE, not for the command prompt and was tested with Python 3.10.6.
If you press Ctrl+Z while the code is running (before it finishes), the previous output will be erased. If you wish to automate this, there's the pynput package.
pip install pynput
Here's a sample code (macros are unsafe, use it at your own risk):
# License: MIT-0
import time
import pynput
class _Eraser:
keyboard = pynput.keyboard.Controller()
ctrl = pynput.keyboard.Key.ctrl
is_initialized = False
#classmethod
def erase(cls, n):
if not cls.is_initialized:
cls.is_initialized = True
n += 1
for _ in range(n):
with cls.keyboard.pressed(cls.ctrl):
cls.keyboard.press('z')
cls.keyboard.release('z')
time.sleep(0.1)
def erase(n=1):
_Eraser.erase(n)
print('test1\n', end='')
print('test2\n', end='')
erase() # Erase 'test2\n'
print('test3')
print('test4')
erase() # Erase '\n'
print('test5')
print('test6')
erase(2) # Erase '\n' and then 'test6'
print('test7')
The output is:
test1
test3
test4test5
test7
This works for me in Windows:
print chr(12)
There is no need to write your own function to do this! Python has a built in clear function.
Type the following in the command prompt:
shell.clear()
If using IPython for Windows, it's
cls()

How to make a python, command-line program autocomplete arbitrary things NOT interpreter

I am aware of how to setup autocompletion of python objects in the python interpreter (on unix).
Google shows many hits for explanations on how to do this.
Unfortunately, there are so many references to that it is difficult to find what I need to do, which is slightly different.
I need to know how to enable, tab/auto completion of arbitrary items in a command-line program written in python.
My specific use case is a command-line python program that needs to send emails. I want to be able to autocomplete email addresses (I have the addresses on disk) when the user types part of it (and optionally presses the TAB key).
I do not need it to work on windows or mac, just linux.
Use Python's readline bindings. For example,
import readline
def completer(text, state):
options = [i for i in commands if i.startswith(text)]
if state < len(options):
return options[state]
else:
return None
readline.parse_and_bind("tab: complete")
readline.set_completer(completer)
The official module docs aren't much more detailed, see the readline docs for more info.
Follow the cmd documentation and you'll be fine
import cmd
addresses = [
'here#blubb.com',
'foo#bar.com',
'whatever#wherever.org',
]
class MyCmd(cmd.Cmd):
def do_send(self, line):
pass
def complete_send(self, text, line, start_index, end_index):
if text:
return [
address for address in addresses
if address.startswith(text)
]
else:
return addresses
if __name__ == '__main__':
my_cmd = MyCmd()
my_cmd.cmdloop()
Output for tab -> tab -> send -> tab -> tab -> f -> tab
(Cmd)
help send
(Cmd) send
foo#bar.com here#blubb.com whatever#wherever.org
(Cmd) send foo#bar.com
(Cmd)
Since you say "NOT interpreter" in your question, I guess you don't want answers involving python readline and suchlike. (edit: in hindsight, that's obviously not the case. Ho hum. I think this info is interesting anyway, so I'll leave it here.)
I think you might be after this.
It's about adding shell-level completion to arbitrary commands, extending bash's own tab-completion.
In a nutshell, you'll create a file containing a shell-function that will generate possible completions, save it into /etc/bash_completion.d/ and register it with the command complete. Here's a snippet from the linked page:
_foo()
{
local cur prev opts
COMPREPLY=()
cur="${COMP_WORDS[COMP_CWORD]}"
prev="${COMP_WORDS[COMP_CWORD-1]}"
opts="--help --verbose --version"
if [[ ${cur} == -* ]] ; then
COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) )
return 0
fi
}
complete -F _foo foo
In this case, the typing foo --[TAB] will give you the values in the variable opts, i.e. --help, --verbose and --version. For your purposes, you'll essentially want to customise the values that are put into opts.
Do have a look at the example on the linked page, it's all pretty straightforward.
I am surprised that nobody has mentioned argcomplete, here is an example from the docs:
from argcomplete.completers import ChoicesCompleter
parser.add_argument("--protocol", choices=('http', 'https', 'ssh', 'rsync', 'wss'))
parser.add_argument("--proto").completer=ChoicesCompleter(('http', 'https', 'ssh', 'rsync', 'wss'))
Here is a full-working version of the code that was very supplied by ephemient here (thank you).
import readline
addrs = ['angela#domain.com', 'michael#domain.com', 'david#test.com']
def completer(text, state):
options = [x for x in addrs if x.startswith(text)]
try:
return options[state]
except IndexError:
return None
readline.set_completer(completer)
readline.parse_and_bind("tab: complete")
while 1:
a = raw_input("> ")
print "You entered", a
# ~/.pythonrc
import rlcompleter, readline
readline.parse_and_bind('tab:complete')
# ~/.bashrc
export PYTHONSTARTUP=~/.pythonrc
You can try using the Python Prompt Toolkit, a library for building interactive command line applications in Python.
The library makes it easy to add interactive autocomplete functionality, allowing the user to use the Tab key to visually cycle through the available choices. The library is cross-platform (Linux, OS X, FreeBSD, OpenBSD, Windows). Example:
(Image source: pcgli)
The posted answers work fine but I have open sourced an autocomplete library that I wrote at work. We have been using it for a while in production and it is fast, stable and easy to use. It even has a demo mode so you can quickly test what you would get as you type words.
To install it, simply run: pip install fast-autocomplete
Here is an example:
>>> from fast_autocomplete import AutoComplete
>>> words = {'book': {}, 'burrito': {}, 'pizza': {}, 'pasta':{}}
>>> autocomplete = AutoComplete(words=words)
>>> autocomplete.search(word='b', max_cost=3, size=3)
[['book'], ['burrito']]
>>> autocomplete.search(word='bu', max_cost=3, size=3)
[['burrito']]
>>> autocomplete.search(word='barrito', max_cost=3, size=3) # mis-spelling
[['burrito']]
Checkout: https://github.com/seperman/fast-autocomplete for the source code.
And here is an explanation of how it works: http://zepworks.com/posts/you-autocomplete-me/
It deals with mis-spellings and optionally sorting by the weight of the word. (let's say burrito is more important than book, then you give burrito a higher "count" and it will show up first before book in the results.
Words is a dictionary and each word can have a context. For example the "count", how to display the word, some other context around the word etc. In this example words didn't have any context.
This works well.
#!/usr/bin/python3
import readline
readline.parse_and_bind("tab: complete")
def complete(text,state):
volcab = ['dog','cat','rabbit','bird','slug','snail']
results = [x for x in volcab if x.startswith(text)] + [None]
return results[state]
readline.set_completer(complete)
line = input('prompt> ')

Categories

Resources