是否存在任何标准的“附带电池”方法来清除Python脚本中的终端屏幕,或者我必须去诅咒(库,而不是单词)?
当前回答
这个函数在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文件启动该文件。
其他回答
您可以尝试使用clear,但它可能并非在所有Linux发行版上都可用。在windows上使用你提到的cls。
import subprocess
import platform
def clear():
subprocess.Popen( "cls" if platform.system() == "Windows" else "clear", shell=True)
clear()
注意:控制终端屏幕可能被认为是一种糟糕的形式。你在考虑使用期权吗?让用户自己决定是否要清除屏幕可能会更好。
只使用:
print("\033c")
这将清除终端窗口。
公认的答案是一个很好的解决方案。问题是,到目前为止,它只适用于Windows 10, Linux和Mac。是的,Windows(以缺乏ANSI支持而闻名)!这个新功能是在Windows 10(及以上版本)上实现的,它包括ANSI支持,尽管你必须启用它。这将以跨平台的方式清除屏幕:
import os
print ('Hello World')
os.system('')
print ("\x1B[2J")
在任何低于Windows 10的系统上,它会返回这个:
[2J
这是由于在以前的Windows版本中缺乏ANSI支持。但是,可以使用colorama模块来解决这个问题。这增加了对Windows上ANSI字符的支持:
在Unix和mac上,ANSI转义字符序列长期用于生成彩色终端文本和光标定位。Colorama也在Windows上实现了这一点,它通过包装stdout,剥离它找到的ANSI序列(在输出中作为官书),并将它们转换为适当的win32调用来修改终端的状态。在其他平台上,Colorama什么都不做。
这里有一个跨平台的方法:
import sys
if sys.platform == 'win32':
from colorama import init
init()
print('Hello World')
print("\x1B[2J")
或者用print(chr(27) + "[2J")代替print("\x1B[2J")。
@poke的答案在Windows上是非常不安全的,是的,它可以工作,但它真的是一个黑客。与脚本在同一字典中的名为“cls.bat”或“cls.exe”的文件将与命令发生冲突,并执行该文件而不是命令,从而产生巨大的安全隐患。
一个最小化风险的方法是改变cls命令被调用的位置:
import os
os.system('cd C:\\Windows|cls' if os.name == 'nt' else 'clear')
这将把Currant Dictionary更改为C:\Window(这里反斜杠很重要),然后执行。C:\Windows始终存在,需要管理权限才能在那里写入,这使得它适合以最小的风险执行此命令。另一种解决方案是通过PowerShell而不是命令提示符运行命令,因为PowerShell已经防范了此类漏洞。
在这个问题中还提到了其他方法:在shell中清除屏幕,这也可能是有用的。
这适用于所有平台,并且在Python 2和3中都有效。
def clear(number):
for i in range(number):
print(" ")
然后输入clear(numberhere)来清除。
您可以对terminfo数据库进行分解,但这样做的函数无论如何都是在curses中。
推荐文章
- Numpy Max vs amax vs maximum
- 我应该在.gitignore文件中添加Django迁移文件吗?
- 每n行有熊猫
- 实例属性attribute_name定义在__init__之外
- 如何获取在Python中捕获的异常的名称?
- 第一次出现的值大于现有值的Numpy
- 如何从Python函数中返回两个值?
- 前一个月的Python日期
- Python中方括号括起来的列表和圆括号括起来的列表有什么区别?
- Python日志记录不输出任何东西
- 每n秒运行特定代码
- SQLAlchemy是否有与Django的get_or_create等价的函数?
- 如何将python datetime转换为字符串,具有可读格式的日期?
- 美丽的汤和提取div及其内容的ID
- 在Python中重置生成器对象