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


当前回答

如果您希望在使用python shell时清除您的终端。然后,您可以执行以下操作清除屏幕

import os
os.system('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)。

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

import subprocess
import platform

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

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

如果您希望在使用python shell时清除您的终端。然后,您可以执行以下操作清除屏幕

import os
os.system('clear')

你可以自己做。这将不依赖于你的终端,或操作系统类型。

def clear(num):
    for i in range(num): print 

clear(80)
print "hello"