如何清除解释器控制台?

问题:如何清除解释器控制台?

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

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

我听说过要进行系统调用,然后cls在Windows或clearLinux 上进行调用,但是我希望可以命令解释器自己执行一些操作。

注意:我在Windows上运行,因此Ctrl+L无法正常工作。

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.


回答 0

如前所述,您可以进行系统调用:

对于Windows

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

对于Linux,lambda变为

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

As you mentioned, you can do a system call:

For Windows

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

For Linux the lambda becomes

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

回答 1

这里有一些方便的东西,它是跨平台的

import os

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

# now, to clear the screen
cls()

here something handy that is a little more cross-platform

import os

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

# now, to clear the screen
cls()

回答 2

好吧,这是一个快速的技巧:

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

Well, here’s a quick hack:

>>> clear = "\n" * 100
>>> print clear
>>> ...do some other stuff...
>>> print clear

Or to save some typing, put this file in your python search path:

# wiper.py
class Wipe(object):
    def __repr__(self):
        return '\n'*1000

wipe = Wipe()

Then you can do this from the interpreter all you like :)

>>> from wiper import wipe
>>> wipe
>>> wipe
>>> wipe

回答 3

尽管这是一个比较老的问题,但我认为我会提供一些建议,总结我认为是其他最佳答案的建议,并建议您将这些命令放入文件并设置PYTHONSTARTUP,以增加我的见识。环境变量指向它。由于我目前在Windows上,因此这种方式略有偏差,但很容易将其向其他方向倾斜。

我发现这里有一些文章描述了如何在Windows上设置环境变量:
    什么时候使用sys.path.append以及何时修改%PYTHONPATH%就足够了
    如何在Windows XP中管理环境变量
    配置系统和用户环境变量
    如何使用全局系统Windows中的环境变量

顺便说一句,即使文件中有空格,也不要在文件的路径两边加上引号。

无论如何,这是我放入(或添加到现有的)Python启动脚本中的代码的看法:

# ==== pythonstartup.py ====

# add something to clear the screen
class cls(object):
    def __repr__(self):
        import os
        os.system('cls' if os.name == 'nt' else 'clear')
        return ''

cls = cls()

# ==== end pythonstartup.py ====

顺便说一句,您也可以使用@ Triptych的 __repr__技巧将其更改exit()为just exit(别名也同上quit):

class exit(object):
    exit = exit # original object
    def __repr__(self):
        self.exit() # call original
        return ''

quit = exit = exit()

最后,这是将主解释程序提示从更改>>>cwd +的其他方法>>>

class Prompt:
    def __str__(self):
        import os
        return '%s >>> ' % os.getcwd()

import sys
sys.ps1 = Prompt()
del sys
del Prompt

Although this is an older question, I thought I’d contribute something summing up what I think were the best of the other answers and add a wrinkle of my own by suggesting that you put these command(s) into a file and set your PYTHONSTARTUP environment variable to point to it. Since I’m on Windows at the moment, it’s slightly biased that way, but could easily be slanted some other direction.

Here’s some articles I found that describe how to set environment variables on Windows:
    When to use sys.path.append and when modifying %PYTHONPATH% is enough
    How To Manage Environment Variables in Windows XP
    Configuring System and User Environment Variables
    How to Use Global System Environment Variables in Windows

BTW, don’t put quotes around the path to the file even if it has spaces in it.

Anyway, here’s my take on the code to put in (or add to your existing) Python startup script:

# ==== pythonstartup.py ====

# add something to clear the screen
class cls(object):
    def __repr__(self):
        import os
        os.system('cls' if os.name == 'nt' else 'clear')
        return ''

cls = cls()

# ==== end pythonstartup.py ====

BTW, you can also use @Triptych’s __repr__ trick to change exit() into just exit (and ditto for its alias quit):

class exit(object):
    exit = exit # original object
    def __repr__(self):
        self.exit() # call original
        return ''

quit = exit = exit()

Lastly, here’s something else that changes the primary interpreter prompt from >>> to cwd+>>>:

class Prompt:
    def __str__(self):
        import os
        return '%s >>> ' % os.getcwd()

import sys
sys.ps1 = Prompt()
del sys
del Prompt

回答 4

在Windows上,您可以采用多种方法:

1.使用键盘快捷键:

Press CTRL + L

2.使用系统调用方法:

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

3.使用换行打印100次:

cls = lambda: print('\n'*100)
cls()

You have number of ways doing it on Windows:

1. Using Keyboard shortcut:

Press CTRL + L

2. Using system invoke method:

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

3. Using new line print 100 times:

cls = lambda: print('\n'*100)
cls()

回答 5

毫无疑问,最快,最简单的方法是Ctrl+ L

对于终端上的OS X,这是相同的。

Quickest and easiest way without a doubt is Ctrl+L.

This is the same for OS X on the terminal.


回答 6

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

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 …所有操作系统。

my way of doing this is to write a function like so:

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

then call clear() to clear the screen. this works on windows, osx, linux, bsd… all OSes.


回答 7

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

Here’s a cross platform (Windows / Linux / Mac / Probably others that you can add in the if check) version snippet I made combining information found in this question:

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

Same idea but with a spoon of syntactic sugar:

import subprocess   
clear = lambda: subprocess.call('cls||clear', shell=True)
clear()

回答 8

刮水器很酷,关于它的好处是我不必在其周围键入’()’。这是它的细微变化

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

用法很简单:

>>> cls = Cls()
>>> cls # this will clear console.

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.

回答 9

这是您可以做的最简单的事情,不需要任何其他库。它将清除屏幕并返回>>>到左上角。

print("\033[H\033[J")

This is the simplest thing you can do and it doesn’t require any additional libraries. It will clear the screen and return >>> to the top left corner.

print("\033[H\033[J")

回答 10

对于python控制台类型内的mac用户

import os
os.system('clear')

用于窗户

os.system('cls')

for the mac user inside the python console type

import os
os.system('clear')

for windows

os.system('cls')

回答 11

这是合并所有其他答案的最终解决方案。特征:

  1. 您可以代码复制粘贴到您的shell或脚本中。
  2. 您可以根据需要使用它:

    >>> clear()
    >>> -clear
    >>> clear  # <- but this will only work on a shell
  3. 您可以其作为模块导入

    >>> from clear import clear
    >>> -clear
  4. 您可以其称为脚本:

    $ python clear.py
  5. 它是真正的多平台 ; 如果它不能识别系统
    centdosposix)将回落到打印空白行。


您可以在此处下载[full]文件:https//gist.github.com/3130325
或如果您只是在寻找代码:

class clear:
 def __call__(self):
  import os
  if os.name==('ce','nt','dos'): os.system('cls')
  elif os.name=='posix': os.system('clear')
  else: print('\n'*120)
 def __neg__(self): self()
 def __repr__(self):
  self();return ''

clear=clear()

Here’s the definitive solution that merges all other answers. Features:

  1. You can copy-paste the code into your shell or script.
  2. You can use it as you like:

    >>> clear()
    >>> -clear
    >>> clear  # <- but this will only work on a shell
    
  3. You can import it as a module:

    >>> from clear import clear
    >>> -clear
    
  4. You can call it as a script:

    $ python clear.py
    
  5. It is truly multiplatform; if it can’t recognize your system
    (ce, nt, dos or posix) it will fall back to printing blank lines.


You can download the [full] file here: https://gist.github.com/3130325
Or if you are just looking for the code:

class clear:
 def __call__(self):
  import os
  if os.name==('ce','nt','dos'): os.system('cls')
  elif os.name=='posix': os.system('clear')
  else: print('\n'*120)
 def __neg__(self): self()
 def __repr__(self):
  self();return ''

clear=clear()

回答 12

我使用iTerm和Mac OS的本机终端应用程序。

我只要按⌘+ k

I use iTerm and the native terminal app for Mac OS.

I just press ⌘ + k


回答 13

使用空闲。它具有许多方便的功能。 Ctrl+F6,例如,重置控制台。关闭和打开控制台是清除它的好方法。

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.


回答 14

我不确定Windows的“ shell”是否支持此功能,但是在Linux上:

print "\033[2J"

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

在我看来,cls与通话os通常是一个坏主意。想象一下,如果我设法更改系统上的cls或clear命令,并且您以admin或root身份运行脚本。

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.


回答 15

我在Windows XP SP3上使用MINGW / BASH。

(在.pythonstartup坚持这一点)
#我CTRL-L已经样的工作,但是这可能帮助别人
#树叶窗口虽然…的底部提示
导入的ReadLine
readline.parse_and_bind(“氯\:清屏”)

#这在BASH中有效,因为我也在.inputrc中也有它,但是由于某些
原因,当我进入Python
readline 时它被丢弃了(’\ Cy:kill-whole-line’)


我再也无法忍受键入’exit()’了,对martineau / Triptych的把戏感到满意:

我虽然稍加修改(将其粘贴在.pythonstartup中)

class exxxit():
    """Shortcut for exit() function, use 'x' now"""
    quit_now = exit # original object
    def __repr__(self):
        self.quit_now() # call original
x = exxxit()

Py2.7.1>help(x)
Help on instance of exxxit in module __main__:

class exxxit
 |  Shortcut for exit() function, use 'x' now
 |
 |  Methods defined here:
 |
 |  __repr__(self)
 |
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |
 |  quit_now = Use exit() or Ctrl-Z plus Return to exit

I’m using MINGW/BASH on Windows XP, SP3.

(stick this in .pythonstartup)
# My ctrl-l already kind of worked, but this might help someone else
# leaves prompt at bottom of the window though…
import readline
readline.parse_and_bind(‘\C-l: clear-screen’)

# This works in BASH because I have it in .inputrc as well, but for some
# reason it gets dropped when I go into Python
readline.parse_and_bind(‘\C-y: kill-whole-line’)


I couldn’t stand typing ‘exit()’ anymore and was delighted with martineau’s/Triptych’s tricks:

I slightly doctored it though (stuck it in .pythonstartup)

class exxxit():
    """Shortcut for exit() function, use 'x' now"""
    quit_now = exit # original object
    def __repr__(self):
        self.quit_now() # call original
x = exxxit()

Py2.7.1>help(x)
Help on instance of exxxit in module __main__:

class exxxit
 |  Shortcut for exit() function, use 'x' now
 |
 |  Methods defined here:
 |
 |  __repr__(self)
 |
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |
 |  quit_now = Use exit() or Ctrl-Z plus Return to exit

回答 16

clearLinux和clsWindows中的OS命令输出一个“魔术字符串”,您可以直接打印该字符串。要获取字符串,请使用popen执行命令并将其保存在变量中以备后用:

from os import popen
with popen('clear') as f:
    clear = f.read()

print clear

在我的机器上,字符串是'\x1b[H\x1b[2J'

The OS command clear in Linux and cls in Windows outputs a “magic string” which you can just print. To get the string, execute the command with popen and save it in a variable for later use:

from os import popen
with popen('clear') as f:
    clear = f.read()

print clear

On my machine the string is '\x1b[H\x1b[2J'.


回答 17

这是两种不错的方法:

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

Here are two nice ways of doing that:

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

回答 18

如果是在Mac上,那么一个简单的方法cmd + k就可以解决问题。

If it is on mac, then a simple cmd + k should do the trick.


回答 19

最简单的方法是使用os模块

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

The easiest way is to use os module

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

回答 20

这应该是跨平台的,并且还使用所述优选的subprocess.call,而不是os.systemos.system文档。应该适用于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

This should be cross platform, and also uses the preferred subprocess.call instead of os.system as per the os.system docs. Should work in 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

回答 21

这样清楚吗

- os.system('cls')

那大约是尽可能的短!

How about this for a clear

- os.system('cls')

That is about as short as could be!


回答 22

我是python的新手(真的很新),在我读的一本书中,他们熟悉该语言,他们教他们如何创建此小功能来清除控制台的可见积压以及过去的命令和打印内容:

打开外壳程序/创建新文档/创建函数,如下所示:

def clear():
    print('\n' * 50)

将其保存在python目录中的lib文件夹中(我的文件夹为C:\ Python33 \ Lib)。下次您需要清除控制台时,只需使用以下函数调用该函数:

clear()

而已。PS:您可以随意命名自己的功能。我见过人们使用“雨刮器”,“擦拭”和其他形式。

I’m new to python (really really new) and in one of the books I’m reading to get acquainted with the language they teach how to create this little function to clear the console of the visible backlog and past commands and prints:

Open shell / Create new document / Create function as follows:

def clear():
    print('\n' * 50)

Save it inside the lib folder in you python directory (mine is C:\Python33\Lib) Next time you nedd to clear your console just call the function with:

clear()

that’s it. PS: you can name you function anyway you want. Iv’ seen people using “wiper” “wipe” and variations.


回答 23

我正在使用Spyder(Python 2.7),并且要清洁解释器控制台,请使用

%明确

迫使命令行转到顶部,而我不会看到以前的旧命令。

或在控制台环境中单击“选项”,然后选择“ Restart kernel”(删除所有内容)。

I am using Spyder (Python 2.7) and to clean the interpreter console I use either

%clear

that forces the command line to go to the top and I will not see the previous old commands.

or I click “option” on the Console environment and select “Restart kernel” that removes everything.


回答 24

我可能迟到了,但这是一个很简单的方法

类型:

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

所以只要您想输入清除代码的内容

cls()

最好的方法!(信用:https : //www.youtube.com/watch?annotation_id=annotation_3770292585&feature=iv&src_vid=bguKhMnvmb8&v=LtGEp9c6Z-U

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)


回答 25

只需输入

import os
os.system('cls') # Windows
os.system('clear') # Linux, Unix, Mac OS X

Just enter

import os
os.system('cls') # Windows
os.system('clear') # Linux, Unix, Mac OS X

回答 26

如果您不需要通过代码完成操作,只需按CTRL + L

If you don’t need to do it through code, just press CTRL+L


回答 27

Arch Linux(已在xfce4-terminalPython 3中测试):

# 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() 擦除整个终端缓冲区

Arch Linux (tested in xfce4-terminal with Python 3):

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

import os

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

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

… added to ~/.pythonrc

  • clear() clears screen
  • wipe() wipes entire terminal buffer

回答 28

编辑:我刚刚读过“ Windows”,这是给Linux用户的,抱歉。


在bash中:

#!/bin/bash

while [ "0" == "0" ]; do
    clear
    $@
    while [ "$input" == "" ]; do
        read -p "Do you want to quit? (y/n): " -n 1 -e input
        if [ "$input" == "y" ]; then
            exit 1
        elif [ "$input" == "n" ]; then
            echo "Ok, keep working ;)"
        fi
    done
    input=""
done

将其保存为“ whatyouwant.sh”,chmod + x然后运行:

./whatyouwant.sh python

或python以外的其他东西(空闲等)。这将询问您是否确实要退出,如果不是,则重新运行python(或您作为参数给出的命令)。

这将清除所有,屏幕以及您在python中创建/导入的所有变量/对象/所有内容。

在python中,当您要退出时只需键入exit()即可。

EDIT: I’ve just read “windows”, this is for linux users, sorry.


In bash:

#!/bin/bash

while [ "0" == "0" ]; do
    clear
    $@
    while [ "$input" == "" ]; do
        read -p "Do you want to quit? (y/n): " -n 1 -e input
        if [ "$input" == "y" ]; then
            exit 1
        elif [ "$input" == "n" ]; then
            echo "Ok, keep working ;)"
        fi
    done
    input=""
done

Save it as “whatyouwant.sh”, chmod +x it then run:

./whatyouwant.sh python

or something other than python (idle, whatever). This will ask you if you actually want to exit, if not it rerun python (or the command you gave as parameter).

This will clear all, the screen and all the variables/object/anything you created/imported in python.

In python just type exit() when you want to exit.


回答 29

好的,所以这是一个技术性较差的答案,但是我使用的是Notepad ++的Python插件,事实证明,您可以通过右键单击控制台并单击“清除”来手动清除控制台。希望这可以帮助某人!

OK, so this is a much less technical answer, but I’m using the Python plugin for Notepad++ and it turns out you can just clear the console manually by right-clicking on it and clicking “clear”. Hope this helps someone out there!