是否存在任何标准的“附带电池”方法来清除Python脚本中的终端屏幕,或者我必须去诅咒(库,而不是单词)?


当前回答

转义序列呢?

print(chr(27) + "[2J")

其他回答

这适用于所有平台,并且在Python 2和3中都有效。

def clear(number):
    for i in range(number):
        print(" ")

然后输入clear(numberhere)来清除。

对于Windows,只能在解释器命令行上(而不是GUI)!简单的类型: (记住在python中使用适当的缩进):

import os
def clear():
    os.system('cls')

每次在shell(命令行)上输入clear(),它都会清除shell上的屏幕。如果退出shell,那么在打开新的Python(命令行)shell时,必须重新执行上述操作。

注意:无论你使用的是哪个版本的Python,明确地(2.5、2.7、3.3和3.4)。

对我来说,最优雅的说法是:

import os
os.system('cls||clear')

您可以尝试使用clear,但它可能并非在所有Linux发行版上都可用。在windows上使用你提到的cls。

import subprocess
import platform

def clear():
    subprocess.Popen( "cls" if platform.system() == "Windows" else "clear", shell=True)

clear()

注意:控制终端屏幕可能被认为是一种糟糕的形式。你在考虑使用期权吗?让用户自己决定是否要清除屏幕可能会更好。

只使用:

print("\033c")

这将清除终端窗口。