Search code examples
pythonwhile-loopprogress-bargoogle-speech-api

How to take progress update and turn into a progress bar?


I'm using a speech-to-text API and while waiting for the results I'm able to print the current percentage of progress with this:

    while not operation.done():
        print(operation.metadata.progress_percent)
        time.sleep(5)
    print(operation.metadata.progress_percent)

And get this:

    0
    2
    3
    ...

How can i turn it into a progress bar?


Solution

  • You can end the line of a print statement with a carriage return, \r, to overwrite the current line, and use that to continually "update" the progress bar.

    An example of printing a progress bar:

    import time
    
    def progress_bar(progress, total=100, bar_length=20):
      # How much of the bar should be filled
      fill = progress * bar_length // total
      # How much of the bar should be empty
      empty = bar_length - fill
      print(f'[{"#"*fill}{"-"*empty}]', end='\r')
      # Go to next line if done
      if progress == total:
        print()
    
    # Emulate a percentage progress
    for i in range(0, 101):
      progress_bar(i)
      time.sleep(0.05)
    

    This will output a bar that looks like this

    [##############------]