1##########################################################################
2# Copyright (c) 2009-2016 ETH Zurich.
3# All rights reserved.
4#
5# This file is distributed under the terms in the attached LICENSE file.
6# If you do not find this file, copies can be found by writing to:
7# ETH Zurich D-INFK, Universitaetstr 6, CH-8092 Zurich. Attn: Systems Group.
8##########################################################################
9
10from threading import Timer
11
12# Wait for Popen instance p for timeout seconds and terminate/kill it after
13# the timeout expires
14# Adapted from
15# http://stackoverflow.com/questions/1191374/using-module-subprocess-with-timeout
16def wait_or_terminate(p, timeout=5):
17
18    # Kill process if terminate doesn't exit in 1 second
19    def cleanup(x):
20        k = lambda y: y.kill()
21        timer2 = Timer(1, k, [x])
22        try:
23            timer2.start()
24            x.terminate()
25        finally:
26            timer2.cancel()
27
28    # Termiate process if it doesn't voluntarily exit in `timeout` seconds
29    timer = Timer(timeout, cleanup, [p])
30    try:
31        timer.start()
32        p.wait()
33    finally:
34        timer.cancel()
35