是否存在任何标准的“附带电池”方法来清除Python脚本中的终端屏幕,或者我必须去诅咒(库,而不是单词)?


当前回答

你可以使用call()函数来执行终端的命令:

from subprocess import call
call("clear")

其他回答

从操作系统导入系统;系统(清晰的)”

这个函数在gnome-terminal中工作,因为默认情况下,它识别ANSI转义序列。它为您提供了一个到终端底部的CLEAN PROMPT rows_max距离,但也精确地从调用它的位置开始。让你完全控制要清除多少。

def clear(rows=-1, rows_max=None, *, calling_line=True, absolute=None,
          store_max=[]):
    """clear(rows=-1, rows_max=None)
clear(0, -1) # Restore auto-determining rows_max
clear(calling_line=False) # Don't clear calling line
clear(absolute=5) # Absolutely clear out to 5 rows up"""
    from os import linesep
    if rows_max and rows_max != -1:
        store_max[:] = [rows_max, False]
    elif not store_max or store_max[1] or rows_max == -1 or absolute:
        try:
            from shutil import get_terminal_size
            columns_max, rows_max = get_terminal_size()
        except ImportError:
            columns_max, rows_max = 80, 24
        if absolute is None:
            store_max[:] = [rows_max, True]
    if store_max:
        if rows == -1:
            rows = store_max[0]
        elif isinstance(rows, float):
            rows = round(store_max[0] * rows)
        if rows > store_max[0] - 2:
            rows = store_max[0] - 2
    if absolute is None:
        s = ('\033[1A' + ' ' * 30 if calling_line else '') + linesep * rows
    else:
        s = '\033[{}A'.format(absolute + 2) + linesep
        if absolute > rows_max - 2:
            absolute = rows_max - 2
        s += (' ' * columns_max + linesep) * absolute + ' ' * columns_max
        rows = absolute
    print(s + '\033[{}A'.format(rows + 1))

实现:

clear() # Clear all, TRIES to automatically get terminal height
clear(800, 24) # Clear all, set 24 as terminal (max) height
clear(12) # Clear half of terminal below if 24 is its height
clear(1000) # Clear to terminal height - 2 (24 - 2)
clear(0.5) # float factor 0.0 - 1.0 of terminal height (0.5 * 24 = 12)
clear() # Clear to rows_max - 2 of user given rows_max (24 - 2)
clear(0, 14) # Clear line, reset rows_max to half of 24 (14-2)
clear(0) # Just clear the line
clear(0, -1) # Clear line, restore auto-determining rows_max
clear(calling_line=False) # Clear all, don't clear calling line
clear(absolute=5) # Absolutely clear out to 5 rows up

Parameters: rows is the number of clear text rows to add between prompt and bottom of terminal, pushing everything up. rows_max is the height of the terminal (or max clearing height) in text rows, and only needs to be set once, but can be reset at any time. *, in the third parameter position means all following parameters are keyword only (e.g., clear(absolute=5)). calling_line=True (default) works better in Interactive mode. calling_line=False works better for text-based, terminal applications. absolute was added to try to fix glitchy gap problems in Interactive mode after reducing size of terminal, but can also be used for terminal applications. store_max is just for secret, "persistent" storage of rows_max value; don't explicitly use this parameter. (When an argument is not passed for store_max, changing the list contents of store_max changes this parameter's default value. Hence, persistent storage.)

可移植性:对不起,这在IDLE中不工作,但它在终端(控制台)识别ANSI转义序列的交互模式下工作>>非常酷。我只在Ubuntu 13.10中使用Python 3.3在gnome-terminal中测试了这个。因此,我只能假设可移植性依赖于Python 3.3(用于shutil.get_terminal_size()函数以获得最佳结果)和ANSI识别。print(…)函数是Python 3。我还用一个简单的、基于文本的终端Tic Tac Toe游戏(应用程序)测试了这一点。

在交互模式下使用:首先在交互模式下复制并粘贴copy(…)函数,看看它是否适合您。如果是,那么将上面的函数放到一个名为clear.py的文件中。在终端中启动python,使用'python3'。输入:

>>> import sys
>>> sys.path
['', '/usr/lib/python3.3', ...

现在,将clear.py文件放到列出的路径目录中,以便Python可以找到它(不要覆盖任何现有文件)。从现在开始容易使用:

>>> from clear import clear
>>> clear()
>>> print(clear.__doc__)
clear(rows=-1, rows_max=None)
clear(0, -1) # Restore auto-determining rows_max
clear(calling_line=False) # Don't clear calling line
clear(absolute=5) # Absolutely clear out to 5 rows up

在终端应用程序中使用:将copy(…)函数放入名为clear.py的文件中,与main.py文件放在同一个文件夹中。下面是一个来自Tic Tac Toe游戏应用程序的工作摘要(骨架)示例(从终端提示符:python3 tictactoe.py运行):

from os import linesep

class TicTacToe:    
    def __init__(self):
        # Clear screen, but not calling line
        try:
            from clear import clear
            self.clear = clear
            self.clear(calling_line=False)
        except ImportError:
            self.clear = False
        self.rows = 0    # Track printed lines to clear

        # ...
        self.moves = [' '] * 9

    def do_print(self, *text, end=linesep):
        text = list(text)
        for i, v in enumerate(text[:]):
            text[i] = str(v)
        text = ' '.join(text)
        print(text, end=end)
        self.rows += text.count(linesep) + 1

    def show_board(self):
        if self.clear and self.rows:
            self.clear(absolute=self.rows)
        self.rows = 0
        self.do_print('Tic Tac Toe')
        self.do_print('''   |   |
 {6} | {7} | {8}
   |   |
-----------
   |   |
 {3} | {4} | {5}
   |   |
-----------
   |   |
 {0} | {1} | {2}
   |   |'''.format(*self.moves))

    def start(self):
        self.show_board()
        ok = input("Press <Enter> to continue...")
        self.moves = ['O', 'X'] * 4 + ['O']
        self.show_board()
        ok = input("Press <Enter> to close.")

if __name__ == "__main__":
    TicTacToe().start()

Explanation: do_print(...) on line 19 is a version of print(...) needed to keep track of how many new lines have been printed (self.rows). Otherwise, you would have to self.rows += 1 all over the place where print(...) is called throughout the entire program. So each time the board is redrawn by calling show_board() the previous board is cleared out and the new board is printed exactly where it should be. Notice self.clear(calling_line=False) on line 9 basically pushes everything up RELATIVE to the bottom of the terminal, but does not clear the original calling line. In contrast, self.clear(absolute=self.rows) on line 29 absolutely clears out everything self.rows distance upward, rather than just pushing everything upward relative to the bottom of the terminal.

Ubuntu用户使用Python 3.3: Put #!/usr/bin/env python3在tictactoe.py文件的第一行。右击tictactoe.py file => Properties => Permissions tab => Check Execute:允许将文件作为程序执行。双击文件=>单击“终端运行”按钮。如果打开的终端的当前目录是tictactoe.py文件的目录,也可以使用。/tictactoe.py文件启动该文件。

在Windows中,您可以使用:

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

对于Windows, Mac和Linux,您可以使用以下代码:

import subprocess, platform

if platform.system()=="Windows":
    if platform.release() in {"10", "11"}:
        subprocess.run("", shell=True) #Needed to fix a bug regarding Windows 10; not sure about Windows 11
        print("\033c", end="")
    else:
        subprocess.run(["cls"])
else: #Linux and Mac
    print("\033c", end="")

jamesnotjim为Mac测试了打印(“\033c”,end=“”),我在Linux和Windows上测试了它(它不适用于Windows,因此调用cls的其他代码)。我不记得我第一次看到使用print("\033c")和/或printf版本:subprocess.run("printf '\033c'", shell=True)。

Rolika指出,end=""将阻止它随后打印新行。

注意,新版本的Ubuntu会很好地清除屏幕(不只是向下滚动,让它看起来是清除的),不像旧版本。

注意,用ESC c ("\033c")重置终端将使光标下划线并闪烁。如果你不想这样,你可以使用这些代码将其更改为另一种风格(在GNOME Terminal 3.44.0上测试,使用VTE 0.68 +BIDI +GNUTLS +ICU +SYSTEMD):

下划线闪烁:"\033[0 q" 块闪烁:"\033[1 q" 方块:"\033[2 q" 下划线闪烁:"\033[3 q" 下划线:"\033[4 q" 细条闪烁:“\033[5 q” 细条:"\033[6q "(大于6的数字似乎也是这样)

还要注意,你可以在Linux上做以下任何事情来清除屏幕:

print("\033c", end=""): print("\u001bc", end="") print("\U0000001bc", end="") print("\x1bc", end="") subprocess.run(["clear"]) #This doesn't reset the whole terminal subprocess.run('echo -ne "\033c"', shell=True) subprocess.run('echo -ne "\ec"', shell=True) subprocess.run('echo -ne "\u001bc"', shell=True) subprocess.run('echo -ne "\U0000001bc"', shell=True) subprocess.run('echo -ne "\x1bc"', shell=True) subprocess.run("printf '\033c'", shell=True) subprocess.run("printf '\ec'", shell=True) subprocess.run("printf '\u001bc'", shell=True) subprocess.run("printf '\U0000001bc'", shell=True) subprocess.run("printf '\x1bc'", shell=True)

我相信下面的代码应该是为了清除你必须向上滚动才能看到的内容(但它很难与另一个命令一起使用而没有问题):

打印('*)

这可以做和clear以前做的一样的事情(所以你可以向上滚动查看被删除的内容,除了它不会将光标上升到顶部):

打印('**)

一个纯Python解决方案。 不依赖于ANSI或外部命令。 只有您的终端必须能够告诉您视图中有多少行。

from shutil import get_terminal_size
print("\n" * get_terminal_size().lines, end='')

Python版本>= 3.3.0