Command line Progress Bar for interactive python scripts — quick and emotive

Shivaji Basu
3 min readAug 27, 2022

Python is the chosen language for scripting automation (and everything else!). Be it heavy lifting of data, processing bulk emails, or churning excel sheets, python tasks that have made back and front office jobs business-essential. But for business users running automation jobs at their desks, interactiveness is important. Scripts running within the dark terminals scrolling cryptic messages are not the most palatable.

Progress bar is one way to keep the user stay put. What if the progress bar also flashes emotive status messages while the program runs? “Emotive”, for it also shows emojis when things turn bad or better.

So you may want the terminal to behave something like this while it is running..

Interactive progress bar on terminal on Python

Since the terminal is a progressive scrolling screen, printing dynamic content on the same line is not its natural way. Good news is, you do not need to install libraries to make your script interactive. Here is a quick trick to make emotive progress bars.

Four python strings you should know:

#Bringing back the cursor to the previous line on terminal
print(“\033[1A”)
#Clear the current line on terminal
print(“\033[1A”) #Clear the line
#show happy emoji
print("\U0001F600")
#show sad emoji
print("\U0001F92F")

So now you would have got the trick. Below is a function that you may call to show a progress bar during a running process.

Your script would have a counter on the number of transactions or tasks it would have performed. The values can be passed in as val and max_val. The function would covert those into relative percentage scale.

To flash interim status messages, you would set the parameters alert to True with an emoji as happy or sad, and the wait parameter set to the number of seconds you would want the message to be flashed on…

The progress bar function

Now lets start using the function in your automation batch. I am using a for loop with a dummy latency using time.sleep() function from python standard library. At each stage, I am calling the function with progress counter and status messages. I am also passing in the emotive attribute (happy, sad) the emoji parameter…

Calling the Progress Bar function during the process

Putting it together…

Get the code from here: https://carbon.now.sh/kHefU6lEW5rFMrbqqJIT

One last thing…what if you need a progress bar that rolls back regressively as your jobs winds up partially due to any error? For that, try playing with printing backspace on terminal:

print('\b')

I leave it you to figure that out in the function. Happy automating!

About the author:

The author is a regular pythonista and full stack developer. The opinions and suggestions are his own and may not construe that of his employer.

--

--