python exe程序更新

本文介绍了Python程序的更新流程,包括检测更新、断点续传下载新版本和使用脚本进行无窗口更新。首先,通过比较本地和服务器的版本号触发更新,然后利用断点续传技术下载新版本,最后通过VBS脚本无窗口运行BAT脚本,实现旧版本的删除和新版本的替换。
摘要由CSDN通过智能技术生成

python 程序打包系列


更新原理

获取服务器端的应用版本号,与当前的应用版本号比较,有新版本则将服务端的新应用下载到本地,然后通过脚本移除老版本,新版本替换。(还有许多更新方式,这只是我使用的方式,不是很完美,每次都要下载完整的应用,下载较慢)

1、检测更新:本地保存一个json文件,里面保存了当前版本号,读取该版本号,通过爬虫获取到服务端的版本号进行比较
2、下载新版本:通过断点续传的方式下载
3、下载完后退出主程序,通过脚本移除来移除旧版本文件夹,再把新版本替换老版本


一、断点续传下载

# url:xxxxx/demo.exe
# file_path:保存的文件,与老版本的文件夹在同一级
r1 = requests.get(url, stream=True)
total_size = int(r1.headers['Content-Length'])
if os.path.exists(file_path):
	os.remove(file_path)
temp_size = 0
# 设置range和下方的chunk_size实现断点续传功能
headers = {'Range': 'bytes=%d-' % temp_size}
r = requests.get(url, stream=True, verify=False, headers=headers)

with open(file_path, 'ab+') as f:
    for chunk in r.iter_content(chunk_size=1024):
        if chunk:
            temp_size += len(chunk)
            f.write(chunk)
            f.flush()
            done = int(50 * temp_size / total_size)
            sys.stdout.write("\r[%s%s]%d%%" % ('*' * done, ' ' * (50 - done), 100 * temp_size / total_size))
            sys.stdout.flush()
            if self.statue:
                break

二、脚本更新

1.在主程序中生成脚本文件

脚本的位置与下载的文件在同一级

代码如下(示例):

with open(path0+"\\run.vbs",'w') as f:
    content = 'set ws=wscript.createobject("wscript.shell")\n'
    content += 'ws.run "update.bat /start",0\n'
    content += 'wscript.quit'
    f.write(content)

with open(path0+"\\update.bat", 'w') as b:
    TempList = "@echo off\n"  # 关闭bat脚本的输出
    TempList += "if not exist "+"新文件"+" exit \n"  # 新文件不存在,退出脚本执行
    TempList += "ping 127.0.0.1 -n 3 > nul \n"
    TempList += ":plan \n"
    TempList += "rd /s /q " +"\\旧文件\\ \n" #移除旧文件
    TempList += "ping 127.0.0.1 -n 1 > nul \n"
    TempList += "if exist \\旧文件 goto plan \n"
    TempList += "ren 新文件名 旧文件名" # 将新文件名更改为旧文件名
    b.write(TempList)
subprocess.call("cscript run.vbs") #开始运行脚本
sys.exit() #退出主程序

这里使用了两个脚本,bat脚本在运行的时候会有黑窗口,不能直接运行这个脚本,可以通过vbs脚本来运行bat脚本就会把黑窗口隐藏。

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值