有没有办法用python清除打印文本?

2024-04-23 06:28:49 发布

您现在位置:Python中文网/ 问答频道 /正文

很长一段时间以来,我一直想知道如何清除python中的print(“example”)之类的内容,但我似乎找不到或想不出任何方法。

print("Hey")
>Hey

现在我需要清除它,并写一些新的文本。

print("How is your day?")

它会打印出来。

Hey

>How is your day?

但是我想清除“嘿”,这样用户就不应该同时看到这两个,而且看起来有点混乱。


Tags: 方法用户文本内容yourisexamplehow
3条回答

好吧,我有一个临时办法:

print('Hey', end = '')

for i in range(4):
    print('\b', end = '')
print('How is your day?')

我想这就是你想做的:

take the cursor one line up and delete the line

这可以像使用下面的代码一样完成

import sys
import time

def delete_last_line():
    "Use this function to delete the last line in the STDOUT"

    #cursor up one line
    sys.stdout.write('\x1b[1A')

    #delete last line
    sys.stdout.write('\x1b[2K')


########## FOR DEMO ################
if __name__ == "__main__":
    print("hello")
    print("this line will be delete after 2 seconds")
    time.sleep(2)
    delete_last_line()
####################################
import os
os.system('cls')

或者在unix(mac和linux)上os.system('clear')。如果您也不希望向上滚动,则可以执行以下操作:

os.system("printf '\033c'")也应该去掉向后滚动。对所有系统都有效的东西:

import os
os.system('cls' if os.name == 'nt' else "printf '\033c'")

相关问题 更多 >