Timeout process call in Python

Sometimes you may do a process call that's unstable (for example, doing ssh to a dead server).

Here is some code I stumbled upon which makes it trivial to do a timeout on process calls:

def timeout_command(command, timeout):
    """call shell-command and either return its output or kill it
    if it doesn't normally exit within timeout seconds and return None"""
    import subprocess, datetime, os, time, signal

    cmd = command.split(" ")
    start = datetime.datetime.now()
    process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

    while process.poll() is None:
        time.sleep(0.1)
        now = datetime.datetime.now()
        if (now - start).seconds > timeout:
            os.kill(process.pid, signal.SIGKILL)
            os.waitpid(-1, os.WNOHANG)
            return None

    return process.stdout.read()

I use it to monitor servers (using timeout_command means that a dead server won't block the monitoring application...)

Some other modules that could do this and that I find too complex for this task:

Code · Python · Tips 18. Mar 2009
© Amir Salihefendic. Powered by Skeletonz.