Files
WeReadBoard/start_server.sh
T
admin 92a48d14cd feat: 添加配置读取工具,支持从环境变量和 .env 文件加载 WEREAD_API_KEY
fix: 修复启动脚本中的 Python 解释器路径识别
style: 更新样式以支持按钮最小宽度和灵活布局
docs: 添加项目最终文档,整合各类信息与说明
2026-07-17 22:11:27 +08:00

117 lines
2.9 KiB
Bash
Executable File

#!/bin/bash
# 微信读书数据看板 - 服务启动脚本
# 用法:
# ./start_server.sh 启动服务(前台运行)
# ./start_server.sh daemon 后台守护进程方式启动
# ./start_server.sh stop 停止服务
# ./start_server.sh restart 重启服务
# ./start_server.sh status 查看状态
PROJECT_DIR="$(cd "$(dirname "$0")" && pwd)"
PYTHON="${PYTHON:-$(command -v python3 || command -v python)}"
PID_FILE="$PROJECT_DIR/.server.pid"
LOG_FILE="/tmp/weread_server.log"
PORT=8080
cd "$PROJECT_DIR" || exit 1
is_running() {
if [ -f "$PID_FILE" ]; then
local pid=$(cat "$PID_FILE")
if kill -0 "$pid" 2>/dev/null; then
return 0
fi
fi
# 也检查端口是否被占用
if lsof -i :$PORT -t >/dev/null 2>&1; then
return 0
fi
return 1
}
get_pid() {
if [ -f "$PID_FILE" ]; then
local pid=$(cat "$PID_FILE")
if kill -0 "$pid" 2>/dev/null; then
echo "$pid"
return
fi
fi
lsof -i :$PORT -t 2>/dev/null | head -1
}
stop_server() {
if is_running; then
local pid=$(get_pid)
echo "停止服务 (PID: $pid)..."
kill "$pid" 2>/dev/null
sleep 1
if kill -0 "$pid" 2>/dev/null; then
kill -9 "$pid" 2>/dev/null
fi
rm -f "$PID_FILE"
echo "已停止"
else
echo "服务未运行"
fi
}
start_foreground() {
if is_running; then
echo "服务已在运行 (PID: $(get_pid))"
exit 1
fi
if [ -z "$PYTHON" ]; then
echo "未找到可用的 Python 解释器"
exit 1
fi
echo "启动服务(前台模式)..."
exec "$PYTHON" app.py
}
start_daemon() {
if is_running; then
echo "服务已在运行 (PID: $(get_pid))"
exit 1
fi
if [ -z "$PYTHON" ]; then
echo "未找到可用的 Python 解释器"
exit 1
fi
echo "启动服务(后台守护模式)..."
nohup "$PYTHON" app.py > "$LOG_FILE" 2>&1 &
local pid=$!
echo "$pid" > "$PID_FILE"
sleep 2
if kill -0 "$pid" 2>/dev/null; then
echo "服务已启动 (PID: $pid)"
echo "访问: http://127.0.0.1:$PORT"
echo "日志: $LOG_FILE"
else
echo "启动失败,请查看日志: $LOG_FILE"
cat "$LOG_FILE"
rm -f "$PID_FILE"
exit 1
fi
}
show_status() {
if is_running; then
local pid=$(get_pid)
echo "✅ 服务运行中 (PID: $pid)"
echo " 端口: $PORT"
echo " 日志: $LOG_FILE"
else
echo "❌ 服务未运行"
fi
}
case "${1:-start}" in
start) start_foreground ;;
daemon) start_daemon ;;
stop) stop_server ;;
restart) stop_server; sleep 1; start_daemon ;;
status) show_status ;;
*) echo "用法: $0 {start|daemon|stop|restart|status}"; exit 1 ;;
esac