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

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

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

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


当前回答

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

import os

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

# now, to clear the screen
cls()

其他回答

我的方法是这样写一个函数:

import os
import subprocess

def clear():
    if os.name in ('nt','dos'):
        subprocess.call("cls")
    elif os.name in ('linux','osx','posix'):
        subprocess.call("clear")
    else:
        print("\n") * 120

然后调用clear()清除屏幕。 这适用于windows, osx, linux, bsd…所有的操作系统。

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

Wiper很酷,它的好处是我不需要在它周围输入'()' 这里有一些细微的变化

# wiper.py
import os
class Cls(object):
    def __repr__(self):
        os.system('cls')
        return ''

用法很简单:

>>> cls = Cls()
>>> cls # this will clear console.

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

>>> ' '*80*25

更新:80x25不太可能是控制台窗口的大小,所以要获得真正的控制台尺寸,使用从寻呼机模块的函数。Python没有提供任何与核心发行版类似的东西。

>>> from pager import getheight
>>> '\n' * getheight()