Terminating a program within a time frame through python
<p>I'm running a fortran code from a python script which sometimes takes a while to run. Thus I'm limiting the run time with a code taken from <a href="http://stackoverflow.com/a/13821695/3910261">this link</a>:</p>

<pre><code>def timeout(func, args=(), kwargs={}, timeout_duration=15, default=1):
    import signal

    class TimeoutError(Exception):
        pass

    def handler(signum, frame):
        raise TimeoutError()

    # set the timeout handler
    signal.signal(signal.SIGALRM, handler) 
    signal.alarm(timeout_duration)
    try:
        result = func(*args, **kwargs)
    except TimeoutError as exc:
        result = default
    finally:
        signal.alarm(0)

    return result
</code></pre>

<p>I'm basically putting another function (partly below) in to this one (above) to run fortran code as:</p>

<pre><code>subprocess.check_output('./../bin/SPhenoUMSSM ../UMSSM/LH_out_'+mod+' &gt; SPheno_log_'+mod, shell=True)
</code></pre>

<p>However I realised that when fortran code takes more than 15 seconds, which is the boundary in timeout function, it leaves in the core and executes other one in the for loop which creates dump in my cores. In order to prevent that, I wanted to use <code>subprocess.popen()</code> since it gives me pid to terminate the job in the core, but I need to wait for the process to be executed as well, like <code>subprocess.check_output()</code> does. Thus I was wondaring if there is a way to combine popen and check_output properties to wait until job is done within 15 seconds and if its not just terminates that.</p>

<p>There's a timeout argument on check_output, just set it to 15 seconds.</p>

<pre><code>try:
  subprocess.check_output(['arg1', 'arg2'], timeout=15)
except:
  print("Timed out")
</code></pre>

<p>Documentation here <a href="https://docs.python.org/3/library/subprocess.html#subprocess.check_output" rel="nofollow">https://docs.python.org/3/library/subprocess.html#subprocess.check_output</a></p>

<p>check_output returns the output as well, so if you care about it just store the result.</p>

<p>There's also a wait function that's useful for more complicated use cases. Both check_output and wait block until the process finishes, or until the timeout is reached.</p>

python subprocess popen