11月16, 2016

提供Python调用 Windows API获取系统CPU信息

在C语言中, 我们通过 Windows API提供的GetNativeSystemInfo方法, 我们可以非常方便的获取系统的CPU信息。如下所示:

#include <windows.h>
#include <stdio.h>
#pragma comment(lib, "user32.lib")

void main()
{
   SYSTEM_INFO siSysInfo;

   // Copy the hardware information to the SYSTEM_INFO structure. 

   GetNativeSystemInfo(&siSysInfo); 

   // Display the contents of the SYSTEM_INFO structure. 

   printf("  Number of processors: %d\n", 
      siSysInfo.dwNumberOfProcessors); 
   printf("  Process Achitecture: %d\n", siSysInfo.wProcessorArchitecture); 

   getchar();
}

输出如下所示:

 Number of processors: 8
 Process Achitecture: 9

如果通过Python来调用Windows API, 我们该怎么做呢?

首先,我们需要查看GetNativeSystemInfo函数的声明, 从MSDN中我们可以看到, 它需要传入一个名为SYSTEM_INFO的结构体指针,它的定义如下:

typedef struct _SYSTEM_INFO {
    union {
        DWORD dwOemId;          // Obsolete field...do not use
        struct {
            WORD wProcessorArchitecture;
            WORD wReserved;
        } DUMMYSTRUCTNAME;
    } DUMMYUNIONNAME;
    DWORD dwPageSize;
    LPVOID lpMinimumApplicationAddress;
    LPVOID lpMaximumApplicationAddress;
    DWORD_PTR dwActiveProcessorMask;
    DWORD dwNumberOfProcessors;
    DWORD dwProcessorType;
    DWORD dwAllocationGranularity;
    WORD wProcessorLevel;
    WORD wProcessorRevision;
} SYSTEM_INFO, *LPSYSTEM_INFO;

这的注意的是, SYSTEM_INFO用到了嵌套结构体, 我们都需要想想,嵌套结构体怎么在Python中进行展示。

通过查看ctypes的文档,我们发现可以通过_anonymous_来表示嵌套结构体。最后完整的代码如下所示:

# -*- coding: utf-8 -*-

from ctypes import Structure, Union,wintypes, windll, byref

class _DummyStructureName(Structure):
    _fields_ = [
        ("wProcessorArchitecture", wintypes.WORD),
        ("wReserved", wintypes.WORD),
    ]

class _DummyUnionName(Union):
    _anonymous_ = ("s",)
    _fields_ = [
        ("dwOemId", wintypes.DWORD),
        ("s", _DummyStructureName)
    ]

class SystemInfo(Structure):
    _anonymous_ = ("u", )
    _fields_  = [
        ("u", _DummyUnionName),
        ("dwPageSize", wintypes.DWORD),
        ("lpMinimumApplicationAddress", wintypes.LPVOID),
        ("lpMaximumApplicationAddress", wintypes.LPVOID),
        ("dwActiveProcessorMask", wintypes.LPVOID),
        ("dwNumberOfProcessors", wintypes.DWORD),
        ("dwProcessorType", wintypes.DWORD),
        ("dwAllocationGranularity", wintypes.DWORD),
        ("wProcessorLevel", wintypes.DWORD),
        ("wProcessorRevision", wintypes.DWORD)
    ]

    def __str__(self):
        return "处理器个数:{0},处理器类型:{1}".format(self.dwNumberOfProcessors, self.wProcessorArchitecture)

def main():
    system_info = SystemInfo()
    windll.kernel32.GetNativeSystemInfo(byref(system_info))
    print system_info


if __name__ == "__main__":
    main()

运行程序,可以得到如下结果:

处理器个数:8,处理器类型:9

处理器类型为9表述当前系统是64位系统, 如果是32位,则返回0。

参考资料:

本文链接:http://www.asyncoder.com//post/get-system-cpu-info.html

-- EOF --

Comments