首页 文章资讯内容详情

如何在python中清除屏幕?

2026-06-04 1 花语

在Python中,有时我们链接了输出,我们想在单元格提示中清除屏幕,我们可以通过按Control+l来清除屏幕。但是在某些情况下,我们需要根据程序的输出结果以及如何格式化输出来以编程方式清除屏幕。在这种情况下,我们需要在python脚本中放置一些命令,这些命令将在程序需要时清除屏幕。

我们需要python的OS模块中的system()来清理屏幕。对于Windows和Linux等不同的平台,我们需要传递不同的命令,如下例所示。另外,我们使用_变量,该变量用于保存解释器中的最后一个表达式的值。

示例

import os from time import sleep # The screen clear function def screen_clear(): # for mac and linux(here, os.name is posix) if os.name == posix: _ = os.system(clear) else: # for windows platfrom _ = os.system(cls) # print out some text print("The platform is: ", os.name) print("big output\n"* 5) # wait for 5 seconds to clear screen sleep(5) # now call function we defined above screen_clear()

输出结果

运行上面的代码给我们以下结果-

The platform is: nt big output big output big output big output big output

从结果窗口显示5秒钟后,以上输出将被清除。