def runCmd(cmd, timeout=None):
    """
    Will execute a command, read the output and return it back.
    @param cmd: command to execute
    @param timeout: process timeout in seconds
    @return: a tuple of three: first stdout, then stderr, then exit code
    @raise OSError: on missing command or if a timeout was reached
    """
ph_out = None
ph_err = None
ph_ret = None
p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=
    subprocess.PIPE)
if not timeout:
    ph_ret = p.wait()
else:
    fin_time = time.time() + timeout
while p.poll() == None and fin_time > time.time():
    time.sleep(1)
if fin_time < time.time():
    os.kill(p.pid, signal.SIGKILL)
raise OSError('Process timeout has been reached')
ph_ret = p.returncode
ph_out, ph_err = p.communicate()
return ph_out, ph_err, ph_ret
Python, Popen и select — ожидание завершения процесса или тайм-аута