像大多数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()擦除整个终端缓冲区

其他回答

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

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

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

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:

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

对于Linux,它将是:

>>> import os
>>> clear = lambda: os.system('clear')
>>> clear()

这里有两种很好的方法:

1.

import os

# Clear Windows command prompt.
if (os.name in ('ce', 'nt', 'dos')):
    os.system('cls')

# Clear the Linux terminal.
elif ('posix' in os.name):
    os.system('clear')

2.

import os

def clear():
    if os.name == 'posix':
        os.system('clear')

    elif os.name in ('ce', 'nt', 'dos'):
        os.system('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