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)?
相关问题
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- How to get the background from multiple images by
- Evil ctypes hack in python
- Correctly parse PDF paragraphs with Python
What about escape sequences?
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:
On anything below Windows 10 however it returns this:
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:
So here is a cross platform method:
Or
print(chr(27) + "[2J")
used instead ofprint("\x1B[2J")
.@poke answer is very insecure on Windows, yes it works but it is really a hack. A file named
cls.bat
orcls.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: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.
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.
Python version >= 3.3.0
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.
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.
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.