Clear terminal in Python [duplicate]
Solution 1:
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')
Solution 2:
What about escape sequences?
print(chr(27) + "[2J")
Solution 3:
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.
Solution 4:
As for me, the most elegant variant:
import os
os.system('cls||clear')
Solution 5:
For Windows, Mac and Linux, you can use the following code:
import subprocess, platform
if platform.system()=="Windows":
subprocess.Popen("cls", shell=True).communicate() #I like to use this instead of subprocess.call since for multi-word commands you can just type it out, granted this is just cls and subprocess.call should work fine
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.Popen("printf '\033c'", shell=True).communicate()
.
rolika pointed out that end=""
will prevent it from printing a new line afterward.