Python 如何清除屏幕

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

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程