当我们使用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