简体   繁体   中英

How to display a progress bar using Python print

I want to show a progress of a loop by printing on the same line. The following snippet works fine

for x in range(10):
    print("Step " + str(x), '\r', end='', flush=True)

But it doesn't seem to work when I use it in my main code.

epochs = 200
for epoch in range(epochs):
    # start of epoch
    start_time = time.time()
    print("Epoch: {}/{}".format(epoch+1, epochs))
    for step, train_batch in enumerate(train_gen):
        curr_loss = train_step(train_batch)
        percent_completed = step // (len(train_gen)//20)
        time_elapsed = time.time() - start_time
        print(f"{step}/{len(train_gen)}: [{'=' * percent_completed + '>' + '.'*(20-percent_completed)}] - ETA: {time_elapsed}s - Loss: {curr_loss}", '\r', end='', flush=True)
       

The output of the above code looks like
在此处输入图像描述

Why is it not displaying the print statement in the nested for loop?

Try this:

for epoch in range(epochs):
    # start of epoch
    start_time = time.time()
    print("Epoch: {}/{}".format(epoch + 1, epochs))
    for step, train_batch in enumerate(train_gen, 1):
        curr_loss = train_step(train_batch)
        percent_completed = int(step / (len(train_gen) / 20))
        time_elapsed = time.time() - start_time
        print(
            f"{step}/{len(train_gen)}: [{'=' * percent_completed + '>' + '.' * (20 - percent_completed)}] - ETA: {time_elapsed}s - Loss: {curr_loss}",
            '\r', end='', flush=True)

you got Error:

ZeroDivisionError: integer division or modulo by zero

in this line

percent_completed = step // (len(train_gen)//20)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM