如何从 32 位 Python 访问 64 位 Windows 环境变量?

How to access 64-bit Windows environment variables from 32-bit Python?

是否有一些相当简单的方法从 32 位 Python 读取 64 位 Windows 环境变量?

例如默认值为

os.environ['ProgramFiles']

是 r'C:\Program Files' 在 32 位环境中(这就是 os.environ 在 32 位环境中的报告 Python),但它是 r'C:\Program Files ( x86)' 在 64 位环境中。

我想从 32 位 Python 获取 64 位版本的变量。怎么样?

============================================= ======================

这部分问题是对那些迫不及待想说 "Why do you want to do that?"[= 的人的先发制人的咆哮36=],而不是回答问题。

我有充分的理由问。我正在使用 Python 来自动设置 Windows 框。它们可能 运行 32 位或 64 位 Windows,因此只有 32 位 Python 可以确保两者都 运行。但是 64 位变量的值很重要,因为它们决定了某些文件应该放在哪里。

并且 - 在你说 "just put things in "C:\Program Files" 之前,如果它是 32 位 Windows 或 "C:\Program Files (x86)" 如果它是 64 位 Windows,让我指出这些环境变量的存在是有原因的。虽然这些位置在 99% 的情况下可能是正确的,但用户可能已将这些文件夹移动到其他驱动器号或其他位置。

如果没有人查看它们,让环境变量告诉您​​事情的去向是没有意义的。 :-)

如果您是 64 位计算机上的 32 位程序 运行,则可以使用 ProgramW6432 环境变量获取 Program Files 的真实(64 位)路径Windows 的位版本:

ProgramFiles=C:\Program Files (x86)
ProgramFiles(x86)=C:\Program Files (x86)
ProgramW6432=C:\Program Files

.. 而在 32 位 OS 下的 运行 将不会设置变量。

所以在 python 中,类似于:

path = os.environ['ProgramW6432'] if 'ProgramW6432' in os.environ else os.environ['ProgramFiles']

.. 应该可以如您所愿地工作。