如何在Python中清除屏幕?
大多数时候,在使用Python交互式 shell/终端(不是控制台)时,我们最终会得到一个混乱的输出,并且出于某种原因想要清除屏幕。
在交互式外壳/终端中,我们可以简单地使用
ctrl+l
但是,如果我们想在运行Python脚本时清除屏幕怎么办。
不幸的是,没有内置的关键字或函数/方法来清除屏幕。所以,我们自己做。
我们可以使用 ANSI 转义序列,但这些不是可移植的,可能不会产生所需的输出。
print(chr(27)+'[2j')print('\033c')print('\x1bc')
因此,这就是我们要在脚本中执行的操作:
- From os import system.
- Define a function.
- Make a system call with ‘clear’ in Linux and ‘cls’ in Windows as an argument.
- Store the returned value in an underscore or whatever variable you want (an underscore is used because python shell always stores its last output in an underscore).
- Call the function we defined.
# import only system from os
from os import system, name
# import sleep to show output for some time period
from time import sleep
# define our clear function
def clear():
# for windows
if name == 'nt':
_ = system('cls')
# for mac and linux(here, os.name is 'posix')
else:
_ = system('clear')
# print out some text
print('hello geeks\n'*10)
# sleep for 2 seconds after printing output
sleep(2)
# now call function we defined above
clear()
注意:您也可以只“import os”而不是“from os import system”,但是,您必须将 system('clear') 更改为 os.system('clear')。
另一种方法是使用 subprocess 模块。
# import call method from subprocess module
from subprocess import call
# import sleep to show output for some time period
from time import sleep
# define clear function
def clear():
# check and make call for specific operating system
_ = call('clear' if os.name =='posix' else 'cls')
print('hello geeks\n'*10)
# sleep for 2 seconds after printing output
sleep(2)
# now call function we defined above
clear()