是否存在任何标准的“附带电池”方法来清除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文件启动该文件。
其他回答
这将清除25个新行:
def clear():
print(' \n' * 25)
clear()
我在pydev中使用eclipse。我更喜欢换行解决方案比范围内的for num。for循环抛出警告,而打印换行符则不会。 如果您想在clear语句中指定换行数,请尝试此变体。
def clear(j):
print(' \n' * j)
clear(25)
您可以尝试使用clear,但它可能并非在所有Linux发行版上都可用。在windows上使用你提到的cls。
import subprocess
import platform
def clear():
subprocess.Popen( "cls" if platform.system() == "Windows" else "clear", shell=True)
clear()
注意:控制终端屏幕可能被认为是一种糟糕的形式。你在考虑使用期权吗?让用户自己决定是否要清除屏幕可能会更好。
对于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)。
清除屏幕的方法可能有些俗气,但在我所知的任何平台上都适用,如下:
for i in xrange(0,100):
print ""
对我来说,最优雅的说法是:
import os
os.system('cls||clear')
推荐文章
- 使用Pandas将列转换为行
- 从matplotlib中的颜色映射中获取单个颜色
- 将Pandas或Numpy Nan替换为None以用于MysqlDB
- 使用pandas对同一列进行多个聚合
- 使用Python解析HTML
- django MultiValueDictKeyError错误,我如何处理它
- 如何在for循环期间修改列表条目?
- 我如何在Django中创建一个鼻涕虫?
- 没有名为'django.core.urlresolvers'的模块
- 蟒蛇导出环境文件
- Django - makemigrations -未检测到任何更改
- SQLAlchemy:引擎、连接和会话差异
- 在Python Pandas中删除多个列中的所有重复行
- 更改pandas DataFrame中的特定列名
- 将Pandas多索引转换为列