最近工作中遇到需要看看某程序是否在正常运行,输出检测日志。这里手写一个简单的python脚本,记录一下,便于以后找到,也给初学者提供一个学习方案。
#!/usr/bin/python
# -*- coding: UTF-8 -*-
"""
定时检测同步脚是否在运行,如果没有运行则立即启动,如果运行则不启动
nohup python ftp_sync_task.py &
"""
import time
import os
# 处理的进程名,作为判断该程序是否在运行
process_name = 'test_print'
# 检查间隔时间,单位(s)
interval_second = 1
# 需要运行的命令
process_cmd = 'python test_print.py'
log_file = 'console_task.log'
def log(text):
f = open(log_file, "a+")
f.write('{}->{}\n'.format(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()), str(text)))
f.close()
while True:
time.sleep(interval_second)
# 判断该进程是否在运行,如果在运行则不启动,没有在运动则启动
# 通过输出到文件是否为空作为判断程序是否运行中
os.system('ps aux|egrep -v grep |egrep ' + str(process_name) + ' > process_temp')
file = open('process_temp')
content = file.readline().strip('\n').strip() # 只读取一行内容
file.close()
if content != '':
log(process_name + '在运行中......')
time.sleep(interval_second)
else:
os.system(process_cmd)
log(process_name + '程序启动.......')