python项目在linux中的启动脚本(shell脚本)

背景:

  在linux环境,使用shell脚本,实现对某个服务的启动、停止功能。

shell脚本的功能:

  1. 启动(start):通过参数 start ,实现启动服务。如果该服务已经启动,给出已经启动的提示信息,避免重复启动该服务;如果未启动,启动该服务。
  2. 关闭(stop):通过参数 stop ,实现停止服务。如果该服务已停止,给出已关闭的提示信息。如果服务已启动,停止该服务。
  3. 提示信息:如果没有传递任何参数,给出可用参数的提示信息。

实现:

ps:以python实现的定时任务为例,说明服务启动、关闭脚本的实现

shell 复制代码
# 服务配置
# python 项目使用的虚拟环境路径
venvPath="/home/ops/add_missing_room_detail/py36"
# python 项目的路径
projectPath="/home/ops/add_missing_room_detail/HotelGo2DelonixPmx"
# python 项目启动命令
CMD="python fix_missing_rates.py"

# 启动进程函数
start_process() {
  # 判断进程是否已经在运行,如果已经在运行则不需要重复启动
  start_pid=$(ps aux | grep "$CMD" | grep -v grep | awk '{print $2}')
  if [ -n "$start_pid" ]; then
    echo "The process is already running with PID:" $start_pid
    return 1
  fi

	# 激活python虚拟环境
  echo "activate python venv3  $venvPath"
  source $venvPath"/bin/activate"
  cd $projectPath
  # 后台运行执行命令,将日志输出到文件runoob.log
  nohup $CMD >runoob.log 2>&1 &
  start_pid=$!

  # 判断进程是否成功启动
  if [ -z "$start_pid" ]; then
    echo "Fail to start process"
    return 1
  else
    echo "The process has been started with PID:" $start_pid
    return 0
  fi
}

# 停止进程函数
stop_process() {
  # 根据进程名过滤出进程id,并结束进程
  start_pid=$(ps aux | grep "$CMD" | grep -v grep | awk '{print $2}')
  if [ -z "$start_pid" ]; then
    echo "No process to stop."
    return 1
  else
    kill -9 $start_pid
    echo "The process has been stopped with PID:" $start_pid
    return 0
  fi
}

# 根据传入参数执行对应的操作
case $1 in
start)
  start_process
  ;;
stop)
  stop_process
  ;;
*)
  echo "Usage: $0 {start|stop}"
  exit 1
  ;;
esac

使用

  1. 提示信息:

  2. 启动:

  3. 关闭:

相关推荐
XiaoYu1__6 分钟前
JavaGUI文件管理系统开发实战:从静态展示到动态交互的演进
java·开发语言
SunnyDays10116 分钟前
使用 Python 提取 Word 文档中的表格数据
python·word
for_ever_love__8 分钟前
python基础语法学习: 动态类型
开发语言·python·学习
霸道流氓气质15 分钟前
MCP(Model Context Protocol)核心概念与Java SDK集成
java·开发语言
企查查数据服务16 分钟前
全军禁入下客商准入风控,关联图谱与穿透核查
大数据·开发语言·数据库·php
troy12835 分钟前
分布式系统框架选型指南:主流框架优缺点深度对比
python·django·pygame
PC2005-cloud40 分钟前
DSH 白嫖指南:接入 Command Code Go、WorkBuddy 与 Trae 的免费额度
开发语言·后端·golang
129Lab1 小时前
BMS算法快速原型开发:AI辅助实现扩展卡尔曼滤波(EKF)SOC估算从理论到代码落地
python·嵌入式开发·bms·卡尔曼滤波·电池管理系统·soc估算
萧鼎1 小时前
safetensors 库的安装、核心语法与实战用法,安全保存模型权重
python·开源·教程·python库·safetensors
千里码aicood1 小时前
基于Python语言的测量程序设计
开发语言·python