需要设计一个可以通过web方式自动更新的程序,其中升级后的可执行文件通过http方式提供下载。程序运行后启动两个进程,主进程处理正常业务,子进程进入轮询状态,定时查询 URL 是否有可更新的内容。当指定 URL 的文件可供下载时,子进程下载最新文件,并杀掉父进程,然后启动下载的可执行文件。
在测试环节,使用 python 的 http.server 模块提供下载服务:
python -m http.server 8888

因为尝试使用子进程不停轮询来查看 URL 目标是否存在,当目标不存在时进行休眠,sleep 60 秒后重试,当然也可以使用定时方式来触发更新。
测试代码如下:
#!python3import osimport sysimport timeimport requestsimport signalfrom multiprocessing import Processdef autoupdate():url = 'http://localhost:8888/autoupdate.exe'print('自动更新程序启动')while True:try:r = requests.get(url, timeout=0.2)if r.status_code == 404:print('目标不存在,等待...')time.sleep(60)if r.status_code == 200:breakexcept requests.exceptions.RequestException as e:print(e)print('目标不存在,等待...')time.sleep(60)f = r'd:\testdir\test.exe'dir = os.path.dirname(f)if not os.path.exists(dir):os.makedirs(dir)try:with open(f, mode='wb') as fd:fd.write(r.content)except Exception as e:print("程序出现异常!\n异常类型:%s" % type(e))print("具体内容:\n %s" % e)sys.exit()print('程序已自动更新')cmd = 'taskkill f pid ' + str(os.getppid())print(cmd)os.system(cmd)os.execv(f, (' ',))def do_something():print('主程序启动')while True:time.sleep(2)def main():do_something()if __name__ == '__main__':p = Process(target=autoupdate)p.start()main()
程序输出为:

全文完。
如果转发本文,文末务必注明:“转自微信公众号:生有可恋”。
文章转载自生有可恋,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。




