How to clear cmd/terminal while running a python script

╄→尐↘猪︶ㄣ 提交于 2021-02-08 05:36:18

问题


I keep seeing ways to clear the shell while running a script, however is there a way to clear the screen while running a script in the CMD? My current method works like this:

clear.py

import title
def clear():
    print('\n' * 25)
    title.title()

game.py

from engine import clear
clear.clear()
print(Fore.CYAN + Style.BRIGHT + "--------------------------------")

However this method isn't really reliable as some cmd sizes are different on all computers, nor have I tried it on OSx.


回答1:


Here's another way, that handles Windows cases as well as Unix-like systems (Linux, OSX, etc.):

import os
os.system('cls' if os.name == 'nt' else 'clear')

The clear command works in all Unix-like systems (ie, OSX, Linux, etc.). The Windows equivalent is cls.




回答2:


Your best bet is probably to use the colorama module to enable ANSI escape sequences in the Windows terminal, and then use the ANSI sequence to clear the screen:

import colorama
colorama.init()
print("\033[2J\033[1;1f")

This should work on all common platforms.



来源:https://stackoverflow.com/questions/22108683/how-to-clear-cmd-terminal-while-running-a-python-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!