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脚本就会把黑窗口隐藏。