How can I clear the Python pdb screen? - python

Let's say I write
(Pdb) p dir(object)
and, now my screen is taken up with a list of attributes. How can I clear this text while still in debug mode? Importantly, I don't want to lose my place in the code.

Depends on your OS. If you're on windows this should work:
import os; os.system('cls')
If you're on GNU/Linux (I think in Mac OS too) this should do the trick:
import os; os.system('clear')
But, if you use bash as you shell interpreter, there is a handy keymap: CTRL+l

You could always print('\n'*30)

In your ~/.pdbrc (which is initialized when you fire up pdb) you can add :
import os
def cls(): os.system('clear')
Then when you are in Pdb, you can type cls() to clear the screen without needing as many key strokes at the command line.

Related

How to clear VS code terminal using python code?

I am taking input from user in python code. and as per user's provided input I want to clear previous outputs in terminal.
so is there any function? So I can put it in my code.
I searched on internet but it showing me Shortcut keys from keyboard but I want to clear terminal with help of code.(not want to type terminal )
The commands will be slightly different depending on if you're running Python in Windows or Linux/Mac (or a Unix like terminal while in Windows)
In Windows terminals, the command to clear the screen is cls.
In Max/Linux/Unix, the command is clear.
Windows Powershell appears to
except either cls or clear.
To call the appropriate command from within a script, you need to import the os module and call os.system(cmd). This will return a value of 0 for success, so if you are testing it in the terminal directly you may see an extra 0 get displayed on the screen if you don't put the return value into a variable.
Here's some code to call the correct function based on your os. os.name will return 'nt' for Windows or 'posix' for Mac/Linux
import os
# define our clear function
def clear():
# for Windows
if os.name == 'nt':
_ = os.system('cls')
# Mac or Linux (aka posix)
else:
_ = os.system('clear')
Calling the clear() function in your script should clear the terminal as needed.
You can clear the terminal with:
print('\x1b[H\x1b[2J', end='')
...or...
from sys import stdout
stdout.write('\x1b[H\x1b[2J')
...which is probably more efficient than os.system(...)
The string is actually 2 CSI sequences. The first moves the cursor to the screen origin (1, 1). The second sequence is the clear screen directive

how to clear a running file on python [duplicate]

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

Python - ctrl L does not work

Attempting to use Ctrl+L for clearing Power Sheel in Python 2.7.8 I get no response.
Is there any problem in Windows 10?
Ctrl+L only works on Linux/OS X terminals. It does not work on Windows. To clear the screen on Windows you could do the following:
import os
os.system('cls')
If you're using IDLE on Windows there is not a way to clear it. As a workaround you can use:
print('\n' * 80)
To extend Kredns answer to Linux/OS X terminals as well:
import os
os.system('clear')
I like Kredns's answer, however, you have to type all of that every time.
I made a module/function.
Okay, I am using Python 3.7.3, but similar answer for Python 2.
def cls():
import os
os.system('cls')
return
Save this as a script and import cls or whatever you want to call it. Import that (e.g. on python start up). So if you're in the correct directory:
from cls import cls
Then call it with cls() whenever you want to clear the screen.
cls()
IdleX extension of IDLE has the functionality you are looking for.
Try installing from here
http://idlex.sourceforge.net/
OR
https://pypi.org/project/idlex/
pressing CTRL-L, works in the intutive way (clear the console and take you to the top with a prompt, and doesn't clear the variables and definitions you have defined yet)

Anyway of clearing text in IDLE

Is there anyway of clearing text in IDLE, its really anoying when i run the script a couple of times and then there's a cluster of words which is really hard to read.
and yes I have looked on google, stack_overflow and a couple of more websites but i cant find anything useful.
I tried to do:
import os
def cls():
os.system("cls")
>>>cls()
If you mean using the actual IDLE shell, I don't think there's any way to do it. IDLE is not meant to run programs from, it's just supposed to be a development tool. If you want to run programs from terminal or cmd, you can clear the text easily.
Use this instead:
os.system("clear") # or "cls" on windows
or
subprocess.call('clear') # or "cls" on windows
To fake it in IDLE, you can use something like:
print("\n" * 50)
from subprocess import call as c
def cls():
c("cls",shell=True)
print([x for x in range(10000)])
cls()
Whenever you wish to clear console call the function cls, but note that this function will clear the screen in Windows only if you are running Python Script using cmd prompt, it will not clear the buffer if you running by IDLE.

How to clear the interpreter console?

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

Categories