Have you ever wanted to track the progress of a series of function calls in Python β maybe during some tasks that take time to complete?
In this short post, Iβll show you a minimal example of how to execute a list of functions sequentially while displaying a simple progress bar to track completion in the terminal.
π§ Code Walkthrough
import time
def test_1():
time.sleep(5)
print('this is function 1')
def test_2():
time.sleep(2)
print('this is function 2')
def test_3():
time.sleep(3)
print('this is function 3')
def test_4():
time.sleep(1)
print('this is function 4')
func_list = [
{'index': 1, 'func': test_1},
{'index': 2, 'func': test_2},
{'index': 3, 'func': test_3},
{'index': 4, 'func': test_4},
]
for func_dict in func_list:
index = func_dict['index']
function = func_dict['func']
# call function
function()
# progress bar
progress_total = len(func_list)
progress_bar = int((index / progress_total) * progress_total)
# percent
percent = int((index / progress_total) * 100)
print('π©' * progress_bar, f'{percent} %')
π§ Whatβs Happening Here?
- - time.sleep() is used to simulate time-consuming operations.
- - We store functions in a list of dictionaries with their respective index.
- - After each function call, we calculate:
- - Progress bar length
- - Percent complete
- - A simple emoji-based progress bar (π©) is printed after each function.
β Sample Output
this is function 1
π© 25 %
this is function 2
π©π© 50 %
this is function 3
π©π©π© 75 %
this is function 4
π©π©π©π© 100 %
π‘ Ideas for Improvement
- Add concurrent execution using asyncio or concurrent.futures.
- Turn the progress bar into a dynamic inline update (e.g., using \r or libraries like tqdm).
- Add color using the colorama library or similar.
If you found this helpful, drop a β€οΈ or follow me for more Python tips!
Let me know in the comments: How would you improve this basic progress tracker?
Top comments (0)