在当今的数字时代,我们的计算机上安装了数不胜数的程序。但是,您是否曾想过如何快速获取所有已安装程序的列表,并将其转化为可用的配置文件?今天,我们将探讨如何使用 Python 创建一个强大的工具,它不仅可以列出 Windows 系统中所有已安装的程序,还能生成一个包含这些程序信息的配置文件。
项目概述
我们的项目名为"Windows 程序列表生成器",它主要完成两个任务:
- 扫描并列出 Windows 系统中所有已安装的程序。
- 根据扫描结果生成一个配置文件,其中包含每个程序的详细信息。
这个工具可以帮助系统管理员快速审计已安装的软件,协助开发者创建启动器应用程序,或者simply帮助用户整理他们的软件库。
 C:\pythoncode\new\shortcut.py
全部代码
import wx
import os
import winreg
import configparser
import subprocess
def get_installed_programs():
 programs = []
 
 # 方法 1: 使用 PowerShell 命令获取已安装的应用程序
 command = "Get-ItemProperty HKLM:\\Software\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\*, HKLM:\\Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\* | Select-Object DisplayName, InstallLocation | Where-Object { $_.DisplayName -ne $null }"
 result = subprocess.run(["powershell", "-Command", command], capture_output=True, text=True)
 
 for line in result.stdout.strip().split('\n'):
     if line and not line.startswith("DisplayName"):
         parts = line.split(None, 1)
         if len(parts) == 2:
             name, install_location = parts
             if install_location and install_location.strip() != "":
                 exe_path = os.path.join(install_location.strip(), f"{name.strip()}.exe")
                 if os.path.exists(exe_path):
                     programs.append((name.strip(), exe_path))
 
 # 方法 2: 使用 winreg 直接访问注册表
 for hive in [winreg.HKEY_LOCAL_MACHINE, winreg.HKEY_CURRENT_USER]:
     for key_path in [
         r"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall",
         r"SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall"
     ]:
         try:
             with winreg.OpenKey(hive, key_path) as key:
                 for i in range(winreg.QueryInfoKey(key)[0]):
                     try:
                         subkey_name = winreg.EnumKey(key, i)
                         with winreg.OpenKey(key, subkey_name) as subkey:
                             try:
                                 name = winreg.QueryValueEx(subkey, "DisplayName")[0]
                                 install_location = winreg.QueryValueEx(subkey, "InstallLocation")[0]
                                 if install_location:
                                     exe_path = os.path.join(install_location, f"{name}.exe")
                                     if os.path.exists(exe_path):
                                         programs.append((name, exe_path))
                             except FileNotFoundError:
                                 continue
                     except WindowsError:
                         continue
         except WindowsError:
             continue
 # 方法 3: 搜索常见的程序文件夹
 common_folders = [
     os.environ.get('ProgramFiles'),
     os.environ.get('ProgramFiles(x86)'),
     os.path.join(os.environ.get('LocalAppData'), 'Programs')
 ]
 
 for folder in common_folders:
     if folder:
         for root, dirs, files in os.walk(folder):
             for file in files:
                 if file.endswith('.exe'):
                     full_path = os.path.join(root, file)
                     name = os.path.splitext(file)[0]
                     programs.append((name, full_path))
 return list(set(programs))  # 去除重复项
class MainFrame(wx.Frame):
 def __init__(self):
     super().__init__(parent=None, title='Windows 11 Program Lister')
     panel = wx.Panel(self)
     
     self.list_box = wx.ListBox(panel, pos=(10, 10), size=(580, 300))
     generate_button = wx.Button(panel, label='Generate Config', pos=(10, 320))
     generate_button.Bind(wx.EVT_BUTTON, self.on_generate)
     
     self.populate_list()
     self.Show()
 def populate_list(self):
     programs = get_installed_programs()
     for program in programs:
         self.list_box.Append(f"{program[0]}: {program[1]}")
 def on_generate(self, event):
     config = configparser.ConfigParser()
     
     for i in range(self.list_box.GetCount()):
         item = self.list_box.GetString(i)
         name, path = item.split(': ', 1)
         section = f"Button{i+1}"
         config[section] = {
             "Caption": name,
             "Link": path,
             "Color": "clGreen",
             "Width": "150",
             "Height": "70"
         }
     
     with open('buttons.ini', 'w', encoding='utf-8') as configfile:
         config.write(configfile)
     
     wx.MessageBox(f'Config file generated successfully with {self.list_box.GetCount()} buttons!', 'Info', wx.OK | wx.ICON_INFORMATION)
if __name__ == '__main__':
 app = wx.App()
 frame = MainFrame()
 app.MainLoop()
技术栈
我们将使用以下技术和库来实现这个项目:
- Python:主要编程语言
- wxPython:用于创建图形用户界面
- winreg:用于访问 Windows 注册表
- configparser:用于生成配置文件
- subprocess:用于执行 PowerShell 命令
实现过程
1. 获取已安装程序列表
获取已安装程序列表是最具挑战性的部分。我们采用了三种方法来确保尽可能多地捕获已安装的程序:
a) 使用 PowerShell 命令:
command = "Get-ItemProperty HKLM:\\Software\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\*, HKLM:\\Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\* | Select-Object DisplayName, InstallLocation | Where-Object { $_.DisplayName -ne $null }"
result = subprocess.run(["powershell", "-Command", command], capture_output=True, text=True)
b) 直接访问 Windows 注册表:
for hive in [winreg.HKEY_LOCAL_MACHINE, winreg.HKEY_CURRENT_USER]:
    for key_path in [
        r"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall",
        r"SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall"
    ]:
        # 遍历注册表项
c) 搜索常见的程序文件夹:
common_folders = [
    os.environ.get('ProgramFiles'),
    os.environ.get('ProgramFiles(x86)'),
    os.path.join(os.environ.get('LocalAppData'), 'Programs')
]
2. 创建图形用户界面
我们使用 wxPython 创建了一个简单的图形界面,包含一个列表框来显示找到的程序,以及一个按钮来触发配置文件的生成。
class MainFrame(wx.Frame):
    def __init__(self):
        super().__init__(parent=None, title='Windows 11 Program Lister')
        panel = wx.Panel(self)
        
        self.list_box = wx.ListBox(panel, pos=(10, 10), size=(580, 300))
        generate_button = wx.Button(panel, label='Generate Config', pos=(10, 320))
        generate_button.Bind(wx.EVT_BUTTON, self.on_generate)
3. 生成配置文件
当用户点击"Generate Config"按钮时,我们会为每个找到的程序创建一个配置项:
def on_generate(self, event):
    config = configparser.ConfigParser()
    
    for i in range(self.list_box.GetCount()):
        item = self.list_box.GetString(i)
        name, path = item.split(': ', 1)
        section = f"Button{i+1}"
        config[section] = {
            "Caption": name,
            "Link": path,
            "Color": "clGreen",
            "Width": "150",
            "Height": "70"
        }
    
    with open('buttons.ini', 'w', encoding='utf-8') as configfile:
        config.write(configfile)
使用说明
- 确保安装了所需的库,特别是 wxPython:pip install wxPython
- 以管理员权限运行脚本
- 程序会显示一个窗口,列出所有找到的已安装程序
- 点击"Generate Config"按钮,会在脚本所在目录生成 buttons.ini文件
潜在应用
- 系统审计:IT 管理员可以快速获取系统上安装的所有软件列表。
- 软件启动器:开发者可以使用生成的配置文件来创建自定义的程序启动器。
- 软件清理:用户可以基于这个列表识别并删除不需要的程序。
- 自动化脚本:配置文件可以被其他脚本用来批量操作或分析已安装的软件。
结果如下

 
结语
通过这个项目,我们展示了如何利用 Python 的强大功能来创建一个实用的系统工具。虽然这个工具主要针对 Windows 系统,但类似的概念可以应用到其他操作系统上。希望这个项目能激发你的创意,帮助你开发出更多有趣且实用的工具!



















