问题需求:
在服务器上需要一直运行一个python脚本,但由于某些不稳定因素脚本会自己停掉。因此需要设置一个守护进程对其进行监测,发现停了之后再次启动。
解决方案:
通过shell脚本对该py脚本进行监控
方案一:在crontab 设置定时启动该shell脚本进行检查。
1.创建shell 脚本:
ps -ef | grep demo1.py | grep -v grep #查询python脚本状态
if [ $? -ne 0] #判断执行
then
echo "start wafkfk_to_mysql-v2.py"
cd /home/yd/scripts; nohup python3 /home/yd/scripts/demo1.py >> /home/yd/scripts/demo1.log 2>&1 &
else
echo "wafkfk_to_mysql-v2.py is running"
fi
2.设置定时任务:
crontab -e #进入crontab
# For details see man 4 crontabs
# Example of job definition:
# .---------------- minute (0 - 59)
# | .------------- hour (0 - 23)
# | | .---------- day of month (1 - 31)
# | | | .------- month (1 - 12) OR jan,feb,mar,apr ...
# | | | | .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat
# | | | | |
# * * * * * user-name command to be executed
#例:每五分钟执行一次
*/5 * * * * command
方案二:用while 循环
shell脚本
#!/bin/bash
while [ 1 ];do
python3 demo1.py
done
总结:
切记!!!!给文件赋可执行权限
chmod 777 file #赋最高权限
问题1:运行shell脚本报"syntax error: unexpected end of file"错误。
原因: 在WIN系统上编辑的配置文件到linux系统下不能正常运行,可能是配置文件的编码方式、格式、文件类别不相同导致的;
解决:
进入配置文件vim下编辑
:set ff -------------------------------------------------------------------------# 在vim中查看文件的系统格式
:set fileformat=unix-------------------------------------------------- # 在vim中将系统文件格式改为unix