'Fitting Python Progress Bar into all command prompt window sizes

How to make the progress bar size same on same line at all command prompt window sizes without splitting into half or even multiple times when adjusting the cmd window size?

def progress bar(stream, chunk, bytes remaining):

percent = 100 * (float (bytes remaining) / stream file size)
bar = '█' * int(percent) + '-' * int((100 - percent))
print(f"\r Downloading:  |{bar}|{percent:.2f}%", end="\r")


Solution 1:[1]

  1. Determine Terminal width
    You can use os.get_terminal_size() to do that
width = os.get_terminal_size().columns
  1. Determine the size of the rest of your text
  2. Use your percentages as a ratio to calculate how much bar character(?) and fill character(-) to use to fill the remainder.
   remainder = width - len_text
   bar_chars = int(percent/100) * remainder
   fill_chars = remainder - bar_chars
   bar = '?' * bar_chars + '-' * fill_chars

If you are ok with it being off on a window resize until it's redrawn, then you're done. If you want it to redraw immediately, you need to add a signal handler for signal.SIGWINCH.

Now all that being said, you could just use a library like Enlighten that already handles all of this and includes other features like color and multiple progress bars.

import enlighten

manager = enlighten.get_manager()
pbar = manager.counter(total=file_size, desc='Downloading', unit='bytes')

# This part will vary based on your implementation, but here is an example
while len(data) < file_size:
   chunk = get_next_chunk()
   data += chunk
   pbar.update(len(chunk))

There's an example ftp downloader in the repo.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 aviso