Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run a external program with specified max running time

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?

like image 889
jack Avatar asked Dec 22 '22 02:12

jack


2 Answers

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.

like image 99
Liquid_Fire Avatar answered Dec 26 '22 12:12

Liquid_Fire


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)
like image 33
Cenk Alti Avatar answered Dec 26 '22 11:12

Cenk Alti