Use Python to add a progress bar to the program

Use Python to add a progress bar to the program

For development or operation and maintenance, it is very normal to use python to complete some batch tasks or do some monitoring events. So how to effectively monitor the progress of the task, besides adding log to the task, can there be another way to understand the progress of the task?

This is what we are going to understand today, the progress bar

Standard output

Let me first talk about what control characters are available in the operating system:

  • \r: Move the cursor to the first position of the current line without wrapping;
  • \n: Move the cursor to the next line, not to the first position;
  • \r\n: Move the cursor to the first position of the next line.

Let's take a look at how to add a progress bar to the standard output through python.

import sys
import time

def progress_bar(total):
    Progress bar effect
    # Get standard output
    _output = sys.stdout
    # Determine the total amount of your progress bar by parameters
    for count in range(0, total + 1):
        # The second here is just a substitute for the workload
        # There should be your main program here, main()
        _second = 0.1
        # Simulate business consumption time
        # Output progress bar
        _output.write(f'\rcomplete percent:{count:.0f}')
    # Refresh the standard output at once


Let’s take a look at the actual effect, here I have recorded a gif

tqdm module

tqdm is a fast and extensible progress bar tool library. It provides a lot of interfaces, and interested friends can learn about it. The address of githup is:

Let’s take a look at how to use the tqdm module to implement a progress bar

1. The first is installation, which is very simple

pip install tqdm

2. Next is the operation

from time import sleep
from tqdm import tqdm

# Same here, tqdm is the most commonly used method of this progress bar
# Store an iterable object inside
for i in tqdm(range(1, 500)):
    # Simulate your task

Did you see here that tqdm is very simple? This is just an example. It can also be very complicated. At the same time, you also support multi-threading, multi-process, and pandas. Let’s have a feeling of multi-process.

All the codes have been pushed to my github, interested friends can go to download ~ Miracle Github:

If you are still interested in today's content, why not like it before leaving? If you are interested enough to appreciate me, don’t hesitate~

Reference: Use Python to add a progress bar to the program-Cloud + Community-Tencent Cloud