demo_check_error_pid.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. # -*- codeing = utf-8 -*-
  2. # @Time : 2023/11/29 16:00
  3. # @Author : Clown
  4. # @File : demo_check_error_pid.py
  5. # @Software : PyCharm
  6. import subprocess
  7. import requests
  8. import time
  9. from datetime import datetime, timedelta
  10. def sendMsgToRot(url, msg_txt):
  11. params_json = {
  12. "msgtype": "markdown",
  13. "markdown": {
  14. "content": msg_txt,
  15. "mentioned_list": ["@all"]
  16. }}
  17. resp = requests.post (url, json=params_json).text
  18. print (resp)
  19. def check_process(process_name):
  20. try:
  21. # 执行 ps -aux 命令并获取输出
  22. output = subprocess.check_output(['ps', '-aux'])
  23. pids = output.decode().split('\n')
  24. for i in pids:
  25. if process_name in i:
  26. pid = i
  27. return pid
  28. except subprocess.CalledProcessError:
  29. return []
  30. def main(process_name):
  31. # process_name = "flask" # 替换为你要监控的进程名称
  32. pids = check_process(process_name)
  33. if len(pids) > 0:
  34. print(f"进程 {process_name} 正在运行,进程ID为:{pids}")
  35. else:
  36. command = f"nohup python /home/python_flies/{process_name} &"
  37. subprocess.Popen(command, shell = True)
  38. url = 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=cf7139e1-e623-41ca-8541-5dc6e26d43b0'
  39. msg_txt = f'进程 {process_name} 未运行,已重新启动运行'
  40. sendMsgToRot(url, msg_txt)
  41. print(f"进程 {process_name} 未运行")
  42. def run():
  43. # 初始化时间周期
  44. # 更新间隔
  45. minute = 10
  46. f_now = datetime.now ()
  47. f_mm = f_now.strftime ("%M")
  48. f_ss = f_now.strftime ("%S")
  49. f_c = int (f_mm) % minute
  50. wait_s = (minute - f_c - 1) * 60 + 59 - int (f_ss)
  51. time.sleep (wait_s)
  52. # 执行循环
  53. while True:
  54. now = datetime.now ()
  55. mm = now.strftime ("%M")
  56. ss = now.strftime ("%S")
  57. c = int (mm) % minute
  58. if c == 0 and ss == '01':
  59. s = time.time ()
  60. process_names = ['demo_OceanEngineAd.py', 'demo_baiduAd.py']
  61. for process_name in process_names:
  62. main(process_name)
  63. time.sleep (minute * 60 - 0.5 - (time.time () - s))
  64. if __name__ == "__main__":
  65. run()