语言: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()