在Python中检测64位操作系统(Windows)

44 投票
23 回答
50787 浏览
提问于 2025-04-15 18:56

有没有人知道我该怎么在Python中检测Windows的位数版本?我需要知道这个信息,以便使用正确的程序文件夹。

非常感谢!

23 个回答

38

我想你可以去查看一下 os.environ['PROGRAMFILES'],那里会有程序文件夹的路径。

67

我觉得Mark Ribau给出的解决方案是最好的。

对于Python 2.7及更新版本,最好的答案是:

def is_os_64bit():
    return platform.machine().endswith('64')

在Windows系统上,跨平台的函数 platform.machine() 内部使用了Matthew Scouten提到的环境变量。

我发现了以下值:

  • WinXP-32: x86
  • Vista-32: x86
  • Win7-64: AMD64
  • Debian-32: i686
  • Debian-64: x86_64

对于Python 2.6及更早版本:

def is_windows_64bit():
    if 'PROCESSOR_ARCHITEW6432' in os.environ:
        return True
    return os.environ['PROCESSOR_ARCHITECTURE'].endswith('64')

要找出Python解释器的位数版本,我使用:

def is_python_64bit():
    return (struct.calcsize("P") == 8)
31

platform模块 -- 用来获取底层平台的识别数据

>>> import platform
>>> platform.architecture()
('32bit', 'WindowsPE')

在64位的Windows系统上,32位的Python会返回:

('32bit', 'WindowsPE')

这意味着这个答案虽然被接受了,但其实是错误的。 请查看下面的一些答案,看看有没有适合不同情况的解决方案。

撰写回答