You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Linux环境下使用Python获取可打开指定文件类型的已安装软件列表

实现方案

跨平台通用方案(基于PyQt5内置API,推荐优先使用)

Qt 5.5及以上版本内置了跨平台的MIME类型和关联应用查询接口,无需单独适配不同操作系统,代码示例如下:

from PyQt5.QtCore import QMimeDatabase, QDesktopServices

# 1. 先获取所有图片类的MIME类型
mime_db = QMimeDatabase()
all_mime_types = mime_db.allMimeTypes()
image_mime_types = [mt for mt in all_mime_types if mt.name().startswith("image/")]

# 2. 查询所有支持图片类型的已安装应用
image_apps = set()
for mt in image_mime_types:
    apps = QDesktopServices.applicationsForMimeType(mt)
    for app in apps:
        # 去重,用应用名称+可执行文件路径作为唯一标识
        app_key = (app.name(), app.executable())
        if app_key not in image_apps:
            image_apps.add(app_key)

# 3. 输出结果示例,可直接绑定到PyQt5的列表控件中
for app_name, app_exe in image_apps:
    print(f"应用名称:{app_name},可执行路径:{app_exe}")

# 4. 选中应用后打开指定图片的示例
def open_image_with_app(app_exe_path, image_path):
    import subprocess
    subprocess.Popen([app_exe_path, image_path])

注:该方法会自动适配Windows、macOS、Linux三大桌面系统的关联应用查询逻辑,无需额外处理系统差异。

分系统原生实现方案(需自主适配,适合需要自定义查询逻辑的场景)

  • Windows系统
    读取系统注册表对应文件后缀的关联配置即可,核心查询路径包括:

    1. HKEY_CLASSES_ROOT\<.后缀>\OpenWithList
    2. HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\<.后缀>\OpenWithList
      示例代码:
    import winreg
    
    def get_windows_image_apps(suffix=".png"):
        apps = []
        reg_path = rf"Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\{suffix}\OpenWithList"
        with winreg.OpenKey(winreg.HKEY_CURRENT_USER, reg_path) as key:
            for i in range(winreg.QueryInfoKey(key)[1]):
                value_name, value_data, _ = winreg.EnumValue(key, i)
                if value_name != "MRUList":
                    apps.append(value_data)
        return list(set(apps))
    
  • macOS系统
    调用系统LaunchServices框架的接口查询,可通过PyObjC模块调用原生API,也可执行shell命令查询,示例代码:

    import subprocess
    
    def get_macos_image_apps():
        cmd = ["mdfind", "kMDItemContentType == 'image/*' && kMDItemKind == 'Application'"]
        result = subprocess.check_output(cmd, text=True).strip().split("\n")
        return [app for app in result if app.endswith(".app")]
    
  • Linux系统
    读取系统和用户目录下的.desktop配置文件,匹配MIME类型字段中包含image/的条目即可,配置文件路径为/usr/share/applications/和~/.local/share/applications/,也可直接执行xdg-mime query default image/png类命令查询。

内容的提问来源于stack exchange,提问作者オパラ

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 13:45:04