猜你感兴趣
- 使用Pyqt5玩转ChatGpt
- 内网文件共享服务
- 快速搭建私有pip镜像源
- python设计模式-创建型模式
- docker搭建私有git服务器,项目备份和迁移
- redis持久化方案
说明
windows注册表中有两支子健存储有所有程序的安装信息,因此我们可以通过访问注册表获取已安装软件信息
-
64位:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall
,如下图:
-
32位:
HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall
,如下图:
代码实现
下面代码使用python3实现
class SoftwareManager:def __init__(self):self.sub_keys = [r'SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall',r'SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall']self.__installed = self.__load_all_installed()def __get_value(self, each_key, name):try:value = winreg.QueryValueEx(each_key, name)[0]except Exception:value = Nonereturn valuedef __load_all_installed(self):installed = []for sub_key in self.sub_keys:with OpenKey(HKEY_LOCAL_MACHINE, sub_key) as sub_key_handle:for i in range(QueryInfoKey(sub_key_handle)[0]):try:each_key = OpenKey(HKEY_LOCAL_MACHINE, f'{sub_key}\\{EnumKey(sub_key_handle, i)}')except Exception as e:...else:DisplayName = self.__get_value(each_key, "DisplayName")if not DisplayName:print(DisplayName)continueinstalled.append({"DisplayName": DisplayName,"DisplayVersion": self.__get_value(each_key, "DisplayVersion"),"DisplayIcon": self.__get_value(each_key, "DisplayIcon"),"InstallDate": self.__get_value(each_key, "InstallDate"),"InstallLocation": self.__get_value(each_key, "InstallLocation"),"Publisher": self.__get_value(each_key, "Publisher"),})finally:each_key.Close()return installeddef get_all(self):"""获取所有安装列表:return:"""return self.__installeddef get_by_name(self, name):"""通过名字查找已安装软件:param name: :return: """one = [i for i in self.__installed if i.get('DisplayName') == name]return one[0] if one else Nonedef re_search(self, pattern, flags=0):"""通过正则搜索匹配项:param pattern: :param flags: :return: """return [i for i in self.__installed if re.search(pattern=pattern, string=i.get('DisplayName', ''), flags=flags)]
调用
- 通过名字获取已安装软件信息
manager = SoftwareManager()# 通过名字获取
wechat = manager.get_by_name("微信")
print(wechat['DisplayName'], # 软件名wechat['DisplayVersion'], # 软件版本wechat['InstallLocation'], # 软件安装路径
)
- 使用正则匹配搜索
manager.re_search('微信') # 返回匹配列表
- 获取所有已安装软件
manager = SoftwareManager()
manager.get_all() # 返回匹配列表
- 返回示例:
[{'DisplayName': 'ApiPost Agent 1.1.0', 'DisplayVersion': '1.1.0','DisplayIcon': 'C:\\Program Files\\ApiPost Agent\\ApiPost Agent.exe,0','InstallDate': None,'InstallLocation': None,'Publisher': None},{'DisplayName': 'Apifox 2.1.34', 'DisplayVersion': '2.1.34','DisplayIcon': 'C:\\Program Files\\Apifox\\uninstallerIcon.ico','InstallDate': None,'InstallLocation': None,'Publisher': 'Apifox Team'}
]