python线程超时退出_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()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值