概述
我们在应用的时候,经常需要实现应用启动及检测功能。我们启动命令
python3 restart_and_watchlog.py “sh bin/start.sh” “logs/log.log” “Started Application in” 20
第一个restart_and_watchlog.py 检测脚本
sh bin/start.sh 应用启动命令
logs/log.log 应用启动日志
Started Application in 关键字
20 过期时间20s
# -*- coding: utf-8 -*-#
#-------------------------------------------------------------------------------
# Name: restart_and_watchlog.py
# Description:
# Author: Administrator
# Date: 2022/3/13
#-------------------------------------------------------------------------------
import sys
import importlib
import subprocess
import signal
import os
from collections import deque
importlib.reload(sys)
# python3 restart_and_watchlog.py "sh bin/start.sh" "logs/log.log" "Started Application in" 20
#'sh app.sh restart'
start_shell=sys.argv[1]
#'servicelog'
log_file_name=sys.argv[2]
#'Started DemoApplication in'
keywork_success =sys.argv[3]
time_out: int=sys.argv[4]
def myHandler(signum,frame):
raise Exception("TimeoutError,no found keyword of success.")
logline_queue=deque(maxlen=30)
def log_search(logfile,search_content):
print("#"*50)
#防止读取到老日志
shell_string='tail -n 10 -F '+logfile
print('shell_string:'+shell_string)
working_file=subprocess.Popen(['tail','-n','10','-F',logfile],stdout=subprocess.PIPE,stderr=subprocess.PIPE)
print("execute end")
try:
while True:
line=str(working_file.stdout.readline())
# process data
logline_queue.append(line)
if len(line)>0:
if search_content in line:
print("success keyword of success:"+line)
return True
else:
return False
finally:
os.kill(working_file.pid,signal.SIGKILL)
def log_search_timeout(logfile,seach_content,time_out=10):
try:
signal.signal(signal.SIGALRM,myHandler)
signal.alarm(int(time_out))
result=log_search(logfile,seach_content)
signal.alarm(0)
except Exception as e:
print("execute log search exception",e)
return False
return True
def execute_shell(shellstring):
print("#"*50)
print("execute start shell:"+shellstring)
write_file=subprocess.Popen(shellstring,shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
print(write_file.stdout.read())
print("#"* 50)
execute_shell(start_shell)
#检查脚本执行日志,可以用阻塞式脚本,获取到期望的字符串,就退出
result=log_search_timeout(logfile=log_file_name,seach_content=keywork_success,time_out=time_out)
print("execute shell log is:"+str(result))
if result:
exit(0)
else:
if len(logline_queue)>0:
print("error log content:")
for logline in logline_queue:
print(logline)
pass
exit(-1)
验证结果:
最后
以上就是文静人生为你收集整理的python3 实现应用启动及关键字检测的全部内容,希望文章能够帮你解决python3 实现应用启动及关键字检测所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复