Python subprocess + timeout的命令执行


 

Popen对象

  • poll() 判断是否执行完毕,执行完毕返回0,未执行完毕返回None
  • terminate() 终止进程发送SIGTERM信号
  • raise 自定义返回错误
import time  
import subprocess  
  
class TimeoutError(Exception):  
    pass  
  
def command(cmd, timeout=60):  
    """执行命令cmd,返回命令输出的内容。 
    如果超时将会抛出TimeoutError异常。 
    cmd - 要执行的命令 
    timeout - 最长等待时间,单位:秒 
    """  
    p = subprocess.Popen(cmd, stderr=subprocess.STDOUT, stdout=subprocess.PIPE, shell=True)  
    t_beginning = time.time()  
    seconds_passed = 0  
    while True:  
        if p.poll() is not None:  
            break  
        seconds_passed = time.time() - t_beginning  
        if timeout and seconds_passed > timeout:  
            p.terminate()  
            raise TimeoutError(cmd, timeout)  
        time.sleep(0.1)  
    return p.stdout.read()  
  
if __name__ == "__main__":  
    print command(cmd='ping www.redicecn.com', timeout=1) 

  


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM