Home > Mobile >  How to keep executing code until another function returns value?
How to keep executing code until another function returns value?

Time:06-29

from time import sleep

def foo():
    sleep(3)
    return True

while True:
    print('Running')

    if foo() == True:
        print('Finished.')
        break

I want to keep printing "Running" but when foo returns True I want to print "Finished" (once) and break out of the loop.

I have tried the above but it prints "Running" just once and waits for foo to finish executing and then continues.

CodePudding user response:

import threading
from time import sleep


flag = True


def foo()->None:
    global flag
    sleep(1)
    flag = False


if __name__ == "__main__":
    t1 = threading.Thread(target=foo)
    t1.start()
    while flag:
        print('Running')
    print('Finished')

Because you worked with only one thread, when you call the function the main stops until the function returns. Therefore, if you want the main code and the function to run together, you have to work with threads.

CodePudding user response:

So, after trying somethings I found 2 solutions, of my own question, that uses threading.

1. Modifies the foo function

from time import sleep
from threading import Thread

x = True
def foo():
    sleep(3)

    global x
    x = False
    print('finished')


def printing():
    while x:
        print('Running')


foo_thread = Thread(target=foo)
foo_thread.start()

printing_thread = Thread(target=printing)
printing_thread.start()

2. Uses decorator to keep foo unchanged

from time import sleep
from threading import Thread

x = True
def sets_true(func):

    def wrapper():
        returned_value = func()
        global x
        x = False

        print('finished')

    return wrapper

@sets_true
def foo():
    sleep(3)
    return True


def printing():
    while x:
        print('Running')


foo_thread = Thread(target=foo)
foo_thread.start()

printing_thread = Thread(target=printing)
printing_thread.start()
  • Related