1

How can I get cpuinfo in python 2.4. I want to determine number of processors in a machine. (The code should be OS independent). I have written the code for Linux, but don't know how to make it work for 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])

Assuming that I don't have cygwin installed on windows machine, I just have python2.4. Please let me know if there's some module which can be called for this purpose, or any help to write the code for this functionality.

Thanks, Sandhya

user225312
  • 126,773
  • 69
  • 172
  • 181
Sandhya Jha
  • 356
  • 1
  • 7
  • 18
  • 1
    possible duplicate of [How to find out the number of CPUs in python](http://stackoverflow.com/questions/1006289/how-to-find-out-the-number-of-cpus-in-python) – Sam Dolan Feb 08 '11 at 07:01

5 Answers5

5

On python 2.6+:

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

Update Marked for close because of a duplicate question. See the second answer in How to find out the number of CPUs using python for a way to do it without the multiprocessing module.

Community
  • 1
  • 1
Sam Dolan
  • 31,966
  • 10
  • 88
  • 84
1

Well, that will not be cross platform, as you're relying on the /proc filesystem, which is something Windows does not have (although, yes, it would be epically awesome if it did...)

One option is to use a few "if's" to determine the platform type, then for Linux grab your info from /proc/cpuinfo and for Windows grab your info from WMI (Win32_Processor) (http://www.activexperts.com/admin/scripts/wmi/python/0356/)

platform.processor() should be somewhat platform independent though. As the docs say, not all platforms implement it.

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

dotalchemy
  • 2,459
  • 19
  • 24
1

Here's on old solution written by Bruce Eckel that should work on all major platforms: http://codeliberates.blogspot.com/2008/05/detecting-cpuscores-in-python.html

def detectCPUs():
 """
 Detects the number of CPUs on a system. Cribbed from pp.
 """
 # Linux, Unix and MacOS:
 if hasattr(os, "sysconf"):
     if os.sysconf_names.has_key("SC_NPROCESSORS_ONLN"):
         # Linux & Unix:
         ncpus = os.sysconf("SC_NPROCESSORS_ONLN")
         if isinstance(ncpus, int) and ncpus > 0:
             return ncpus
     else: # OSX:
         return int(os.popen2("sysctl -n hw.ncpu")[1].read())
 # Windows:
 if os.environ.has_key("NUMBER_OF_PROCESSORS"):
         ncpus = int(os.environ["NUMBER_OF_PROCESSORS"]);
         if ncpus > 0:
             return ncpus
 return 1 # Default
shang
  • 24,642
  • 3
  • 58
  • 86
0

You could use cpuidpy, which uses x86 CPUID instruction to get CPU information.

Imran
  • 87,203
  • 23
  • 98
  • 131
0

The purpose is nor conciseness neither compactness, not even elegance ;-), but an attemps to be pedagogic keeping you approach (or whether you get in trouble with the great cpuinfo module), that could be a chunk like:

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)

You should a result as below, when you have one physical CPU with embedding 4 physical cores on your target motherboard:

[['physical id\t: 0', 'cpu cores\t: 4']]