1#!/usr/bin/env python 2 3############################################################################# 4## 5## Copyright (C) 2016 The Qt Company Ltd. 6## Contact: https://www.qt.io/licensing/ 7## 8## This file is part of the test suite of Qt for Python. 9## 10## $QT_BEGIN_LICENSE:GPL-EXCEPT$ 11## Commercial License Usage 12## Licensees holding valid commercial Qt licenses may use this file in 13## accordance with the commercial license agreement provided with the 14## Software or, alternatively, in accordance with the terms contained in 15## a written agreement between you and The Qt Company. For licensing terms 16## and conditions see https://www.qt.io/terms-conditions. For further 17## information use the contact form at https://www.qt.io/contact-us. 18## 19## GNU General Public License Usage 20## Alternatively, this file may be used under the terms of the GNU 21## General Public License version 3 as published by the Free Software 22## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT 23## included in the packaging of this file. Please review the following 24## information to ensure the GNU General Public License requirements will 25## be met: https://www.gnu.org/licenses/gpl-3.0.html. 26## 27## $QT_END_LICENSE$ 28## 29############################################################################# 30 31import time,os 32 33class TimeoutException(Exception): 34 def __init__(self, msg): 35 self.msg = msg 36 37 def __str__(self): 38 return repr(self.msg) 39 40class ProcessTimer(object): 41 '''Timeout function for controlling a subprocess.Popen instance. 42 43 Naive implementation using busy loop, see later other means 44 of doing this. 45 ''' 46 47 def __init__(self, proc, timeout): 48 self.proc = proc 49 self.timeout = timeout 50 51 def waitfor(self): 52 time_passed = 0 53 while(self.proc.poll() is None and time_passed < self.timeout): 54 time_passed = time_passed + 1 55 time.sleep(1) 56 57 if time_passed >= self.timeout: 58 raise TimeoutException("Timeout expired, possible deadlock") 59 60if __name__ == "__main__": 61 #simple example 62 63 from subprocess import Popen 64 65 proc = Popen(['sleep','10']) 66 t = ProcessTimer(proc,5) 67 try: 68 t.waitfor() 69 except TimeoutException: 70 print "timeout - PID: %d" % (t.proc.pid) 71 #TODO: detect SO and kill accordingly 72 #Linux 73 os.kill(t.proc.pid, 9) 74 #Windows (not tested) 75 #subprocess.Popen("taskkill /F /T /PID %i"%handle.pid , shell=True) 76 print "exit code: %d" % (t.proc.poll()) 77 78