Skip to content

启动文件

start.sh

sh
#!/bin/bash

# 定义脚本路径和 PID 文件
SCRIPT_PATH="/path/to/your_script.py"
PIDFILE="/path/to/pidfile"

# 启动 Python 脚本,并将输出重定向到 output.log
nohup python "$SCRIPT_PATH" > /path/to/output.log 2>&1 &

# 获取最后启动的后台进程的 PID
PID=$!

# 将 PID 保存到 PID 文件
echo $PID > "$PIDFILE"

# 输出 PID,方便调试
echo "Started Python script with PID: $PID"

stop.sh

sh
#!/bin/bash

# 定义 PID 文件
PIDFILE="/path/to/pidfile"

# 检查 PID 文件是否存在
if [ ! -f "$PIDFILE" ]; then
    echo "PID file does not exist. Are you sure the script is running?"
    exit 1
fi

# 读取 PID 文件中的 PID
PID=$(cat "$PIDFILE")

# 检查 PID 是否有效
if [ -z "$PID" ]; then
    echo "PID file is empty. Cannot stop the script."
    exit 1
fi

# 终止进程
kill -9 "$PID"

# 检查进程是否成功终止
if [ $? -eq 0 ]; then
    echo "Stopped Python script with PID: $PID"
    # 删除 PID 文件
    rm -f "$PIDFILE"
else
    echo "Failed to stop the Python script."
fi