在shell中清除屏幕

jos*_*osh 71 python shell screen clear

只是一个简单的问题:
如何清除外壳中的屏幕?我见过这样的方式:

import os
os.system('cls')
Run Code Online (Sandbox Code Playgroud)

这只是打开窗口cmd,清除屏幕并关闭但我希望清除shell窗口
(PS:我不知道这有帮助,但我使用的是3.3.2版本的Python)
谢谢:)

Sha*_*fiq 74

快捷方式CTRL+ L怎么样?

它适用于所有shell,例如Python,Bash,MySQL,MATLAB等.

  • ctrl + l你每天都学到一些东西.这非常有用. (7认同)
  • 不幸的是,在Windows10中(包括Windows10中的新cmd)无法使用 (3认同)

Raj*_*nka 50

import os

os.system('cls')  # For Windows
os.system('clear')  # For Linux/OS X
Run Code Online (Sandbox Code Playgroud)


小智 48

对于OS X,您可以使用子进程模块并从shell调用'cls':

import subprocess as sp
sp.call('cls',shell=True)
Run Code Online (Sandbox Code Playgroud)

要防止"0"显示在窗口顶部,请将第二行替换为:

tmp = sp.call('cls',shell=True)
Run Code Online (Sandbox Code Playgroud)

对于linux,你必须用cls命令替换命令clear

tmp = sp.call('clear',shell=True)
Run Code Online (Sandbox Code Playgroud)

  • 试试这个`ctrl + L` (9认同)
  • 我正在使用Mac OS X,我试过这个`import subprocess as sp sp.call('clear',shell = True)`,它起作用,除了终端窗口顶部有一个"0". (3认同)

Ste*_*nes 11

您正在寻找的那种东西可以在curses模块中找到.

import curses  # Get the module
stdscr = curses.initscr()  # initialise it
stdscr.clear()  # Clear the screen
Run Code Online (Sandbox Code Playgroud)

重要的提示

要记住的重要事项是在任何退出之前,您需要将终端重置为正常模式,这可以通过以下行完成:

curses.nocbreak()
stdscr.keypad(0)
curses.echo()
curses.endwin()
Run Code Online (Sandbox Code Playgroud)

如果你不这样做,你会得到各种奇怪的行为.为了确保始终如此,我建议使用atexit模块,例如:

import atexit

@atexit.register
def goodbye():
    """ Reset terminal from curses mode on exit """
    curses.nocbreak()
    if stdscr:
        stdscr.keypad(0)
    curses.echo()
    curses.endwin()
Run Code Online (Sandbox Code Playgroud)

可能会做得很好.


Vla*_*den 9

这是您可以在Windows上使用的一些选项

第一种选择:

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

>>> cls()
Run Code Online (Sandbox Code Playgroud)

第二种选择:

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

>>> cls()
Run Code Online (Sandbox Code Playgroud)

如果您在Python REPL窗口中,则是第三个选项:

Ctrl+L
Run Code Online (Sandbox Code Playgroud)


Mar*_*gur 8

除了是一个全面的优秀CLI库之外,click还提供了与平台无关的clear()功能:

import click
click.clear()
Run Code Online (Sandbox Code Playgroud)


小智 6

在 python 中清除屏幕的一种更简单的方法是使用Ctrl+L尽管它适用于 shell 以及其他程序。


ePi*_*314 5

此功能适用于任何操作系统(Unix,Linux,OS X和Windows)
Python 2和Python 3

import platform    # For getting the operating system name
import subprocess  # For executing a shell command

def clear_screen():
    """
    Clears the terminal screen.
    """

    # Clear command as function of OS
    command = "cls" if platform.system().lower()=="windows" else "clear"

    # Action
    return subprocess.call(command) == 0
Run Code Online (Sandbox Code Playgroud)

在Windows中,命令是cls,在类似unix的系统中,命令是clear.
platform.system()返回平台名称.防爆.'Darwin'在OS X中
subprocess.call()执行系统调用.防爆.subprocess.call(['ls','-l'])