今天在交互式下寫代碼(我的是Python37),一大堆,想清除shell里面的東西讓IDLE看起來更簡潔,百度來了幾種方法,都測試了一下:
1、使用os模塊
import os
os.system("clear")#Linux下
os.system("cls")#Windows下
然而測試結果如下:

2、使用subprocess模塊
import subprocess
subprocess.call("clear")#Linux下
subprocess.call("cls", shell=True)#Windows下
測試結果如下:

3、首先下載一個clearwindow.py(https://bugs.python.org/issue6143),保存到python安裝目錄PythonX/Lib/idlelib目錄下,如果懶得下載,可以自己復制下面的代碼,保存為clearwindow.py文件即可,注意,一定是要保存在剛剛的目錄下:
"""
Clear Window Extension
Version: 0.1
Author: Roger D. Serwy
roger.serwy@gmail.com
Date: 2009-05-22
It provides "Clear Shell Window" under "Options"
Add these lines to config-extensions.def
[ClearWindow]
enable=1
enable_editor=0
enable_shell=1
[ClearWindow_cfgBindings]
clear-window=<Control-Key-l>
"""
class ClearWindow:
menudefs = [
('options', [None,
('Clear Shell Window', '<<clear-window>>'),
]),]
def __init__(self, editwin):
self.editwin = editwin
self.text = self.editwin.text
self.text.bind("<<clear-window>>", self.clear_window)
def clear_window2(self, event): # Alternative method
# work around the ModifiedUndoDelegator
text = self.text
text.mark_set("iomark2", "iomark")
text.mark_set("iomark", 1.0)
text.delete(1.0, "iomark2 linestart")
text.mark_set("iomark", "iomark2")
text.mark_unset("iomark2")
if self.text.compare('insert', '<', 'iomark'):
self.text.mark_set('insert', 'end-1c')
self.editwin.set_line_and_column()
def clear_window(self, event):
# remove undo delegator
undo = self.editwin.undo
self.editwin.per.removefilter(undo)
# clear the window, but preserve current command
self.text.delete(1.0, "iomark linestart")
if self.text.compare('insert', '<', 'iomark'):
self.text.mark_set('insert', 'end-1c')
self.editwin.set_line_and_column()
# restore undo delegator
self.editwin.per.insertfilter(undo)
然后打開在剛才的目錄下找到config-extensions.def這個文件(idle擴展的配置文件),以記事本的方式打開它(為防止出錯,你可以在打開它之前先copy一個備份),在文件的后面加上這樣一段代碼:
[ClearWindow] enable=1 enable_editor=0 enable_shell=1 [ClearWindow_cfgBindings] clear-window=<Control-Key-D>#這是快捷鍵,自己設置,設置好之后就可以用Ctrl+D清除屏幕了
測試結果呢:
非常好!!!
