Python是否有内置函数或库可在运行时清除控制台输出?
Python 运行时清除控制台输出的方法
内置方案(无需第三方库)
- 跨平台系统命令调用:利用
os模块执行系统原生清屏命令,兼容所有主流操作系统
import os import platform def clear_console(): # Windows 用 cls,Linux/macOS 用 clear os.system('cls' if platform.system() == 'Windows' else 'clear') # 调用清屏 clear_console()
- ANSI转义序列:直接输出终端控制字符,无需额外模块,适合支持ANSI的终端(如Linux/macOS终端、Windows Terminal)
# 两种等效写法 print('\033c', end='') # 或者 print('\033[H\033[J', end='')
注意:Windows旧版cmd.exe不支持ANSI序列,使用这种方法会出现乱码。
第三方库方案
- colorama:主要用于让Windows终端支持ANSI序列,间接实现跨平台清屏
from colorama import init # 初始化colorama,让Windows终端识别ANSI序列 init() # 用ANSI命令清屏 print('\033c', end='')
- rich:功能强大的终端美化库,提供直观的清屏方法,同时支持更多复杂终端输出
from rich.console import Console console = Console() # 直接调用clear方法清屏 console.clear()
内容的提问来源于stack exchange,提问作者Celestial_Saiyan
相关产品推荐
相关产品推荐

