今天在交互式下写代码(我的是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清除屏幕了
测试结果呢:
非常好!!!