1

如何在 python 2.4 中获取 cpuinfo。我想确定一台机器中的处理器数量。(代码应该独立于操作系统)。我已经为 Linux 编写了代码,但不知道如何使它适用于 Windows。

import subprocess, re
cmd = 'cat /proc/cpuinfo |grep processor |wc'
d = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
lines = d.stdout.readlines()
lines = re.split('\s+', lines[0])
number_of_procs = int(lines[1])

假设我没有在 windows 机器上安装 cygwin,我只有 python2.4。请让我知道是否有可以为此目的调用的模块,或者任何帮助编写此功能的代码。

谢谢, 桑迪亚

4

5 回答 5

5

在 python 2.6+ 上:

>>> import multiprocessing
>>> multiprocessing.cpu_count()
2

由于重复的问题,更新标记为关闭。请参阅How to find the number of CPUs using python中的第二个答案,以了解在没有多处理模块的情况下执行此操作的方法。

于 2011-02-08T06:05:46.180 回答
1

好吧,这不会是跨平台的,因为您依赖于 /proc 文件系统,这是 Windows 所没有的(虽然,是的,如果它确实如此......)

一种选择是使用一些“if”来确定平台类型,然后对于 Linux 从 /proc/cpuinfo 获取您的信息,对于 Windows 从 WMI (Win32_Processor) (http://www.activeexperts.com/admin) 获取您的信息/scripts/wmi/python/0356/)

platform.processor() 应该在某种程度上独立于平台。正如文档所说,并非所有平台都实现它。

http://docs.python.org/library/platform.html

于 2011-02-08T05:40:42.077 回答
1

这是 Bruce Eckel 编写的旧解决方案,应该适用于所有主要平台:http ://codeliberates.blogspot.com/2008/05/detecting-cpuscores-in-python.html

def 检测CPUs():
 """
 检测系统上的 CPU 数量。抄自pp。
 """
 # Linux、Unix 和 MacOS:
 如果有属性(操作系统,“sysconf”):
     如果 os.sysconf_names.has_key("SC_NPROCESSORS_ONLN"):
         # Linux 和 Unix:
         ncpus = os.sysconf("SC_NPROCESSORS_ONLN")
         如果 isinstance(ncpus, int) 且 ncpus > 0:
             返回 ncpus
     其他:#OSX:
         返回 int(os.popen2("sysctl -n hw.ncpu")[1].read())
 # 窗户:
 如果 os.environ.has_key("NUMBER_OF_PROCESSORS"):
         ncpus = int(os.environ["NUMBER_OF_PROCESSORS"]);
         如果 ncpus > 0:
             返回 ncpus
 返回 1 # 默认
于 2011-02-08T05:47:16.607 回答
0

您可以使用cpuidpy,它使用 x86 CPUID 指令来获取 CPU 信息。

于 2011-02-08T05:52:07.737 回答
0

目的既不是简洁,也不是紧凑,甚至不是优雅;-),而是尝试成为教学法让你接近(或者你是否遇到了伟大的 cpuinfo 模块的麻烦),这可能是一个块:

import re, subprocess, pprint
pp = pprint.PrettyPrinter(indent=2)

cmd = ['cat', '/proc/cpuinfo']
process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = process.communicate()
if not stdout:
    print('ERROR assessing /proc/cpuinfo')
else:
    output = stdout.strip().split("\n")
    processors = []
    element_regex = re.compile(r'processor\t\:\s\d+')
    for item in output:
        if element_regex.match(item):
            processors.append([])
        processors[-1].append(item)
    cores = []
    for processor in processors:
        regex = re.compile('(cpu\scores\t\:\s(\d+)|physical\sid\t\:\s    (\d+))')
        core = [m.group(1) for item in processor for m in [regex.search(item)] if m]
        if core not in cores:
            cores.append(core)
    pp.pprint(cores)

当您的目标主板上有一个嵌入 4 个物理内核的物理 CPU 时,您应该得到如下结果:

[['physical id\t: 0', 'cpu cores\t: 4']]
于 2021-07-26T05:56:53.137 回答