【发布时间】:2014-12-08 09:03:26
【问题描述】:
我正在用 Python 编写一个在 Windows 终端中调用 Ghostscript 的脚本。
我需要获取程序在 windows 中的安装路径(例如 Ghostcript)
有任何环境变量或任何其他方法(系统注册表)来获取路径?
解决方案(来自@abarnert 回答:)
import winreg
program_to_found = 'Software\\GPL Ghostscript'
try:
h_key = winreg.CreateKey(winreg.HKEY_LOCAL_MACHINE, program_to_found)
try:
gs_version = winreg.EnumKey(h_key, 0)
h_subkey = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, program_to_found+'\\'+gs_version)
gs_dll = (winreg.EnumValue(h_subkey,0))[1]
print("Ghostscript %s is installed in: %s" % (gs_version, gs_dll.replace('gsdll32.dll', '')))
except OSError:
print("Ghostscript insn't correctly installed!! ")
except PermissionError:
print("Ghostsript not found!! ")
这适用于winXP和win7 32位系统。
【问题讨论】:
-
你需要这个做什么?如果 Ghostscript 的路径在您的
%PATH%上,您应该可以将其作为裸名运行。如果不是(也就是说,您不能直接从 cmd 窗口使用它),Windows 一般可能无法告诉您。但是……如果 Ghostscript 已将自身安装为处理程序,例如,.ps文件,您可以通过这种方式在注册表中搜索它。或者,如果它有任何它总是创建的已知注册表项。 -
Ghostscript 不会更改 Win 中的 %PATH%。当我调用 Ghostscript 时,我需要使用完整路径来调用它,并且我不想更改脚本用户的 %PATH%。
-
好的,那么没有通用的方法来“获取已安装程序的路径”。正如我之前的评论所暗示的,有一些方法可以从文件类型关联、.msi 安装记录等中获取路径,当然还有 Ghostscript 放入注册表中的任何自定义。但是,如果一个程序有一个自定义的 .exe 安装程序,不创建任何文件类型关联,也不向注册表写入任何内容,则无需查找任何内容。
标签: python windows installation exe