0

I would like to write a simple, command-line based, monitoring tool in Python that displays, on the command line, a visual indicator of a tally. The tally in question is the tally of messages on a queue but that’s not really important, what’s important is I want to display a visual indicator of a tally that can increase or decrease. I do know what the maximum possible value will be.

Does anyone know of an easy way of achieving this in Python?

In my head I’m envisaging a horizontal bar in the shell that shrinks and grows according to the tally. Note I don’t want a progress bar (I know I could use tqdm to give me progress bars) because this is an unbounded tally, there is no notion of it ending.

Any suggestions would be most welcome.

jamiet
  • 10,501
  • 14
  • 80
  • 159
  • Found some solutions here that look like they might work https://stackoverflow.com/questions/38516916/display-updating-text-on-console – jamiet Mar 11 '21 at 19:54

1 Answers1

2

If you take care not to end the line with \n, you can print backspace characters (\b) to move the "cursor" back to the beginning of the line, and overwrite the bar you just printed.

Simple example:

import sys
import random
import time

BAR_WIDTH = 50
curr_bar_width = 0

while True:
    tally = random.randint(0, 50)
    bar = '#' * tally + '.' * (BAR_WIDTH - tally)
    print('\b' * curr_bar_width + bar, file=sys.stderr, end='', flush=True)
    curr_bar_width = len(bar)
    time.sleep(0.2)
Thomas
  • 174,939
  • 50
  • 355
  • 478