You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python获取Windows 7系统主板的内存插槽总数?

Python实现获取Windows 7系统内存插槽数量

当然可以用Python实现你需要的功能,和你用PowerShell调用WMI的思路完全一致,下面给你两种靠谱的实现方式,都适配Windows 7系统:

方法1:使用wmi模块(最贴近PowerShell的写法)

这个模块专门用于Python和Windows WMI交互,语法和PowerShell的WMI调用非常相似,上手成本低。

步骤:

  1. 先安装模块(如果还没装的话):
pip install wmi
  1. 示例代码:
import wmi

def get_memory_slot_count():
    try:
        # 连接到本地WMI服务
        c = wmi.WMI()
        # 查询Win32_PhysicalMemoryArray类,和你PowerShell里的命令对应
        mem_array = c.Win32_PhysicalMemoryArray()[0]
        # MemoryDevices属性就是内存插槽的总数
        slot_count = mem_array.MemoryDevices
        return slot_count
    except Exception as e:
        print(f"查询出错: {str(e)}")
        return None

# 调用测试
slot_num = get_memory_slot_count()
if slot_num is not None:
    print(f"系统内存插槽总数: {slot_num}")

方法2:使用win32com.client(依赖pywin32,无需额外装wmi)

如果你已经在项目里用到了pywin32库,也可以直接用它来调用WMI,不需要单独安装wmi模块。

步骤:

  1. 安装pywin32(如果没装):
pip install pywin32
  1. 示例代码:
import win32com.client

def get_memory_slot_count():
    try:
        # 初始化WMI服务对象
        wmi_service = win32com.client.GetObject("winmgmts:")
        # 查询Win32_PhysicalMemoryArray实例
        mem_arrays = wmi_service.InstancesOf("Win32_PhysicalMemoryArray")
        # 通常系统只有一个物理内存数组,取第一个即可
        for mem_array in mem_arrays:
            slot_count = mem_array.MemoryDevices
            return slot_count
        return 0
    except Exception as e:
        print(f"查询出错: {str(e)}")
        return None

# 调用测试
slot_num = get_memory_slot_count()
if slot_num is not None:
    print(f"系统内存插槽总数: {slot_num}")

关键说明:

这两种方法本质上都是调用WMI的Win32_PhysicalMemoryArray类,其中MemoryDevices属性就是你要的内存插槽总数,和你PowerShell里$MEM.MemoryDevices返回的结果完全一致。

需要注意的是,运行脚本时最好以管理员权限启动Python,避免因为WMI权限不足导致查询失败,尤其是在Windows 7系统中。

内容的提问来源于stack exchange,提问作者Kiffness

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 05:26:40