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

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

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

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


当前回答

这应该是跨平台的,并且也使用首选的子流程。调用而不是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

其他回答

完美的cls,也兼容Python2(在.pythonrc文件中):

from __future__ import print_function
cls = lambda: print("\033c", end='')

并且可以通过如下方式从终端调用:

cls()

或直接:

print("\033c", end='')

\033[H\033] J只清除可见屏幕,与Ubuntu 18.10之前的清除命令完全相同。它不清除滚动缓冲区。向上滚动将显示历史。

为了模拟这种行为,插入一些终端行,然后按Ctrl+L并插入更多。执行打印("\033[H\033[J", end="")后,只会删除按"Ctrl + L"后插入的屏幕行。

\033c清除一切。

\x1bc可能不会给出与\033c相同的结果,因为十六进制转义没有明确的长度限制。

这里有一些更方便的跨平台的东西

import os

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

# now, to clear the screen
cls()

编辑:我刚刚读了“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()。

在Windows上有很多方法:

1. 使用键盘快捷键:

Press CTRL + L

2. 使用系统调用方法:

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

3.使用新行打印100次:

cls = lambda: print('\n'*100)
cls()

这应该是跨平台的,并且也使用首选的子流程。调用而不是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