金天牛

导航

常用的shell脚本:start.sh 和 stop.sh的写法

       在使用python编写系统的时候,有时需要快速启动和快速关闭系统,怎样才能方便快速启动和关闭呢,找了一些资料,记录下我的写法。

       比如我写了一个scheduler.py,用以启动使用apscheduler,进行定时任务的调度。在Linux下使用python3  scheduler.py & 就可以启动,关闭时,是需要找到这个启动的进程进行杀死。

       1.关闭脚本

        那么 ,只需要建立一个shell脚本,输入以下命令即可:ps aux | grep scheduler.py | grep -v grep | awk '{print $2}' | xargs kill -9

        具体的说明,参考文档:https://blog.csdn.net/qq_43544283/article/details/123021771

        2.接着是启动命令,

        我的想法是,当监控到程序没有运行时可以自行启动,如果已经启动,就不处理了。于是写了以下shell脚本

#!/bin/bash
startpid=`ps aux | grep scheduler.py | grep -v grep | awk '{print $2}'`
if [ ! -z "${startpid}" ]; then
echo $startpid
else
/usr/bin/python3 /home/user/bigdatamonitor/scheduler.py >>/home/user/bigdatamonitor/monitorlog/crontab.log 2>&1
fi

         说明 :第二行是获取进程id,和关闭脚本的方法一致。注意=右边的“`”符号,不是引号,是反单引号。在bash中,其用法同$()一样,用``括起来的内容代表一个变量

        第三行是 if 命令,判断startpid不为空 ,!表是非,-z表示 后面的变量检测字符串长度是否为0,或者直接用-n来 检测字符串长度是否不为 0,

        第六行是表示运行python3  scheduler.py。

       关于shell脚本,可以参考https://blog.csdn.net/weixin_50941083/article/details/124157205

        3.运行脚本

         可以直接在/var/spool/cron/  目录下 ,编辑user通过cron来控制定时启动。

 

posted on 2022-09-22 14:59  金天牛  阅读(1498)  评论(0编辑  收藏  举报