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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19596750/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 14:08:17  来源:igfitidea点击:

Is there a way to clear your printed text in python?

pythonclear

提问by Joel Madsen

I have wanted for a long time to find out how to clear something like print("example") in python, but I cant seem to find anyway or figure anything out.

很长一段时间以来,我一直想知道如何在 python 中清除类似 print("example") 之类的东西,但我似乎无法找到或弄清楚任何事情。

print("Hey")
>Hey

Now I need to clear it, and write some new text.

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

print("How is your day?")

It would print.

它会打印。

Hey

>How is your day?

But I want to clear the "Hey" so the user shouldnt look at both at same time, and it looks kinda messy.

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

采纳答案by Games Brainiac

import os
os.system('cls')

Or os.system('clear')on unix (mac and linux). If you don't want the scroll up either, then you cando this:

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

os.system("printf '\033c'")should get rid of scroll back too. Something that works on all systems:

os.system("printf '\033c'")也应该摆脱回滚。适用于所有系统的东西:

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

回答by Aniket Navlur

I think this is what you want to do:

我认为这就是你想要做的:

take the cursor one line up and delete the line

将光标向上移动一行并删除该行

this can be done like using the code below

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

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

回答by Vicrobot

Well; i have a temporary way:-

好; 我有一个临时的方法:-

print('Hey', end = '')

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

回答by Lakshay Kalra

import time
Dots = "."
total = 0
count = 0
while count < 5:
    if total<1:
        print("[+]Saving" + Dots,end="")
    total+=1
    time.sleep(1)
    print(Dots,end="")

This code works perfectly fine...

这段代码工作得很好......