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


当前回答

对我来说,最优雅的说法是:

import os
os.system('cls||clear')

其他回答

前段时间偶然发现的

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()

您可以尝试使用clear,但它可能并非在所有Linux发行版上都可用。在windows上使用你提到的cls。

import subprocess
import platform

def clear():
    subprocess.Popen( "cls" if platform.system() == "Windows" else "clear", shell=True)

clear()

注意:控制终端屏幕可能被认为是一种糟糕的形式。你在考虑使用期权吗?让用户自己决定是否要清除屏幕可能会更好。

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

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

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

只使用:

print("\033c")

这将清除终端窗口。

从操作系统导入系统;系统(清晰的)”