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


当前回答

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

其他回答

如果您希望在使用python shell时清除您的终端。然后,您可以执行以下操作清除屏幕

import os
os.system('clear')

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

这个函数在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文件启动该文件。

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

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

Python版本>= 3.3.0

我将这样做,使它看起来更像bash:

只需在主目录下创建一个名为.pythonstartup的文件,并在函数中使用poke的答案

在Linux上:

echo "from subprocess import call
def clear(int=None):  
    call('clear')
    if int == 0:
       exit()
clear()" >> $HOME/.pythonstartup ; export PYTHONSTARTUP=$HOME/.pythonstartup ; python

您可以添加export PYTHONSTARTUP=$HOME/。Pythonstartup到你的。/bashrc文件

因为我关心的是空间;调用该函数将不会在启动时显示python解释器描述,但您可以删除clear()以保留它。

像使用普通函数一样使用它应该不会打印退出状态:

>>> clear()

如果您将参数0传递给函数,它将清除屏幕并成功退出,因此您可以在干净的屏幕中继续使用shell

>>> clear(0)