在一行中更新打印结果并同时在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")
,

您的行没有更新,因为打印功能会打印换行符,所以您要做的就是

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)