在一行中更新打印结果,同时在python中更新其进度条



我想在第一行更新打印结果,在第二行更新进度条。我制作了一个python代码,但我的脚本逐行打印文本,但不会在一行中更新它。

我该怎么修?

from tqdm import *
import time
total_num = 100
bar = tqdm(total=total_num)
bar.set_description('Count Up')
for i in range(total_num):
bar.update()
print(f'r-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ {i} -+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+')
time.sleep(1)

您可以使用python的内置subprocess模块来清除屏幕。

from subprocess import run
from sys import platform
def clear():
run("cls" if platform in {'win32', 'cygwin'} else "clear")

您的行没有更新,因为print函数打印换行符,所以您要做的是

from tqdm import *
import time
import sys
total_num = 100
bar = tqdm(total=total_num)
bar.set_description('Count Up')
for i in range(total_num):
bar.update()
sys.stdout.write(f'r{i}')
time.sleep(0.2)

但这会打乱输出,我建议更新条形图描述(这也在tqdm github页面上的一个例子中(

from tqdm import *
import time
total_num = 100
bar = tqdm(total=total_num)
for i in range(total_num):
bar.set_description(f"{i} Count Up")
bar.update()
time.sleep(0.2)

最新更新