如何解决Python自更新程序通过树莓派更新后无法启动新程序的问题
Python自动更新程序无法启动新版本
我希望制作一款可自动更新至最新版本的Python程序:添加新功能后,把更新文件上传到树莓派这类中心存储位置,让所有设备上的程序自动完成更新,无需逐个手动操作。
我编写了如下代码,程序能识别自身是否为最新版本,也能成功下载新程序并删除旧文件,但新程序无法启动,且无任何错误提示。
更新测试代码(updaterV1.py)
#updaterV1.py import time import requests import os import hashlib time.sleep(5) cwd = os.getcwd() URL = r"http://[rasberry pi's ip]/update%20files/dev/hash.txt" hash_path = os.path.join(cwd,"remote hash.txt") with open (hash_path, "wb") as f: f.write(requests.get(URL).content) with open(hash_path,"r") as hash_file: remotehash = (hash_file.readline()).strip() os.remove(hash_path) hasher = hashlib.sha256() with open(__file__, 'rb') as self_file: selfunhashed = self_file.read() hasher.update(selfunhashed) selfhash = hasher.hexdigest() print(selfhash) print(remotehash) if (selfhash == remotehash): print("program is up to date") input() else: update_path = os.path.join(cwd,"temp name update.py") URL = r"http://[rasberry pi's ip]/update%20files/dev/update.py" with open (update_path, "wb") as f: f.write(requests.get(URL).content) with open(update_path,"r") as f: name = f.readline().strip() name = name[1:] #use the 1st line as "#name.py" not "# name" update_path = os.path.join(cwd,name) try: os.remove(update_path) except: pass os.rename(os.path.join(cwd,"temp name update.py"),update_path) os.system("python \""+update_path+"\"") print("removing self file now") os.remove(__file__)
该代码通过存储在远程目录下的独立TXT文件保存程序哈希值,无需下载完整远程程序即可对比哈希值判断是否需要更新。
内容的提问来源于stack exchange,提问作者Ice129
相关产品推荐
相关产品推荐

