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

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

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

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


当前回答

我使用Spyder (Python 2.7)和清理我使用的解释器控制台

%明显

这迫使命令行跳转到顶部,我将看不到以前的旧命令。

或者我在控制台环境中单击“选项”并选择“重新启动内核”,这将删除所有内容。

其他回答

我发现最简单的方法就是关闭窗口并运行模块/脚本重新打开shell。

我在Windows XP, SP3上使用MINGW/BASH。

(在.pythonstartup中插入) #我的ctrl-l已经有点工作了,但这可能会帮助其他人 #在窗口底部留下提示符… 进口readline readline。parse_and_bind(“\价氯:清除屏幕”)

#这在BASH中工作,因为我在.inputrc中也有它,但对于一些 #当我进入Python时它被删除的原因 readline。parse_and_bind(“\ bxcy: kill-whole-line”)


我再也无法忍受输入“exit()”,并对马蒂诺/三联画的技巧感到高兴:

不过我稍微修改了一下(把它放在.pythonstartup中)

class exxxit():
    """Shortcut for exit() function, use 'x' now"""
    quit_now = exit # original object
    def __repr__(self):
        self.quit_now() # call original
x = exxxit()

Py2.7.1>help(x)
Help on instance of exxxit in module __main__:

class exxxit
 |  Shortcut for exit() function, use 'x' now
 |
 |  Methods defined here:
 |
 |  __repr__(self)
 |
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |
 |  quit_now = Use exit() or Ctrl-Z plus Return to exit

这里有一个最终的解决方案,它融合了所有其他的答案。特点:

您可以将代码复制粘贴到shell或脚本中。 你可以随心所欲地使用它: > > > clear () > > >明确 >>> clear # <-但这只适用于shell 你可以把它作为一个模块导入: >>> from clear import clear > > >明确 你可以调用它作为一个脚本: $ python clear.py 它是真正的多平台游戏;如果它不能识别你的系统 (ce, nt, DOS或posix),它将回落到打印空白行。


你可以在这里下载[完整]文件:https://gist.github.com/3130325 或者如果你只是在寻找代码:

class clear:
 def __call__(self):
  import os
  if os.name==('ce','nt','dos'): os.system('cls')
  elif os.name=='posix': os.system('clear')
  else: print('\n'*120)
 def __neg__(self): self()
 def __repr__(self):
  self();return ''

clear=clear()

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

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…所有的操作系统。

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

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

用法很简单:

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