发布时间:2019-08-27 08:16:40编辑:auto阅读(2776)
#!/usr/bin/python
#-*-coding:utf-8-*-
import os,time,signal,platform,subprocess
class TimeoutError(Exception):
    pass
def run_command(cmd, timeout=60):
    is_linux = platform.system() == 'Linux'
    
    p = subprocess.Popen(cmd, stderr=subprocess.STDOUT, stdout=subprocess.PIPE, shell=True, preexec_fn=os.setsid if is_linux else None)
    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:
            if is_linux:
                os.killpg(p.pid, signal.SIGTERM)
            else:
                p.terminate()
            raise TimeoutError(cmd, timeout)
        time.sleep(0.1)
    return p.stdout.read()
if __name__ == '__main__':
    cmd = 'ping www.google.com
    timeout = 10
    try:
        result = run_command(cmd, timeout)
    except TimeoutError:
        print 'excute command=<%s> timeout after %i' %(cmd,timeout)
    else:
        print = 'other error'
上一篇: 如何调试python(Debugging
下一篇: python route 知识总结
 51195
 50613
 41236
 38052
 32514
 29421
 28282
 23137
 23095
 21434
 1490°
 2203°
 1829°
 1756°
 2065°
 1816°
 2500°
 4197°
 4059°
 2896°