python-3.x - 用不同的值替换上面的打印行
问题描述
import time
def exitpro(t):
a=0
while t>=0:
timer="Loading "+"."*((a%3)+1)
print(timer,end='\r')
time.sleep(1)
t-=1
a+=1
t=int(input("enter time in seconds "))
exitpro(int(t))
我在 jupyter 笔记本上这样做。我想打印“正在加载”之类的内容。然后在一秒钟后“加载..”然后“加载...”然后再次“加载”。但是当我运行它时,它会打印到 3 个点,然后打印一个点的加载与 3 个点的加载重叠,所以看起来程序卡在加载 3 个点。基本上,它不会清除上面的行,而是在上面打印。请帮忙。
解决方案
\r
不清除线。它只是将光标移动到行首。您需要实际清除该行,或者通过在写入之前明确清除它Loading.
,或者通过写入Loading.
(注意句点后的额外空格)来覆盖额外的句点。
import time
def exitpro(t):
a=0
while t>=0:
dotcount = (a % 3) + 1
timer="Loading" + "." * dotcount + " " * (3 - dotcount)
print(timer, end='\r', flush=True)
time.sleep(1)
t-=1
a+=1
t=int(input("enter time in seconds "))
exitpro(t)
flush=True
强制输出立即打印,而不是等待缓冲。