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


当前回答

这将清除25个新行:

def clear():
    print(' \n' * 25)

clear()

我在pydev中使用eclipse。我更喜欢换行解决方案比范围内的for num。for循环抛出警告,而打印换行符则不会。 如果您想在clear语句中指定换行数,请尝试此变体。

def clear(j):
    print(' \n' * j)

clear(25)

其他回答

如果您使用的是Linux/UNIX系统,那么打印ANSI转义序列以清除屏幕就可以了。您还需要将光标移动到屏幕的顶部。这将在任何支持ANSI的终端上工作。

import sys
sys.stderr.write("\x1b[2J\x1b[H")

这将不能在Windows上工作,除非ANSI支持已启用。Windows可能有一个等效的控制序列,但我不知道。

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

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

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

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

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

似乎没有人对这个问题提供一个真实的答案,每个人的回答都是“不使用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,但根本不熟悉它。

转义序列呢?

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