#!/usr/bin/env python
# -*- coding: utf-8 -*-
import subprocess
import time
import sys
class Timeout(Exception):
pass
def run(command, timeout=10):
"""
Esta función tienes que recibir el comando a ejecutar, y el tiempo máximo
de ejecución. Si pasado dicho tiempo sigue ejecutandose devuelve la
excepcion timeou
"""
proc = subprocess.Popen(command, bufsize=0, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
poll_seconds = .250
deadline = time.time()+timeout
while time.time() < deadline and proc.poll() == None:
time.sleep(poll_seconds)
if proc.poll() == None:
proc.terminate()
raise Timeout()
stdout, stderr = proc.communicate()
return stdout, stderr, proc.returncode
if __name__=="__main__":
try:
# ejecutamos un simple "ls -l"
(stdout, stderr, returncode)=run(["ls -l"])
print "ls -l -> ok"
except Timeout:
print "timeout"
try:
# ejecutamos un "find /" que normalmente tarda mas de 5 segundos
(stdout, stderr, returncode)=run(["find /"], timeout=5) #should timeout
print "find / -> ok"
except Timeout:
print "timeout"
Comentarios sobre la versión: Versión 1.0 (0)
No hay comentarios