`
lhq1013
  • 浏览: 86839 次
  • 性别: Icon_minigender_2
  • 来自: 丽水
社区版块
存档分类
最新评论

python2.X利用线程实现超时结束执行的功能

阅读更多

 

语言:python 2.X

 

   
def command_timeout(command, timeout = 120):
    # print "command: ", command
    logging.info(command)
#     if timeout<30:
#         timeout=30
    result = ''
    q = Queue()
    start = time.time()
    # T0-DO Why PIPE ??
    p = subprocess.Popen(command, stdout = subprocess.PIPE, stdin=subprocess.PIPE, universal_newlines=True,shell = True)
    t = Thread(target=enqueue_output, args=(p.stdout, q))
    t.start()
        
    while p.poll() is None:
        time.sleep(0.1)
        now = time.time()
        if (now - start) > timeout:
            if isWindows():
                logging.info("timeout,kill %s, %s"%(str(p.pid),command))
                subprocess.call('TASKKILL /PID '+str(p.pid)+' /F')
            else:
                # p.send_signal(signal.SIGKILL)
                os.kill(p.pid, signal.SIGKILL) 
                # os.waitpid(-1, os.WNOHANG)
                p.kill()
                # p.terminate()
                pass
            break
    
    t.join(timeout=5)
    while 1:
        try: 
            line = q.get(False)
            # print "----- process ct: ", line
        except Empty:
            break
        else:
            # print "--------line: ", line
            result = result + line
            
    p.returncode = 1 if p.returncode == None else p.returncode
    # print "result: ", result
    logging.debug(result)
    return p.returncode,result

def isWindows():
    return True if sys.platform == "win32" else False

def isLinux():
    return 'linux' in sys.platform

def isDarwin():
    return 'darwin' == sys.platform

def enqueue_output(out, queue):
    for line in iter(out.readline, b''):
        queue.put(line)
    out.close()

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics