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

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

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

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


当前回答

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

set editing-mode vi

它是:

ESC Ctrl-L

其他回答

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

import os

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

# now, to clear the screen
cls()

下面是一个跨平台(Windows / Linux / Mac /可能其他你可以添加在if检查)版本片段,我结合了这个问题中发现的信息:

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

同样的想法,但有一勺语法糖:

import subprocess   
clear = lambda: subprocess.call('cls||clear', shell=True)
clear()

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

>>> 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

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

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

用法很简单:

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

在Windows上有很多方法:

1. 使用键盘快捷键:

Press CTRL + L

2. 使用系统调用方法:

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

3.使用新行打印100次:

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