像大多数Python开发人员一样,我通常打开一个控制台窗口,运行Python解释器来测试命令、dir()之类的东西、help()之类的东西,等等。

像任何控制台一样,在一段时间后,过去命令和打印的可见积压会变得混乱,并且在多次重新运行相同的命令时有时会令人困惑。我想知道是否以及如何清除Python解释器控制台。

我听说过做一个系统调用,或者在Windows上调用cls,或者在Linux上清除,但我希望有一些我可以命令解释器本身做的事情。

注意:我在Windows上运行,所以Ctrl+L不起作用。


当前回答

如果是在mac上,那么一个简单的cmd + k就可以了。

其他回答

好吧,这里有一个小窍门:

>>> clear = "\n" * 100
>>> print clear
>>> ...do some other stuff...
>>> print clear

或者为了节省一些输入,把这个文件放在你的python搜索路径中:

# wiper.py
class Wipe(object):
    def __repr__(self):
        return '\n'*1000

wipe = Wipe()

然后你可以从解释器做这一切你喜欢的:)

>>> from wiper import wipe
>>> wipe
>>> wipe
>>> wipe

正如你提到的,你可以做一个系统调用:

Windows:

>>> import os
>>> clear = lambda: os.system('cls')
>>> clear()

对于Linux,它将是:

>>> import os
>>> clear = lambda: os.system('clear')
>>> clear()

如果你在.inputrc中使用vim键绑定:

set editing-mode vi

它是:

ESC Ctrl-L

编辑:我刚刚读了“windows”,这是针对linux用户的,抱歉。


在bash中:

#!/bin/bash

while true; do
    clear
    "$@"
    while [ "$input" == "" ]; do
        read -p "Do you want to quit? (y/n): " -n 1 -e input
        if [ "$input" == "y" ]; then
            exit 1
        elif [ "$input" == "n" ]; then
            echo "Ok, keep working ;)"
        fi
    done
    input=""
done

保存为“whatyouwant.sh”,chmod +x然后运行:

./whatyouwant.sh python

或者python以外的东西(idle,随便什么)。 这将询问你是否真的想退出,如果不是,它将重新运行python(或你作为参数给出的命令)。

这将清除所有,屏幕和所有变量/对象/任何你在python中创建/导入的东西。

在python中,当你想退出时,只需输入exit()。

这应该是跨平台的,并且也使用首选的子流程。调用而不是os。系统按操作系统。系统文档。应该在Python >= 2.4中工作。

import subprocess
import os

if os.name == 'nt':
    def clearscreen():
        subprocess.call("cls", shell=True)
        return
else:
    def clearscreen():
        subprocess.call("clear", shell=True)
        return