如何在Python中清除屏幕?

时间:2019-03-01 11:11:48

标签: python screen clear

我正在Python 3.7.1上运行,并且一直在尝试寻找一种方法来清除所有先前打印的消息的屏幕。问题是os.system("cls")什么也不做,只会使一个小窗口弹出一秒钟,然后关闭。我尝试在末尾添加\ n并将其乘以有多少个字母,但仍然无法正常工作。

2 个答案:

答案 0 :(得分:0)

很遗憾,没有内置关键字或功能/方法可以清除屏幕。所以,我们自己做。

我们可以使用ANSI转义序列,但是这些序列不可移植,并且可能无法产生所需的输出。

# 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() 

答案 1 :(得分:-1)

我不认为有办法,或者至少从未见过。但是,有一种解决方法看起来像

print "\n" * 100

这将仅打印100个换行符,这将为您清除屏幕。

您也可以将其放在函数中

def cls(): print "\n" * 100

然后在需要时使用cls()进行调用

相关问题