如何使用 Python 清除屏幕?
programmingpythonserver side programming
要在运行 Python 脚本时清除屏幕,我们必须为此做一些事情,因为没有内置关键字或函数/方法来清除屏幕。因此,我们必须编写一些代码。
使用 Python 清除屏幕
要在 Python 中清除屏幕,我们可以使用 os 模块 −
示例
from os import system, name from time import sleep # define our clear function def screen_clear(): if name == 'nt': _ = system('cls') # for mac and linux(here, os.name is 'posix') else: _ = system('clear') # print out some text print('This is a demo line!!!\n'*10) # sleep sleep(2) # now call function we defined above screen_clear()
输出
This is a demo line!!! This is a demo line!!! This is a demo line!!! This is a demo line!!! This is a demo line!!! This is a demo line!!! This is a demo line!!! This is a demo line!!! This is a demo line!!! This is a demo line!!!
使用 Python 的 subprocess 模块清除屏幕
subprocess 模块也可用于清除屏幕 −
示例
import os from subprocess import call from time import sleep def screen_clear(): _ = call('clear' if os.name =='posix' else 'cls') print('This is a demo line!!!\n'*10) # sleep for 2 seconds after printing output sleep(2) # call the function we defined above screen_clear()
输出
This is a demo line!!! This is a demo line!!! This is a demo line!!! This is a demo line!!! This is a demo line!!! This is a demo line!!! This is a demo line!!! This is a demo line!!! This is a demo line!!! This is a demo line!!! clear: terminal attributes: No such device or address