You need to run an infinite stream that will periodically call a callback function that changes data in the main thread. Trying to do as indicated below in the example.

In the example, it is expected that sad smiles in a couple of seconds will be replaced by funny ones. But no. The program starts, the foo_callback function is called (if you insert print ("bla bla") into the terminal normally outputs it), however, if you try to change the status variable value, then nothing happens. Most likely, I badly smoked streams, tell me how to achieve this effect. I tried to use the queue, but the end of the stream is necessary there, and I need to periodically throw information into the main stream during the work of the endless stream.

In principle, the desired effect can be achieved by transferring data through a global variable, but, hell, this is a global variable, for sure there is a beautiful way.

Example:

import time from threading import Thread def very_very_long_func(foo_callback): while True: time.sleep(2) foo_callback(":)") status=":(" def it_callback(s): status=s thrd = Thread(target = very_very_long_func, args= ( it_callback,)) thrd.start() while thrd.is_alive(): print(status) time.sleep(0.5) 

    1 answer 1

    You need to use the global operator to make the assignment to a global variable instead of creating a local copy inside the function:

     import time from threading import Thread def very_very_long_func(foo_callback): while True: time.sleep(2) foo_callback(":)") status = ":(" def it_callback(s): global status status = s thrd = Thread(target=very_very_long_func, args=(it_callback,)) thrd.start() while thrd.is_alive(): print(status) time.sleep(0.5) 

    those. without global status , you simply create a status variable inside it_callback , which will disappear after the function is completed.

    • Yes, I used a global variable, and in this particular case, this is sufficient and works, but I would like something like callback. For example, if you write a timer in a separate thread, you would like it to generate events in this way. And with a global variable, you will need to continuously monitor its state. - Vivatist pm