有时,我们会遇到Python程式莫名其妙地退出,也没有任何异常提示,但我们希望程式能够一直运行,即便异常终止,也能自动启动,这时我们可以写一个监视程式,来达到目的:

# -*- coding: utf-8 -*-
#!/usr/bin/python

import os
import subprocess

res = subprocess.Popen('ps -ef | grep slackbot',stdout=subprocess.PIPE,shell=True)
attn=res.stdout.readlines()
counts=len(attn)  #获取ASRS下的进程个数
#print(counts)
if counts<=2:    #当进程不够正常运行的个数时,说明某只程式退出了
#    os.system('python /home/pi/ASRS/ASRS.py')     ##启动程式
   os.system('source /etc/profile && nohup python -u /home/www/XXX/xxx.py > /home/www/python/nohup.out 2>&1 &') ##启动程式   
##    os.system('reboot')    #重启系统

ps:切记在nohup python····· 前加上source /etc/profile &&  如图所示写即可,不然不会重启的(不服你试试)

Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐