I'm creating a Python application that calls a few system commands. However, I want it to terminate those commands if they take too much time (say, 10s). I tried to do this on my own, using some subprocesses - without much success. After searching on stackoverflow, I found the following question: Using module 'subprocess' with timeout
It has an answer, that almost works for me - the problem is, that when the process is "terminated", it actually isn't - in fact, the process remains running in the background even after my script finishes. Of course this is not a desirable effect, but I can't find a workaround. Is there a preffered solution to this problem?
Code from mentioned answer (the bad one) for reference:
import subprocess, threading
class Command(object):
def __init__(self, cmd):
self.cmd = cmd
self.process = None
def run(self, timeout):
def target():
print 'Thread started'
self.process = subprocess.Popen(self.cmd, shell=True)
self.process.communicate()
print 'Thread finished'
thread = threading.Thread(target=target)
thread.start()
thread.join(timeout)
if thread.is_alive():
print 'Terminating process'
self.process.terminate()
thread.join()
print self.process.returncode
command = Command("echo 'Process started'; sleep 2; echo 'Process finished'")
command.run(timeout=3)
command.run(timeout=1)