You should keep cpusets (in Linux) in mind. If you're in a cpuset, the solutions below will still give the number of real CPUs in the system, not the number available to your process. /proc/<PID>/status has some lines that tell you the number of CPUs in the current cpuset: look for Cpus_allowed_list.
–
wpoely86Sep 30 '13 at 10:59

If you're interested into the number of processors available to your current process, you have to check cpuset first. Otherwise (or if cpuset is not in use), multiprocessing.cpu_count() is the way to go in Python 2.6. The following method falls back to a couple of alternative methods in older versions of Python:

An other option is to use the psutil library, which always turn out useful in these situations:

>>> import psutil
>>> psutil.cpu_count()
2

This should work on any platform supported by psutil(unix and windows).

Note that in some occasions multiprocessing.cpu_count may raise a NotImplementedError while psutil will be able to obtain the number of CPUs. This is simply because psutil first tries to use the same techniques used by multiprocessing and, if those fail, it also uses other techniques.

multiprocessing.cpu_count() will return the number of logical CPUs, so if you have a quad-core CPU with hyperthreading, it will return 8. If you want the number of physical CPUs, use the python bindings to hwloc: