如何处理在 Linux 机器上远程更新连续运行的 python 脚本

问题描述 投票:0回答:1

我有一个在树莓派上运行的Python脚本。
该脚本是 git 存储库的一部分。

我打算让 rpi 和此脚本一直运行,因为该应用程序用于相当快速地响应 MQTT 消息和控制设备。一些小<5min downtime during updating is acceptable.

我正在桌面计算机上开发脚本,并希望部署到树莓派。

我正在尝试找到一种方法(在 rpi 上)

  1. 从 git 存储库更新脚本
  2. 停止当前运行的脚本
  3. 开始新的

不一定按照这个顺序。

我一直在手动执行上述过程,但我希望 rpi 能够处理它,并且我只需对脚本进行更改并将更改推送到 git。

我研究了一个从 cron 作业调用的 shell 脚本。这似乎是一条潜在的道路。 我还研究过使用容器,这似乎有点矫枉过正。

linux docker raspberry-pi
1个回答
0
投票

好的,答案的基础知识如下。 shell脚本来检查更新,然后如果repo中有新代码,将其拉下来,然后杀死脚本并重新运行它

#!/bin/bash

# Set the path to the repository and the script
REPO_DIR="/path/to/script"
SCRIPT="Main.py"

# Change directory to the repository
cd "$REPO_DIR"

# Function to check for updates
check_updates() {
    
    git fetch

    # Check if there are any new commits
    LOCAL=$(git rev-parse @)
    REMOTE=$(git rev-parse @{u})

    if [ $LOCAL != $REMOTE ]; then
        echo "New updates found. Updating..."
        return 0
    else
        echo "No updates found."
        return 1
    fi
}

# Function to update and restart the script
update_and_restart() {

    echo "pulling updates"
    # Pull the latest changes
    git pull

    echo "stopping script"
    # Kill the running Main.py process
    pkill -f $SCRIPT

    
    # Start the new version of script
    echo "running script"
    nohup python3 "$REPO_DIR/$SCRIPT" &
}

if check_updates; then
    update_and_restart
fi
© www.soinside.com 2019 - 2024. All rights reserved.