I want to execute an external program in each thread of a multi-threaded python program.
Let's say max running time is set to 1 second. If started process completes within 1 second, main program capture its output for further processing. If it doesn't finishes in 1 second, main program just terminate it and start another new process.
How to implement this?
You could poll it periodically:
import subprocess, time
s = subprocess.Popen(['foo', 'args'])
timeout = 1
poll_period = 0.1
s.poll()
while s.returncode is None and timeout > 0:
    time.sleep(poll_period)
    timeout -= poll_period
    s.poll()
if timeout <= 0:
    s.kill() # timed out
else:
    pass # completed
You can then just put the above in a function and start it as a thread.
This is the helper function I use:
def run_with_timeout(command, timeout):
    import time
    import subprocess
    p = subprocess.Popen(command, shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    while timeout > 0:
        if p.poll() is not None:
            return p.communicate()
        time.sleep(0.1)
        timeout -= 0.1
    else:
        try:
            p.kill()
        except OSError as e:
            if e.errno != 3:
                raise
    return (None, None)
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With