【发布时间】:2011-01-06 06:29:59
【问题描述】:
是否存在任何标准的“附带电池”方法来从 Python 脚本中清除终端屏幕,或者我必须去诅咒(库,而不是单词)?
【问题讨论】:
-
我会检查 Windows 并使用“cls”,然后无条件地为所有内容执行
clear,因为这可能涵盖大多数情况。请参阅相关问题How to clear python interpreter console?。
是否存在任何标准的“附带电池”方法来从 Python 脚本中清除终端屏幕,或者我必须去诅咒(库,而不是单词)?
【问题讨论】:
clear,因为这可能涵盖大多数情况。请参阅相关问题How to clear python interpreter console?。
一个简单的跨平台解决方案是在 Windows 上使用 cls 命令,在 Unix 系统上使用 clear。与os.system 一起使用,这是一个不错的单线:
import os
os.system('cls' if os.name == 'nt' else 'clear')
【讨论】:
os.system 的字符串都是固定的。
clear 和 cls 都这样做)时,您会运行整个过程:print("\n" * 100) 跨度>
cls不 只是打印空行。它显式清除控制台缓冲区,因此它不等同于打印任何数量的空白。此外,对于“明显错误”的代码,该代码运行得非常好。您可能不喜欢它,但这并没有错(更不用说 Windows 上的 cls 不是进程,而是控制台主机的功能,例如 cmd.exe 或 PowerShell)。
cls 和clear 本质上是不同的——因为clear 是一个外部进程并且不会清除缓冲区——这使得解决方案不一致,除了效率低下cls 可能成为 Windows 中的内置 shell - 但 system 调用仍然会运行新的 shell。 "系统函数将命令传递给命令解释器,命令解释器将字符串作为操作系统命令执行。系统使用 COMSPEC 和 PATH 环境变量来定位命令解释器文件 CMD.exe。" #msdn.microsoft.com/en-us/library/277bwbdz.aspx
转义序列呢?
print(chr(27) + "[2J")
【讨论】:
为什么没有人谈论只是简单地在 Windows 中执行 Ctrl+L 或 Cmd+L在麦克。 当然是最简单的清屏方式了。
【讨论】:
os.system('clear'),但我认为您的回答是最简单的方法。点赞! :)
至于我,最优雅的变体:
import os
os.system('cls||clear')
【讨论】:
对于 Windows、Mac 和 Linux,您可以使用以下代码:
import subprocess, platform
if platform.system()=="Windows":
subprocess.Popen("cls", shell=True).communicate() #I like to use this instead of subprocess.call since for multi-word commands you can just type it out, granted this is just cls and subprocess.call should work fine
else: #Linux and Mac
print("\033c", end="")
jamesnotjim 为 Mac 测试了 print("\033c", end=""),我在 Linux 和 Windows 上测试了它(它不适用于 Windows,因此调用 cls 的其他代码)。我不记得我第一次看到使用print("\033c") 和/或printf 版本的是谁:subprocess.Popen("printf '\033c'", shell=True).communicate()。
rolika 指出end="" 将阻止它之后打印新行。
【讨论】:
print("\033c", end="") 如果不想打印换行符
如果您使用的是 Linux/UNIX 系统,那么打印 ANSI 转义序列以清除屏幕应该可以完成这项工作。您还需要将光标移动到屏幕顶部。这适用于任何支持 ANSI 的终端。
import sys
sys.stderr.write("\x1b[2J\x1b[H")
除非启用了 ANSI 支持,否则这在 Windows 上不起作用。 Windows 可能有等效的控制序列,但我不知道。
【讨论】:
print(没有softspace 调整和/或sys.stdout.flush())不能 将光标留在屏幕的左上角,我编辑了您对 Python 2.x 和 3.x 都可以使用的内容的答案
sys.stderr.flush()。 print() 实际上也可以。
import colorama; colorama.init() 使"\x1b[2J\x1b[H" 序列也可以在 Windows 上运行。
只需使用:
print("\033c")
这将清除终端窗口。
【讨论】:
print("\033c", end="") 在清除控制台时不会注入换行符。
您可以尝试依赖 clear,但它可能不适用于所有 Linux 发行版。正如你提到的,在 Windows 上使用 cls。
import subprocess
import platform
def clear():
subprocess.Popen( "cls" if platform.system() == "Windows" else "clear", shell=True)
clear()
注意:控制终端屏幕可能被认为是不好的形式。您是否正在考虑使用选项?让用户决定是否要清除屏幕可能会更好。
【讨论】:
os.system?这里有什么优势?
subprocess.call() 来处理这个调用这样简单的事情。
前段时间遇到过这个
def clearscreen(numlines=100):
"""Clear the console.
numlines is an optional argument used only as a fall-back.
"""
# Thanks to Steven D'Aprano, http://www.velocityreviews.com/forums
if os.name == "posix":
# Unix/Linux/MacOS/BSD/etc
os.system('clear')
elif os.name in ("nt", "dos", "ce"):
# DOS/Windows
os.system('CLS')
else:
# Fallback for other operating systems.
print('\n' * numlines)
然后只需使用 clearscreen()
【讨论】:
这将适用于 Python2 或 Python3 版本
print (u"{}[2J{}[;H".format(chr(27), chr(27)))
【讨论】:
print (u"{}[2J{}[;H".format(chr(27), chr(27)), end="") 用于删除换行符。
纯 Python 解决方案。
不依赖 ANSI 或外部命令。
只有您的终端必须能够告诉您有多少行在视图中。
from shutil import get_terminal_size
print("\n" * get_terminal_size().lines, end='')
Python 版本 >= 3.3.0
【讨论】:
所以我只是想我会把我的两分钱扔在这里......
似乎没有人对 OP 问题提供真正的答案,每个人要么回答“不要使用 os.system() 这是邪恶的!!!”没有解释或提供依赖于打印新行的解决方案。
对于那些需要清除终端屏幕并向后滚动的人,无论出于何种原因,您都可以使用以下代码:
import os
def clear():
'''
Clears the terminal screen and scroll back to present
the user with a nice clean, new screen. Useful for managing
menu screens in terminal applications.
'''
os.system('cls' if os.name == 'nt' else 'echo -e \\\\033c')
print('A bunch of garbage so we can garble up the screen...')
clear()
# Same effect, less characters...
def clear():
'''
Clears the terminal screen and scroll back to present
the user with a nice clean, new screen. Useful for managing
menu screens in terminal applications.
'''
os.system('cls||echo -e \\\\033c')
这具有 OP 的预期效果。它确实使用了 os.system() 命令,所以如果这是邪恶的,并且有人知道使用 subprocess.call() 实现它的方法,请发表评论,因为我也更喜欢使用 subprocess 但根本不熟悉它。
【讨论】:
'clear' 适用于某些 nix 环境,但不是全部,而 'cls' 是特定于 Windows 的,'echo -e \\\\033c' 适用于所有 Bash 环境
echo -e 是一个非 POSIX 扩展——根本不保证支持它,即使你的 shell 100% 保证是 bash,它也可以关闭(运行set -o posix; shopt -s xpg_echo,然后echo -e 将在输出上打印-e)。请参阅the POSIX specification for echo,它明确建议您在需要打印转义序列时使用printf。
此函数在 gnome-terminal 中工作,因为默认情况下,它识别 ANSI 转义序列。它给你一个干净的提示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
参数:rows 是在提示符和终端底部之间添加的明文行数,将所有内容向上推。 rows_max是文本行中终端的高度(或最大清除高度),只需设置一次,可随时重置。第三个参数位置的*, 表示所有后续参数都是关键字(例如,clear(absolute=5))。 calling_line=True(默认)在交互模式下效果更好。 calling_line=False 更适合基于文本的终端应用程序。添加absolute 是为了在缩小终端尺寸后尝试修复交互模式下的毛刺间隙问题,但也可用于终端应用程序。 store_max 仅用于秘密“持久”存储 rows_max 值;不要显式使用此参数。 (当没有为store_max 传递参数时,更改store_max 的列表内容会更改此参数的默认值。因此,持久存储。)
可移植性:抱歉,这在 IDLE 中不起作用,但它在识别 ANSI 转义序列的终端(控制台)中的交互模式下工作 >> 非常酷 shutil.get_terminal_size() 函数)和 ANSI 识别。 print(...) 函数是 Python 3。我还用一个简单的、基于文本的终端井字游戏(应用程序)对此进行了测试。
在交互模式下使用:首先在交互模式下复制并粘贴copy(...) 函数,看看它是否适合您。如果是这样,则将上述函数放入名为 clear.py 的文件中。在终端启动 python,使用“python3”。输入:
>>> import sys
>>> sys.path
['', '/usr/lib/python3.3', ...
现在将 clear.py 文件放入列出的 path 目录之一,以便 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(...) 函数放入与您的main.py 文件位于同一文件夹中的名为 clear.py 的文件中。这是一个井字游戏应用程序的工作抽象(骨架)示例(从终端提示符运行: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()
解释:第 19 行上的 do_print(...) 是 print(...) 的一个版本,用于跟踪已打印的新行数 (self.rows)。否则,您将不得不在整个程序中调用print(...) 的地方到处都是self.rows += 1。因此,每次通过调用show_board() 重新绘制电路板时,前一个电路板都会被清除,新电路板会准确地打印在它应该在的位置。注意第 9 行的self.clear(calling_line=False) 基本上将所有内容向上推到终端底部,但不会清除原始调用行。相比之下,第 29 行的self.clear(absolute=self.rows) 绝对清除了所有向上的self.rows 距离,而不是仅仅将所有内容相对于终端底部向上推。
使用 Python 3.3 的 Ubuntu 用户:将 #!/usr/bin/env python3 放在 tictactoe.py 文件的第一行。右键单击 tictactoe.py 文件 => 属性 => 权限选项卡 => 检查执行:允许将文件作为程序执行。双击文件=>单击在终端中运行按钮。如果打开终端的当前目录是 tictactoe.py 文件所在的目录,也可以使用./tictactoe.py 启动文件。
【讨论】:
如果您希望在使用 python shell 时清除终端。然后,您可以执行以下操作来清除屏幕
import os
os.system('clear')
【讨论】:
在 Windows 中,您可以使用:
>>> import os
>>> clear = lambda: os.system('cls')
>>> clear()
【讨论】:
您可以撕开 terminfo 数据库,但这样做的函数无论如何都在 curses 中。
【讨论】:
python -c "from os import system; system('clear')"
【讨论】:
system('clear') 很糟糕?我不同意。
rm file 删除bash 中的文件——因为有人可能会误解它并以root 身份执行rm -rf /。
你可以使用call()函数来执行终端的命令:
from subprocess import call
call("clear")
【讨论】:
您可以自己制作。这将不依赖于您的终端或操作系统类型。
def clear(num):
for i in range(num): print
clear(80)
print "hello"
【讨论】:
这将清除 25 个新行:
def clear():
print(' \n' * 25)
clear()
我使用 Eclipse 和 pydev。我比 for num in range 更喜欢换行解决方案。 for 循环会引发警告,而打印换行符不会。 如果您想在 clear 语句中指定换行符的数量,请尝试此变体。
def clear(j):
print(' \n' * j)
clear(25)
【讨论】:
如果您只需要清除屏幕,这可能就足够了。问题是甚至没有 100% 跨平台的方式来跨 linux 版本执行此操作。问题是终端的实现都支持略有不同的东西。我相当确定“清除”将在任何地方工作。但更“完整”的答案是使用 xterm 控制字符来移动光标,但这需要 xterm 本身。
在不了解更多问题的情况下,您的解决方案似乎已经足够好了。
【讨论】:
一种可能很俗气的清除屏幕的方法,但在我所知道的任何平台上都可以使用,如下所示:
for i in xrange(0,100):
print ""
【讨论】:
print ('\n' * 100),它可以在 Python 2.x 和 3.x 中运行,同时速度更快。
我会用这种方式让它看起来更像 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)
【讨论】:
对于 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)。
【讨论】:
def cls(): if platform.system() == "Linux": os.system("clear") elif platform.system() == "Windows": os.system("cls")
The accepted answer 是一个很好的解决方案。它的问题是到目前为止它只适用于 Windows 10、Linux 和 Mac。是的 Windows(以缺乏 ANSI 支持而闻名)!此新功能已在包含 ANSI 支持的 Windows 10(及更高版本)上实现,但您必须启用它。这将以跨平台的方式清屏:
import os
print ('Hello World')
os.system('')
print ("\x1B[2J")
在 Windows 10 以下的任何设备上,它都会返回:
[2J
这是由于以前的 Windows 版本缺乏 ANSI 支持。然而,这可以使用colorama 模块来解决。这增加了对 Windows 上 ANSI 字符的支持:
ANSI 转义字符序列长期以来一直用于在 Unix 和 Mac 上生成彩色终端文本和光标定位。 Colorama 也可以在 Windows 上完成这项工作,方法是包装标准输出、剥离它找到的 ANSI 序列(在输出中将显示为 gobbledygook),并将它们转换为适当的 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 上非常不安全,是的,它可以工作,但它确实是一个 hack。与脚本在同一个字典中名为cls.bat或cls.exe的文件会与命令冲突,执行文件而不是命令,造成巨大的安全隐患。
将风险降至最低的一种方法是更改调用cls 命令的位置:
import os
os.system('cd C:\\Windows|cls' if os.name == 'nt' else 'clear')
这会将Currant D字典更改为C:\Window(反斜杠在这里很重要)然后执行。 C:\Windows 始终存在,需要管理权限才能在此处写入,使其非常适合以最小风险执行此命令。另一种解决方案是通过 PowerShell 而不是命令提示符运行命令,因为它已针对此类漏洞进行了保护。
这个问题中还提到了其他方法:Clear screen in shell 也可能有用。
【讨论】:
默认情况下,os.system("clear")/os.system("cls") 将返回一个 int 类型为 0。
我们可以通过将其分配给一个变量并删除它来完全清除屏幕。
def clear():
if (os.name == 'nt'):
c = os.system('cls')
else:
c = os.system('clear')
del c # can also omit c totally
#clear()
【讨论】:
这适用于所有平台,并且适用于 Python 2 和 3。
def clear(number):
for i in range(number):
print(" ")
然后输入clear(numberhere)来清除。
【讨论】:
print(""*100) 慢。也不需要打印空间。