How to clear the interpreter console?

2018-12-31 08:56发布

Like most Python developers, I typically keep a console window open with the Python interpreter running to test commands, dir() stuff, help() stuff, etc.

Like any console, after a while the visible backlog of past commands and prints gets to be cluttered, and sometimes confusing when re-running the same command several times. I'm wondering if, and how, to clear the Python interpreter console.

I've heard about doing a system call and either calling cls on Windows or clear on Linux, but I was hoping there was something I could command the interpreter itself to do.

Note: I'm running on Windows, so Ctrl+L doesn't work.

30条回答
明月照影归
2楼-- · 2018-12-31 09:10

Just enter

import os
os.system('cls') # Windows
os.system('clear') # Linux, Unix, Mac OS X
查看更多
低头抚发
3楼-- · 2018-12-31 09:10

Wiper is cool, good thing about it is I don't have to type '()' around it. Here is slight variation to it

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

The usage is quite simple:

>>> cls = Cls()
>>> cls # this will clear console.
查看更多
余欢
4楼-- · 2018-12-31 09:12

I might be late to the part but here is a very easy way to do it

Type:

def cls():
    os.system("cls")

So what ever you want to clear the screen just type in your code

cls()

Best way possible! (Credit : https://www.youtube.com/watch?annotation_id=annotation_3770292585&feature=iv&src_vid=bguKhMnvmb8&v=LtGEp9c6Z-U)

查看更多
无与为乐者.
5楼-- · 2018-12-31 09:13
>>> ' '*80*25

UPDATE: 80x25 is unlikely to be the size of console windows, so to get the real console dimensions, use functions from pager module. Python doesn't provide anything similar from core distribution.

>>> from pager import getheight
>>> '\n' * getheight()
查看更多
春风洒进眼中
6楼-- · 2018-12-31 09:13

Use idle. It has many handy features. Ctrl+F6, for example, resets the console. Closing and opening the console are good ways to clear it.

查看更多
临风纵饮
7楼-- · 2018-12-31 09:15

I'm not sure if Windows' "shell" supports this, but on Linux:

print "\033[2J"

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

In my opinion calling cls with os is a bad idea generally. Imagine if I manage to change the cls or clear command on your system, and you run your script as admin or root.

查看更多
登录 后发表回答