是否存在任何标准的“附带电池”方法来清除Python脚本中的终端屏幕,或者我必须去诅咒(库,而不是单词)?
当前回答
对于Windows, Mac和Linux,您可以使用以下代码:
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为Mac测试了打印(“\033c”,end=“”),我在Linux和Windows上测试了它(它不适用于Windows,因此调用cls的其他代码)。我不记得我第一次看到使用print("\033c")和/或printf版本:subprocess.run("printf '\033c'", shell=True)。
Rolika指出,end=""将阻止它随后打印新行。
注意,新版本的Ubuntu会很好地清除屏幕(不只是向下滚动,让它看起来是清除的),不像旧版本。
注意,用ESC c ("\033c")重置终端将使光标下划线并闪烁。如果你不想这样,你可以使用这些代码将其更改为另一种风格(在GNOME Terminal 3.44.0上测试,使用VTE 0.68 +BIDI +GNUTLS +ICU +SYSTEMD):
下划线闪烁:"\033[0 q" 块闪烁:"\033[1 q" 方块:"\033[2 q" 下划线闪烁:"\033[3 q" 下划线:"\033[4 q" 细条闪烁:“\033[5 q” 细条:"\033[6q "(大于6的数字似乎也是这样)
还要注意,你可以在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)
我相信下面的代码应该是为了清除你必须向上滚动才能看到的内容(但它很难与另一个命令一起使用而没有问题):
打印('*)
这可以做和clear以前做的一样的事情(所以你可以向上滚动查看被删除的内容,除了它不会将光标上升到顶部):
打印('**)
其他回答
转义序列呢?
print(chr(27) + "[2J")
您可以尝试使用clear,但它可能并非在所有Linux发行版上都可用。在windows上使用你提到的cls。
import subprocess
import platform
def clear():
subprocess.Popen( "cls" if platform.system() == "Windows" else "clear", shell=True)
clear()
注意:控制终端屏幕可能被认为是一种糟糕的形式。你在考虑使用期权吗?让用户自己决定是否要清除屏幕可能会更好。
这将清除25个新行:
def clear():
print(' \n' * 25)
clear()
我在pydev中使用eclipse。我更喜欢换行解决方案比范围内的for num。for循环抛出警告,而打印换行符则不会。 如果您想在clear语句中指定换行数,请尝试此变体。
def clear(j):
print(' \n' * j)
clear(25)
你可以自己做。这将不依赖于你的终端,或操作系统类型。
def clear(num):
for i in range(num): print
clear(80)
print "hello"
如果您希望在使用python shell时清除您的终端。然后,您可以执行以下操作清除屏幕
import os
os.system('clear')