Python loop progress visualization

2.2 Cycle Progress Visualization

In the development of Python programs, we often encounter the situation of loop processing. If the number of loops is large and the time-consuming is relatively long, there is usually no way to know where the loop is. I don’t think it is very easy to wait in a big loop. Good thing, sometimes you can only force stop the program if you can't wait.
If the progress of the cycle can be displayed during the cycle, it will be more reassuring, at least in the heart. The following introduces two methods, which can display the progress of the cycle on the terminal during the cycle.
覆盖终端中的输出以显示循环进度

import time
counts = 200
for i in range(counts):
    percent = (i + 1) * 100 // counts
    print('\r', end='')
    print(f'进度:{
      
      percent}%', end='')
    # 下面是循环处理代码
    time.sleep(0.05)

Progress: 100%

Through the above method, you can set the output starting point to be adjusted to the beginning of the line after each cycle. Since the subsequent progress display will cover the previous one, so from the visual effect, you can see that the progress has been changing, from 1% to 100%.
Advantages: No need to import other modules, and the for statement is very flexible.
Disadvantages: Other content cannot be output in the loop, and a new percent variable needs to be created to display the progress.
使用tqdm库中的trange

from tqdm import trange
from time import sleep
for i in trange(100):
    sleep(0.1)

100%|██████████| 100/100 [00:10<00:00, 9.97it/s]

Since a third-party library is used, the display effect of this method is particularly friendly, and the following information can be displayed:

  • show progress percentage
  • show progress bar
  • Display total time elapsed and countdown
  • Display the number of loops processed per second
    The advantage of this method is that it is simple and easy to use, but the disadvantage is that the for statement is not flexible, and the loop variable can only be obtained from trange.

おすすめ

転載: blog.csdn.net/crleep/article/details/130255408