Python

开箱即用:使用shell脚本一键启停python服务

2022-08-08  本文已影响0人  Rethink
#!/usr/bin/env bash

# chmod 755 monitor.sh
# workdir=$(dirname $(readlink -f "$0"))
# echo $workdir

daemon_start() {
    echo "********************************************"
    echo "需要拉取最新代码"
    # git pull origin master
    echo "Done..."
    echo "********************************************"
    echo "启动监控服务..."
    pid=$(ps -ef | grep python | grep main.py | grep -v grep | awk '{print $2}')
    if [ -n "$pid" ]; then
        echo "检测到监控服务已经启动, PID:$pid, 将会先尝试kill该进程..."
        daemon_stop
    fi
    # 使用-u参数,将标准输出的结果不经缓存直接输出到日志文件
    nohup poetry run python3 -u ./main.py >monitor.log 2>&1 &
}

daemon_status() {
    echo "********************************************"
    echo "查看监控服务状态..."
    status=$(ps -ef | grep python | grep main.py | grep -v grep)
    echo "$status"
    echo "********************************************"
}

daemon_stop() {
    echo "********************************************"
    echo "停止监控服务..."
    pid=$(ps -ef | grep python | grep main.py | grep -v grep | awk '{print $2}')
    if [ -n "$pid" ]; then
        echo "PID: $pid"
        kill -9 "$pid"
    fi
    echo "Done.."
    echo "********************************************"
}
daemon_restart() {
    echo "********************************************"
    daemon_stop
    daemon_start
    echo "Done.."
    echo "********************************************"
}

# 使用 ./start.sh start|stop|restart 来运行脚本启动服务
case "$1" in
start)
    daemon_start
    ;;
status)
    daemon_status
    ;;
stop)
    daemon_stop
    ;;
restart)
    daemon_restart
    ;;
*)
    echo "Usage: ./start.sh {start|status|stop|restart}"
    exit 1
    ;;
esac
exit 0
上一篇下一篇

猜你喜欢

热点阅读