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


当前回答

你可以自己做。这将不依赖于你的终端,或操作系统类型。

def clear(num):
    for i in range(num): print 

clear(80)
print "hello"

其他回答

从操作系统导入系统;系统(清晰的)”

你可以使用call()函数来执行终端的命令:

from subprocess import call
call("clear")

您可以对terminfo数据库进行分解,但这样做的函数无论如何都是在curses中。

对于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)。

所以我想在这里发表我的意见…

似乎没有人对这个问题提供一个真实的答案,每个人的回答都是“不使用os.system()这是邪恶的!!”没有解释,也没有提供依赖于打印新行的解决方案。

对于那些需要清除终端屏幕并向后滚动的用户,无论出于何种原因,您都可以使用以下代码:

import os

def clear():
    '''
    Clears the terminal screen and scroll back to present
    the user with a nice clean, new screen. Useful for managing
    menu screens in terminal applications.
    '''
    os.system('cls' if os.name == 'nt' else 'echo -e \\\\033c')

print('A bunch of garbage so we can garble up the screen...')
clear()

# Same effect, less characters...

def clear():
    '''
    Clears the terminal screen and scroll back to present
    the user with a nice clean, new screen. Useful for managing
    menu screens in terminal applications.
    '''
    os.system('cls||echo -e \\\\033c')

这达到了OP所期望的效果。它确实使用os.system()命令,所以如果这是邪恶的,有人知道使用subprocess.call()实现这一点的方法,请评论,因为我也更喜欢使用subprocess,但根本不熟悉它。