如何在Python中查找Steam可执行文件路径及安装路径的最优方法
在Python中查找Steam安装路径与可执行文件的方法
以下是按优先级排序的可靠方案,覆盖Windows、macOS、Linux平台:
1. 优先通过注册表查询(Windows专属)
Steam会在Windows注册表中记录官方安装路径,这是最准确的获取方式,不受自定义安装位置影响。
实现代码
import winreg import os def get_steam_path_from_registry(): try: # 尝试读取32位/64位注册表项 key_paths = [ r"SOFTWARE\Valve\Steam", r"SOFTWARE\Wow6432Node\Valve\Steam" ] for key_path in key_paths: try: key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, key_path) install_path, _ = winreg.QueryValueEx(key, "InstallPath") winreg.CloseKey(key) steam_exe = os.path.join(install_path, "steam.exe") if os.path.isfile(steam_exe): return (install_path, steam_exe) return (install_path, None) except FileNotFoundError: continue return (None, None) except Exception: return (None, None)
2. 检查常见默认安装路径
如果注册表查询失败,可直接检查各平台的默认安装路径,适合快速验证。
实现代码
import os def check_common_steam_paths(): # Windows 默认路径 win_paths = [ r"C:\Program Files (x86)\Steam\steam.exe", r"C:\Program Files\Steam\steam.exe" ] for path in win_paths: if os.path.isfile(path): return (os.path.dirname(path), path) # macOS 默认路径 mac_paths = [ "/Applications/Steam.app", os.path.expanduser("~/Library/Application Support/Steam/Steam.app") ] for path in mac_paths: if os.path.exists(path): return (os.path.dirname(path), path) # Linux 默认路径 linux_paths = [ os.path.expanduser("~/.steam/steam/steam.sh"), "/usr/games/steam" ] for path in linux_paths: if os.path.isfile(path): return (os.path.dirname(path), path) return (None, None)
3. 解析开始菜单快捷方式(Windows专属)
若用户自定义了安装路径且注册表未更新,可通过Steam的开始菜单快捷方式提取目标路径。需先安装pywin32库(pip install pywin32)。
实现代码
import os import win32com.client def get_steam_path_from_shortcut(): # Steam快捷方式的默认位置 shortcut_path = r"C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Steam\Steam.lnk" if not os.path.exists(shortcut_path): return (None, None) try: shell = win32com.client.Dispatch("WScript.Shell") shortcut = shell.CreateShortCut(shortcut_path) steam_exe = shortcut.TargetPath if os.path.isfile(steam_exe): return (os.path.dirname(steam_exe), steam_exe) return (None, None) except Exception: return (None, None)
4. 整合最优查询逻辑
将上述方法按优先级整合,确保优先获取最可靠的路径:
def get_steam_paths(): # 1. 注册表查询 install_path, steam_exe = get_steam_path_from_registry() if install_path and steam_exe: return (install_path, steam_exe) # 2. 常见路径检查 install_path, steam_exe = check_common_steam_paths() if install_path and steam_exe: return (install_path, steam_exe) # 3. 快捷方式解析 install_path, steam_exe = get_steam_path_from_shortcut() return (install_path, steam_exe) # 使用示例 steam_install_dir, steam_exe_path = get_steam_paths() if steam_install_dir and steam_exe_path: print(f"Steam安装路径: {steam_install_dir}") print(f"Steam可执行文件: {steam_exe_path}") else: print("未找到Steam安装路径或可执行文件")
注意事项
- 注册表查询仅适用于Windows系统,macOS/Linux需直接检查常见路径。
- 若用户手动删除了注册表项或快捷方式,需依赖常见路径或提示用户手动指定。
- 所有路径查询后需用
os.path.exists()或os.path.isfile()验证有效性,避免返回无效路径。
内容的提问来源于stack exchange,提问作者Arjuna
相关产品推荐
相关产品推荐

