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


当前回答

我将这样做,使它看起来更像bash:

只需在主目录下创建一个名为.pythonstartup的文件,并在函数中使用poke的答案

在Linux上:

echo "from subprocess import call
def clear(int=None):  
    call('clear')
    if int == 0:
       exit()
clear()" >> $HOME/.pythonstartup ; export PYTHONSTARTUP=$HOME/.pythonstartup ; python

您可以添加export PYTHONSTARTUP=$HOME/。Pythonstartup到你的。/bashrc文件

因为我关心的是空间;调用该函数将不会在启动时显示python解释器描述,但您可以删除clear()以保留它。

像使用普通函数一样使用它应该不会打印退出状态:

>>> clear()

如果您将参数0传递给函数,它将清除屏幕并成功退出,因此您可以在干净的屏幕中继续使用shell

>>> clear(0)

其他回答

一个简单的跨平台解决方案是在Windows上使用cls命令,或者在Unix系统上使用clear命令。与os连用系统,这是一个很好的一行:

import os
os.system('cls' if os.name == 'nt' else 'clear')

为什么没有人谈论过在Windows中使用Ctrl+L或者在Mac中使用Cmd+L。 这无疑是清除屏幕的最简单方法。

只使用:

print("\033c")

这将清除终端窗口。

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

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

清除屏幕的方法可能有些俗气,但在我所知的任何平台上都适用,如下:

for i in xrange(0,100):
    print ""