Augustus
Augustus

Reputation: 31

How to have a function in one module wait for another function in a separate module to (successfully) begin?

I have three modules, module1.py, module2.py, and module3.py, where module2.py contains a simple flag.

I need a function in module1.py to wait for another function in module3.py to successfully begin (as is indicated by a change in flag value in module2.py). If it helps, module3.py's execution is dependent on whether or not a successful connection is made to an external Bluetooth device.

I'm having an issue where module1.py is not waiting for module3.py to change the flag value in module2.py, and is instead immediately executing code based on the default value of the flag in module2.py, which is False.

I need a way for module1.py to wait for module3.py to change the flag value to True if module3.py begins successfully, and if after a certain amount of time (perhaps 30 seconds) the value of the flag is not changed, then the function in module1.py ceases execution.

Here is some sample code:

module1.py

import module2

def foo():
    try:
        subprocess.Popen(["python", "module3.py"], cwd=os.getcwd()
        if module2.flag:
           print('module3.py started successfully!')
           someOtherFunction()
        else:
           print('module3.py died')
    except Exception as e:
        print('something happened! ', e)

module2.py

flag = False

module3.py

import module2

def run():
    # do some stuff #
    try:
        connect.ToDevice() # connection was made to device
        module2.flag = True
        doCoolStuff()
    except Exception as e: 
        print('startup failed: ', e) # connection to device failed


if __name__ == "__main__":
    # do more cool stuff #
    try:
       loop.run_until_complete(run())
    except KeyboardInterrupt:
       print('User has stopped run() from executing.')

Here, the output would be module3.py died, even if module3.py had successful startup (and, in turn, the flag value was changed to True).

I am aware that I likely do not need to have the flag in a separate module, but I found it to be quite convenient. I would appreciate any advice as to how to solve this problem. Thank you!

Upvotes: 0

Views: 216

Answers (1)

Augustus
Augustus

Reputation: 31

Sharing data between processes via subprocessing was a pain, so I opted to use Popen.wait() as an indicator for whether or not my child process successfully initialized.

Upvotes: 1

Related Questions