Python 如何清除屏幕
在运行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