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


当前回答

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

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

其他回答

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

前段时间偶然发现的

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

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

清除屏幕的方法可能有些俗气,但在我所知的任何平台上都适用,如下:

for i in xrange(0,100):
    print ""

这适用于所有平台,并且在Python 2和3中都有效。

def clear(number):
    for i in range(number):
        print(" ")

然后输入clear(numberhere)来清除。