python 清屏幕_如何使用python清除屏幕?

当我们使用python交互式shell / terminal时,我们会不断获得输出,并且窗口看起来非常笨拙,大多数时候我们不会使用ctrl + l来清除屏幕。

但是,如果我们想在运行python脚本时清除屏幕,则必须为此做些事情,因为没有内置的关键字或函数/方法可以清除屏幕。因此,我们必须为此编写一些代码。

因此,我们必须遵循一些步骤Step 1 − First we have to write from os import system.

Step 2 − Next Define a function.

Step 3 − Then make a system call with 'clear' in Linux and 'cls' in Windows as an argument.

Step 4 − Next we have to store the returned value in an underscore or whatever variable we want (an underscore is used because python shell always stores its last output in an underscore).

Step 6 − Lastly call the function.

范例程式码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('Hi !! I am Python\n'*10)

sleep(2)

# now call function we defined above

screen_clear()

输出结果Hi !! I am Python

Hi !! I am Python

Hi !! I am Python

Hi !! I am Python

Hi !! I am Python

Hi !! I am Python

Hi !! I am Python

Hi !! I am Python

Hi !! I am Python

Hi !! I am Python

使用子流程模块。

示例import os

from subprocess import call

from time import sleep

def screen_clear():

_ = call('clear' if os.name =='posix' else 'cls')

print('Hi !! I am Python\n'*10)

# sleep for 2 seconds after printing output

sleep(2)

# now call the function we defined above

screen_clear()

输出结果Hi !! I am Python

Hi !! I am Python

Hi !! I am Python

Hi !! I am Python

Hi !! I am Python

Hi !! I am Python

Hi !! I am Python

Hi !! I am Python

Hi !! I am Python

Hi !! I am Python

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值