如何使用Python控制Windows的Programs and Features(卸载、更改等操作)
用Python控制Windows「程序和功能」实现卸载/更改操作
Windows的「程序和功能」本质是调用系统底层卸载接口与注册表信息,用Python实现相关操作可通过以下几种实用方式:
1. 利用WMI(Windows管理规范)操作
WMI是Windows原生管理接口,可直接查询已安装程序并执行卸载,需依赖wmi和pywin32库:
步骤:
先安装依赖包:
pip install wmi pywin32
示例代码:
查询已安装程序
import wmi c = wmi.WMI() # 遍历所有已安装程序,输出名称、版本和卸载命令 for program in c.Win32_Product(): print(f"程序名: {program.Name}, 版本: {program.Version}, 卸载命令: {program.UninstallString}")
卸载指定程序
import wmi def uninstall_program(program_name): c = wmi.WMI() for program in c.Win32_Product(Name=program_name): # 执行卸载,返回值为(错误码, ),0表示成功 result = program.Uninstall() if result[0] == 0: print(f"{program_name} 卸载成功") else: print(f"{program_name} 卸载失败,错误码: {result[0]}") # 调用示例,替换为目标程序的精确名称 uninstall_program("示例程序名")
注意:
Win32_Product类会触发MSI包验证,可能导致短暂系统卡顿,追求轻量可选择直接读取注册表的方式。
2. 调用PowerShell命令
通过Python的subprocess模块调用PowerShell的包管理命令,灵活性更强,支持更多类型程序:
示例代码:
查询已安装程序
import subprocess # 调用PowerShell获取已安装程序的名称、版本和来源 result = subprocess.run( ["powershell", "-Command", "Get-Package | Select-Object Name, Version, Source"], capture_output=True, text=True ) print(result.stdout)
卸载指定程序
import subprocess def uninstall_program(program_name): # 调用PowerShell执行卸载,-Force参数强制卸载,调试时可加-NoExit保留窗口查看输出 cmd = ["powershell", "-Command", f"Uninstall-Package -Name '{program_name}' -Force"] result = subprocess.run(cmd, capture_output=True, text=True) if result.returncode == 0: print(f"{program_name} 卸载成功") else: print(f"卸载失败: {result.stderr}") # 调用示例 uninstall_program("示例程序名")
注意:Windows商店应用需替换为
Get-AppxPackage和Remove-AppxPackage命令,例如:Remove-AppxPackage -Package (Get-AppxPackage *程序名*).PackageFullName
3. 直接读取注册表执行卸载
已安装程序的卸载信息存储在注册表中,用Python的winreg模块读取后执行卸载命令:
示例代码:
import winreg import subprocess def get_uninstall_string(program_name): # 覆盖32/64位系统、全局/当前用户的注册表路径 reg_paths = [ r"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall", r"SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall" ] hkeys = [winreg.HKEY_LOCAL_MACHINE, winreg.HKEY_CURRENT_USER] for hkey in hkeys: for reg_path in reg_paths: try: root_key = winreg.OpenKey(hkey, reg_path) subkey_count = winreg.QueryInfoKey(root_key)[0] for i in range(subkey_count): subkey_name = winreg.EnumKey(root_key, i) subkey = winreg.OpenKey(root_key, subkey_name) try: display_name = winreg.QueryValueEx(subkey, "DisplayName")[0] if program_name.lower() in display_name.lower(): return winreg.QueryValueEx(subkey, "UninstallString")[0] except FileNotFoundError: continue finally: winreg.CloseKey(subkey) except FileNotFoundError: continue finally: winreg.CloseKey(root_key) return None def uninstall_program(program_name): uninstall_str = get_uninstall_string(program_name) if not uninstall_str: print("未找到目标程序的卸载信息") return # 处理卸载命令,去除多余引号并添加静默参数(部分程序适用) uninstall_cmd = uninstall_str.replace('"', '') if uninstall_cmd.endswith(".exe"): uninstall_cmd += " /s" # 静默卸载参数,部分程序可能用/quiet或/qn result = subprocess.run(uninstall_cmd, shell=True, capture_output=True, text=True) if result.returncode == 0: print(f"{program_name} 卸载成功") else: print(f"卸载失败: {result.stderr}") # 调用示例 uninstall_program("示例程序名")
关键注意事项
- 管理员权限:绝大多数程序卸载需要以管理员身份运行Python脚本,右键选择「以管理员身份运行」。
- 静默参数适配:不同程序的静默卸载参数可能不同,常见的有
/s(exe程序)、/qn(MSI包),需根据目标程序调整。 - 程序名称匹配:查询时尽量使用精确的程序名称,避免匹配到相似名称的其他程序。
内容的提问来源于stack exchange,提问作者HoYa
相关产品推荐
相关产品推荐

