Clear terminal in Python

2018-12-31 09:03发布

Does any standard "comes with batteries" method exist to clear the terminal screen from a Python script, or do I have to go curses (the libraries, not the words)?

27条回答
梦醉为红颜
2楼-- · 2018-12-31 09:12

This will be work in Both version Python2 OR Python3

print (u"{}[2J{}[;H".format(chr(27), chr(27)))
查看更多
零度萤火
3楼-- · 2018-12-31 09:13

python -c "from os import system; system('clear')"

查看更多
萌妹纸的霸气范
4楼-- · 2018-12-31 09:15

A simple and cross-platform solution would be to use either the cls command on Windows, or clear on Unix systems. Used with os.system, this makes a nice one-liner:

import os
os.system('cls' if os.name == 'nt' else 'clear')
查看更多
素衣白纱
5楼-- · 2018-12-31 09:16

You could tear through the terminfo database, but the functions for doing so are in curses anyway.

查看更多
查无此人
6楼-- · 2018-12-31 09:16

For Windows, on the interpreter command line only (not the GUI)! Simply type: (Remember to use proper indentation with python):

import os
def clear():
    os.system('cls')

Every time you type clear() on the shell (command line), it will clear the screen on your shell. If you exit the shell, then you must redo the above to do it again as you open a new Python (command line) shell.

Note: Does not matter what version of Python you are using, explicitly (2.5, 2.7, 3.3 & 3.4).

查看更多
宁负流年不负卿
7楼-- · 2018-12-31 09:17

Came across this some time ago

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)

Then just use clearscreen()

查看更多
登录 后发表回答