Python Forum

Full Version: How to execute code WHILE a function runs
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi everyone,
I have some code for a loading bar animation that I would like to run during execution of specific functions. I know some sort of while loop would be used for this, but no matter what I try, it just doesn't do what I want.

Here's the logic I want:

while function1() is running:
      animationFunction()
Here's the animation code:
import time

bar = [
    " [=     ]",
    " [ =    ]",
    " [  =   ]",
    " [   =  ]",
    " [    = ]",
    " [     =]",
    " [    = ]",
    " [   =  ]",
    " [  =   ]",
    " [ =    ]",
]
i = 0

while True:
    print(bar[i % len(bar)], end="\r")
    time.sleep(.2)
    i += 1
I tried a while true, but I'm not sure if or how to say "while function 1 runs" (while function1 true?) in correct python syntax.
This might give you some ideas
import progressbar
import time
bar = progressbar.ProgressBar(max_value=progressbar.UnknownLength)
for i in range(20):
    time.sleep(0.1)
    bar.update(i)
You can do this with threading. My logic is 1) start animation in a different thread, 2) run function 1 3) stop animation. Read this page to start learning about threading in python
import threading
import time

event = threading.Event()

def animation():
    bar = [
    " [=     ]",
    " [ =    ]",
    " [  =   ]",
    " [   =  ]",
    " [    = ]",
    " [     =]",
    " [    = ]",
    " [   =  ]",
    " [  =   ]",
    " [ =    ]",
    ]
    
    i = 0
    while True:
        print(bar[i % len(bar)], end="\r")
        was_set = event.wait(timeout=0.2)
        if was_set:
            break
        i += 1

def function1():
    time.sleep(4)

event.clear()
anim = threading.Thread(target=animation)
anim.start()

function1()
event.set()
anim.join() # <-- wait for anim to terminate
print()
there is no need to reinvent the wheel - there are third party packages available that help create progressbar and also package like click (for creating nice CLI interfaces) offer built-in progressbar
look at this current thread
https://python-forum.io/Thread-How-can-I...y-software
and this tutorial by @snippsat
https://python-forum.io/Thread-tqdm-Prog...mmand-line
Thank you guys for all of the input... super helpful as always! I thought 'there must be packages for this type of thing', but had no idea where to look.
Thank you!