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:18

What about escape sequences?

print(chr(27) + "[2J")
查看更多
公子世无双
3楼-- · 2018-12-31 09:18

The accepted answer is a good solution. The problem with it is that so far it only works on Windows 10, Linux and Mac. Yes Windows (known for it lack of ANSI support)! This new feature was implemented on Windows 10 (and above) which includes ANSI support, although you have to enable it. This will clear the screen in a cross platform manner:

import os

print ('Hello World')
os.system('') 
print ("\x1B[2J")

On anything below Windows 10 however it returns this:

[2J

This is due to the lack of ANSI support on previous Windows builds. This can however, be solved using the colorama module. This adds support for ANSI characters on Windows:

ANSI escape character sequences have long been used to produce colored terminal text and cursor positioning on Unix and Macs. Colorama makes this work on Windows, too, by wrapping stdout, stripping ANSI sequences it finds (which would appear as gobbledygook in the output), and converting them into the appropriate win32 calls to modify the state of the terminal. On other platforms, Colorama does nothing.

So here is a cross platform method:

import sys

if sys.platform == 'win32':
    from colorama import init
    init()

print('Hello World')

print("\x1B[2J")

Or print(chr(27) + "[2J") used instead of print("\x1B[2J").


@poke answer is very insecure on Windows, yes it works but it is really a hack. A file named cls.bat or cls.exe in the same dictionary as the script will conflict with the command and execute the file instead of the command, creating a huge security hazard.

One method to minimise the risk could be to change the location of where the cls command is called:

import os
os.system('cd C:\\Windows|cls' if os.name == 'nt' else 'clear')

This will change the Currant Dictionary to C:\Window (backslash is important here) then execute. C:\Windows is always present and needs administration permissions to write there making it a good for executing this command with minimal risk. Another solution is to run the command through PowerShell instead of Command Prompt since it has been secured against such vulnerabilities.

There are also other methods mentioned in this question: Clear screen in shell which may also be of use.

查看更多
皆成旧梦
4楼-- · 2018-12-31 09:19

A Pure Python solution.
Does not rely on either ANSI, or external commands.
Only your terminal has to have the ability to tell you how many lines are in view.

from shutil import get_terminal_size
print("\n" * get_terminal_size().lines, end='')

Python version >= 3.3.0

查看更多
人间绝色
5楼-- · 2018-12-31 09:19

If all you need is to clear the screen, this is probably good enough. The problem is there's not even a 100% cross platform way of doing this across linux versions. The problem is the implementations of the terminal all support slightly different things. I'm fairly sure that "clear" will work everywhere. But the more "complete" answer is to use the xterm control characters to move the cursor, but that requires xterm in and of itself.

Without knowing more of your problem, your solution seems good enough.

查看更多
不流泪的眼
6楼-- · 2018-12-31 09:20

Why hasn't anyone talked about just simply doing Ctrl+L in Windows or Cmd+L in Mac. Surely the simplest way of clearing screen.

查看更多
伤终究还是伤i
7楼-- · 2018-12-31 09:20

By default, os.system("clear")/os.system("cls") will return an int type as 0. We can completely clear the screen by assigning it to a variable and deleting that.

def clear():
    if (os.name == 'nt'):    
        c = os.system('cls')
    else:
        c = os.system('clear')
    del c  # can also omit c totally

#clear()
查看更多
登录 后发表回答