You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在控制台中正确清除已输出的print内容?

清除控制台输出的单行解决方案

要实现一行代码清除控制台内容,可借助Python的os模块调用系统原生清屏命令,不同系统对应命令不同,以下是兼容多系统的写法:

首先在代码开头导入os模块,然后在你的if分支中加入这行代码:

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

修改后的完整代码:

import os

print("hello") #when code starts, this is printed
text = input()

if text == "hello":
    os.system('cls' if os.name == 'nt' else 'clear')

print("hello2")
  • 原理:os.name用于判断系统类型,Windows系统返回nt,执行cls命令;Linux/macOS等类Unix系统返回posix,执行clear命令,一行代码实现多系统兼容清屏。

内容的提问来源于stack exchange,提问作者AstroPY23

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 02:54:51