You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python实现版本检测无限循环以触发程序更新(NSSM后台服务)

实现版本检测与自动更新的后台服务脚本

以下是整合后的完整代码,包含版本对比、循环检测、异常处理以及更新后的版本同步逻辑:

import os
import requests
import time

# 配置参数
CHECK_INTERVAL = 3600  # 检测间隔,单位:秒(示例设为1小时)
# 替换为你已编写好的更新代码逻辑
def update_operation():
    # 这里放入你的实际更新代码块
    print("执行更新操作...")

def get_server_version():
    try:
        winclientsettings = requests.get('https://myapi.website/client-version/Windows')
        winclientsettings.raise_for_status()  # 捕获HTTP请求错误
        winclientdict = winclientsettings.json()
        # 建议用键名直接获取版本(比如winclientdict.get("version")),比依赖列表索引更稳妥
        serverversion = list(winclientdict.values())[1].strip()
        return serverversion
    except Exception as e:
        print(f"获取服务器版本失败: {str(e)}")
        return None

def get_local_version():
    try:
        appdata = os.getenv('LOCALAPPDATA')
        programfolder = os.path.join(appdata, 'My Program')
        versionfile = os.path.join(programfolder, 'localversion')
        with open(versionfile, "r") as file:
            # 去除换行符和空格,避免格式差异导致误判
            localversion = file.readline().strip()
        return localversion
    except Exception as e:
        print(f"读取本地版本失败: {str(e)}")
        return None

def update_local_version(new_version):
    try:
        appdata = os.getenv('LOCALAPPDATA')
        programfolder = os.path.join(appdata, 'My Program')
        versionfile = os.path.join(programfolder, 'localversion')
        with open(versionfile, "w") as file:
            file.write(new_version)
        print(f"本地版本已同步为: {new_version}")
    except Exception as e:
        print(f"更新本地版本文件失败: {str(e)}")

def main():
    while True:
        server_version = get_server_version()
        local_version = get_local_version()
        
        if server_version and local_version:
            print(f"当前本地版本: {local_version}, 服务器最新版本: {server_version}")
            if server_version != local_version:
                print("发现新版本,启动更新流程...")
                update_operation()  # 触发更新代码块
                update_local_version(server_version)  # 更新本地版本记录
            else:
                print("版本一致,无需更新")
        
        print(f"等待 {CHECK_INTERVAL} 秒后再次检测...")
        time.sleep(CHECK_INTERVAL)

if __name__ == "__main__":
    main()

关键细节说明

  • 版本对比容错:用strip()去除版本字符串的空白字符(换行、空格等),避免因格式差异导致的误判。
  • API兼容性优化:建议直接通过字典键名获取服务器版本(比如winclientdict.get("version")),而不是依赖列表索引,防止API返回结构变化导致报错。
  • 异常防护:对网络请求、文件读写操作添加异常捕获,确保单次失败不会导致整个后台服务终止。
  • 版本同步:执行更新后必须将服务器最新版本写入本地文件,否则下次检测会重复触发更新。

内容的提问来源于stack exchange,提问作者TheShadowKnows

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 13:15:32