@lexi.ch home, code, stuff

Kill process after timeout (python script) 11.01.2009

This very simple and small python script starts a process, and kills it if it has not ended in a timely fashion.

Very simple, and uses polling instead of the alarm() function, but enough for me at the moment.


from sys import argv
from sys import exit
from time import sleep
from time import time
from os import kill
from signal import SIGKILL
import subprocess

def print_help():
print "Usage: timeout
 [args ] [...]n"

if len(argv) < 3:

proc = subprocess.Popen(argv[2:])
start = time()

while time() - start < int(argv[1]):
    ret = proc.poll()
    if ret != None:

# time's up: kill the proc:
print "Killing PID %d, it did not end after %d seconds." % (proc.pid,int(argv[1]))
kill(proc.pid, SIGKILL)