欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2023-11-03 22:09:10
python使用ctypes模块调用windows api getversionex获取当前系统版本,没有使用python32 复制代码 代码如下:#!c:/pytho...

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.dwplatformid==1: #windows 95/98/me
        if os.dwmajorversion==4 and os.dwminorversion==0:
            verstr = "windows 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.dwplatformid==2: #windows vista/server 2008/server 2003/xp/2000/nt
        if os.dwmajorversion==4 and os.dwminorversion==0:
            verstr = "windows 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());