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

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

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

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


当前回答

Arch Linux(使用Python 3在xfce4-terminal中测试):

# Clear or wipe console (terminal):
# Use: clear() or wipe()

import os

def clear():
    os.system('clear')

def wipe():
    os.system("clear && printf '\e[3J'")

... 添加到~/.pythonrc

Clear()清除屏幕 Wipe()擦除整个终端缓冲区

其他回答

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

import os

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

# now, to clear the screen
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

下面是一个跨平台(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()

我不确定Windows的“shell”是否支持这个,但在Linux上:

打印”033年\ [2 j”

https://en.wikipedia.org/wiki/ANSI_escape_code#CSI_codes

在我看来,用os调用cls通常是一个坏主意。想象一下,如果我设法更改系统上的cls或clear命令,而您以管理员或根用户身份运行脚本。

上面提到的魔术字符串-我相信它们来自terminfo数据库:

http://www.google.com/?q=x#q=terminfo

http://www.google.com/?q=x#q=tput+command+in+unix

$ tput clear| od -t x1z
0000000 1b 5b 48 1b 5b 32 4a                             >.[H.[2J<
0000007