Clear terminal in Python
What about escape sequences?
print(chr(27) + "[2J")
How to clear the interpreter console?
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()
Clear screen in shell
For macOS/OS X, you can use the subprocess module and call 'cls' from the shell:
import subprocess as sp
sp.call('cls', shell=True)
To prevent '0' from showing on top of the window, replace the 2nd line with:
tmp = sp.call('cls', shell=True)
For Linux, you must replace cls
command with clear
tmp = sp.call('clear', shell=True)
Is there a python 3 command to clear the output console?
On the command prompt (not PyCharm console), try the colorama
library to move the cursor back up and print the next iteration over the current iteration (colorama
makes ANSI control codes compatible with Windows):
(colorama
can be installed via pip install colorama
)
import copy
import random
import time
import colorama
colorama.init()
WIDTH = 60
HEIGHT = 10
nextCells = []
for x in range(WIDTH):
column = []
for y in range(HEIGHT):
if random.randint(0, 1) == 0:
column.append('#')
else:
column.append(' ')
nextCells.append(column)
while True:
#print('\n\n\n\n')
currentCells = copy.deepcopy(nextCells)
for y in range(HEIGHT):
for x in range(WIDTH):
print(currentCells[x][y], end='')
print()
for x in range(WIDTH):
for y in range(HEIGHT):
leftCoord = (x - 1) % WIDTH
rightCoord = (x + 1) % WIDTH
aboveCoord = (y - 1) % HEIGHT
belowCoord = (y + 1) % HEIGHT
numNeighbors = 0
if currentCells[leftCoord][aboveCoord] == '#':
numNeighbors += 1
if currentCells[x][aboveCoord] == '#':
numNeighbors += 1
if currentCells[rightCoord][aboveCoord] == '#':
numNeighbors += 1
if currentCells[leftCoord][y] == '#':
numNeighbors += 1
if currentCells[rightCoord][y] == '#':
numNeighbors += 1
if currentCells[leftCoord][belowCoord] == '#':
numNeighbors += 1
if currentCells[x][belowCoord] == '#':
numNeighbors += 1
if currentCells[rightCoord][belowCoord] == '#':
numNeighbors += 1
if currentCells[x][y] == '#' and (numNeighbors == 2 or numNeighbors == 3):
nextCells[x][y] = '#'
elif currentCells[x][y] == ' ' and numNeighbors == 3:
nextCells[x][y] = '#'
else:
nextCells[x][y] = ' '
# Here we move the cursor back up:
print(f'\033[{HEIGHT+1}A')
time.sleep(1)
How do i automatically clear the terminal in VSCode before execution of script?
Building on @Jacques answer, you can use the sys
module to dynamically perform a platform check:
import os
import sys
# Linux
if sys.platform.startswith('linux'):
os.system('clear')
# Windows
elif sys.platform.startswith('win32'):
os.system('cls')
Alternatively, see this post on configuring vscode to do this for all programs: How do I automatically clear VS Code terminal when starting a build?
clear terminal (and history!) in Python
You could use subprocess.call()
from the standard library subprocess
module to send the reset
command to the terminal which will reinitialize the terminal and in effect do something similar to clear
but also clear the scrollback history.
import subprocess
subprocess.call('reset')
Alternatively, I have learned from this answer, that you can use the command tput reset
instead, which will clear the terminal instantly, whereas with reset
alone you will experience a slight delay. This can also be called with subprocess.call()
as follows:
subprocess.call(['tput', 'reset'])
For more info on the reset
command, do:
$ man reset
For more info on the subprocess
module, see the documentation.
I have tested both of these on Ubuntu, but hopefully the will work on OSX/macOS as well. If not, perhaps you can use subprocess
combined with this solution, but I am unable to test that.
Python - Clearing the terminal screen more elegantly
print "\033c"
works on my system.
You could also cache the clear-screen escape sequence produced by clear
command:
import subprocess
clear_screen_seq = subprocess.check_output('clear')
then
print clear_screen_seq
any time you want to clear the screen.
tput clear
command that produces the same sequence is defined in POSIX.
You could use curses
, to get the sequence:
import curses
import sys
clear_screen_seq = b''
if sys.stdout.isatty():
curses.setupterm()
clear_screen_seq = curses.tigetstr('clear')
The advantage is that you don't need to call curses.initscr()
that is required to get a window object which has .erase()
, .clear()
methods.
To use the same source on both Python 2 and 3, you could use os.write()
function:
import os
os.write(sys.stdout.fileno(), clear_screen_seq)
clear
command on my system also tries to clear the scrollback buffer using tigetstr("E3")
.
Here's a complete Python port of the clear.c
command:
#!/usr/bin/env python
"""Clear screen in the terminal."""
import curses
import os
import sys
curses.setupterm()
e3 = curses.tigetstr('E3') or b''
clear_screen_seq = curses.tigetstr('clear') or b''
os.write(sys.stdout.fileno(), e3 + clear_screen_seq)
Related Topics
Installing Pip Is Not Working in Python ≪ 3.6
How to Use Subprocess.Popen to Connect Multiple Processes by Pipes
How to Use a Decimal Step Value For Range()
Tkinter - Executing Functions Over Time
How to Search and Replace Text in a File
Flask View Raises Typeerror: 'Bool' Object Is Not Callable
How to Save/Restore a Model After Training
How to Split the Definition of a Long String Over Multiple Lines
Pass a List to a Function to Act as Multiple Arguments
Recursive Function Returning None in Python
Why Should Exec() and Eval() Be Avoided
Python Dictionary Comprehension