【问题标题】:Is there a way to find the path of an application with standard libraries?有没有办法使用标准库找到应用程序的路径?
【发布时间】:2013-08-05 09:06:27
【问题描述】:
我想知道是否可以找到Windows 7下的应用程序的安装目录,例如MS Excel,带有标准的python 2.7库。我的意思是,它不应该使用任何 pywin32 或 xlrd 等。
也许它会查找注册表以找到安装路径?
【问题讨论】:
-
_winreg 与 HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Office\**\Common\InstallRoot 作为键?
标签:
python
windows
installation-path
【解决方案1】:
这可能很棘手,但是一种方法是在 HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\foo.exe 中搜索启动器 exe 位置
因此是这样的(我这台电脑上没有 Windows,所以如果发现错误欢迎编辑;),代码应该兼容 Python 2 和 3):
try:
import winreg
except ImportError:
import _winreg as winreg
handle = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE,
r"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\excel.exe")
num_values = winreg.QueryInfoKey(handle)[1]
for i in range(num_values):
print(winreg.EnumValue(handle, i))
在 Python 2 上,模块名为 _winreg,但在 Python 3 上名为 winreg。