【问题标题】:Python: How to know if the OS/CPU is 64bitsPython:如何知道操作系统/CPU 是否为 64 位
【发布时间】:2017-06-23 05:40:54
【问题描述】:

在 Windows 下,我运行的是 32 位 python.exe。我需要知道操作系统/CPU 是 64 位还是 32 位。

我的机器运行的是 Windows7 64 位。

检查了this post,并尝试运行此 Python 脚本:

import ctypes; print(32 if ctypes.sizeof(ctypes.c_voidp)==4 else 64, 'bit CPU')
import sys; print("%x" % sys.maxsize, sys.maxsize > 2**32)
import struct; print( 8 * struct.calcsize("P"))
import platform; print( platform.architecture()[0] )
print( platform.machine() )

它输出:

32 bit CPU
7fffffff False
32
32bit
AMD64

引用的帖子中没有任何建议真正为您提供 CPU/OS 架构信息。它们都报告 32 位,因为我正在运行 Python 32 位二进制文​​件。

我如何以可移植的方式确定 CPU/OS 是 32 位还是 64 位(可以在 platform.machine() 中循环使用 64 位字符串,但我怀疑这是好方法)?

【问题讨论】:

  • 那么为什么AMD64 不告诉你呢?在 32 位二进制中,其他值肯定都应该是 32 位,这是完全正常的。 AMD64x86_64 都应该告诉你 CPU 是 64 位的。
  • @MartijnPieters:是的,它告诉我,但是is_64 = (platform.machine().find( "64" ) != -1) 是一种可移植的检查方式吗?这适用于所有 64 位的 CPU/OS 吗?
  • 它适用于我尝试过的 3 种不同架构(其中一种是 VM)。
  • @MartijnPieters:好吧,这可能是一个可以接受的答案。

标签: python


【解决方案1】:

您查询的大部分信息是由解释器的字长决定的,而不是 CPU。

只有platform.machine() 会忽略此信息;它取自系统 uname -m 数据,这是推荐的命令,用于确定您的系统对于 LinuxOS X 是否为 64 位,并且 Windows 提供完全相同的信息(Python 使用 C @987654325 @函数在所有情况下)。

要么测试该字符串中的64,要么构建一组可接受的值:

'64' in platform.machine()

platform.machine() in {'x86_64', 'AMD64'}

【讨论】:

    【解决方案2】:

    来自https://stackoverflow.com/a/12578715/4124672

    您可能希望将此解决方案用于 python2.7 和更高版本:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-02-11
      • 2011-06-01
      • 2012-08-26
      • 2013-08-29
      • 2011-07-28
      • 1970-01-01
      • 2015-02-01
      • 1970-01-01
      相关资源
      最近更新 更多