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


当前回答

一个简单的跨平台解决方案是在Windows上使用cls命令,或者在Unix系统上使用clear命令。与os连用系统,这是一个很好的一行:

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

其他回答

您可以对terminfo数据库进行分解,但这样做的函数无论如何都是在curses中。

如果您使用的是Linux/UNIX系统,那么打印ANSI转义序列以清除屏幕就可以了。您还需要将光标移动到屏幕的顶部。这将在任何支持ANSI的终端上工作。

import sys
sys.stderr.write("\x1b[2J\x1b[H")

这将不能在Windows上工作,除非ANSI支持已启用。Windows可能有一个等效的控制序列,但我不知道。

对于Windows,只能在解释器命令行上(而不是GUI)!简单的类型: (记住在python中使用适当的缩进):

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

每次在shell(命令行)上输入clear(),它都会清除shell上的屏幕。如果退出shell,那么在打开新的Python(命令行)shell时,必须重新执行上述操作。

注意:无论你使用的是哪个版本的Python,明确地(2.5、2.7、3.3和3.4)。

一个简单的跨平台解决方案是在Windows上使用cls命令,或者在Unix系统上使用clear命令。与os连用系统,这是一个很好的一行:

import os
os.system('cls' if os.name == 'nt' else '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文件启动该文件。