Python中更新当前应用

前言

开发桌面端的时候我们需要在程序中更新版本,这就要求我们下载新版本、安装新版本、关闭当前应用。

要注意的是

  • 程序必须以管理员身份运行才能安装应用。
  • 安装时要结束当前程序,所以调用安装的方法要在主进程中执行,否则sys.exit(0)不会退出当前程序。

安装

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import ctypes
import subprocess
import sys


def is_admin():
try:
return ctypes.windll.shell32.IsUserAnAdmin()
except:
return False

def install_app(exe_path):
if is_admin():
print("当前用户已经是管理员。")
try:
# 启动 exe 安装程序
subprocess.Popen([exe_path], shell=False)
print(f"已启动 {exe_path} 安装程序。")
except FileNotFoundError:
print(f"未找到 {exe_path} 文件,请检查路径是否正确。")
except Exception as e:
print(f"启动安装程序时发生错误: {e}")
# 关闭当前 Python 程序
sys.exit(0)
else:
print("当前用户不是管理员,将尝试重新以管理员身份运行脚本。")