Asynchronous waiting with subprocessing?

Viewed 81

I have a function in a Tkinter script that utilizes subprocess.Popen.wait() that keeps freezing my GUI. After going through some docs (1 and 2), I found that I need to use asyncio to solve this via asynchronous waiting but I am rather confused:

Note: The function is implemented using a busy loop (non-blocking call and short sleeps). Use the asyncio module for an asynchronous wait: see asyncio.create_subprocess_exec.

Does this mean that I have to create a subprocess for my wait() function?

Also, here's what I have so far:

def foo(self)
    try:
        self.proc = subprocess.Popen(["python", "someModule.py"])
        try:
            self.proc.wait(11) # <-- freezes GUI
        except Exception as l:
            someFunc()
    except Exception as e:
        print(e)

Note: the TimeoutException catch on wait() serves as an indicator for another function to begin execution, whereas successful execution of wait() (i.e., a return value of 0) is for the opposite. Further, my goal is to have a timer in my Tkinter script activated upon successful execution of the child process, which as aforementioned, is indicated by a TimeoutException. The Tkinter interface will always be running whereas the child process will only start on user input and, similarly, end on user input (or if it unexpectedly crashes).

Edit: someModule.py is a script that activates an external data collecting bluetooth device. It must (1) establish a connection to the device, and if (1) is successful then (2) begin collecting data. Function (1) will wait 10 seconds for a connection to the bluetooth device to be established. If after 10 seconds a connection is not made, someModule.py (i.e., the child process) prints an error and terminates. This is why wait() executes for 11 seconds.

How do I implement asynchronous waiting?

1 Answers

Workaround: executing foo() via a thread solved the GUI freezing problem.

import threading

def thread(self):
    t1 = threading.Thread(target=foo)
    t1.start() # will terminate independently upon completion of foo()
Related