python使用ctypes模块调用windowsapi获取系统版本示例

python使用ctypes模块调用windows api getversionex获取当前系统版本,没有使用python32

代码如下:

#!c:/python27/python.exe#-*- coding:utf-8 -*-

“通过调用window api判断当前系统版本”# 演示通过ctypes调用windows api函数.# 作者已经知道python32能够实现相同功能# 语句末尾加分号,纯属个人习惯# 仅作部分版本判断,更详细的版本判断推荐系统osversioninfoex结构体

import ctypes;

class osinfo(ctypes.structure): _fields_ = [ (“dwosversioninfosize”,ctypes.c_long), (“dwmajorversion”,ctypes.c_long), (“dwminorversion”,ctypes.c_long), (“dwbuildnumber”,ctypes.c_long), (“dwplatformid”,ctypes.c_long), (“szcsdversion”,ctypes.c_char*128) ];

def getsystemversionstring(): kernel32 = ctypes.windll.loadlibrary(“kernel32.dll”); os = osinfo(); os.dwosversioninfosize = ctypes.sizeof(os); if kernel32.getversionexa(ctypes.byref(os))==0: return “null version”; if os.dwplatformwindows 95″; elif os.dwmajorversion==4 and os.dwminorversion==10: verstr = “windows 98”; elif os.dwmajorversion==4 and os.dwminorversion==90: verstr = “windows me”; else: verstr = “unknown version”; elif os.dwplatformwindows nt 4.0″; elif os.dwmajorversion==5 and os.dwminorversion==0: verstr = “windows 2000”; elif os.dwmajorversion==5 and os.dwminorversion==1: verstr = “windows xp”; elif os.dwmajorversion==5 and os.dwminorversion==2: verstr = “windows 2003”; elif os.dwmajorversion==6 and os.dwminorversion==0: verstr = “windows vista”; # or 2008 elif os.dwmajorversion>=0: verstr = “windows 7”; else: verstr = “unknown version”; else: return “unknown version”; return verstr+” build”+str(os.dwbuildnumber)+” “+ctypes.string_at(os.szcsdversion);

if __name__ == “__main__”: print(getsystemversionstring());