代码之家  ›  专栏  ›  技术社区  ›  davidmytton

如何在Windows上读取Python中的系统信息?

  •  1
  • davidmytton  · 技术社区  · 16 年前

    从此 OS-agnostic question this response ,类似于Linux上的/proc/meminfo等可用数据,如何使用Python从Windows读取系统信息(包括但不限于内存使用)。

    3 回复  |  直到 7 年前
        1
  •  6
  •   Kyle Bradshaw TankorSmash    8 年前

    在Windows中,如果您想从SYSTEMINFO命令中获取信息,可以使用 WMI module.

    import wmi
    
    c = wmi.WMI()    
    systeminfo = c.Win32_ComputerSystem()[0]
    
    Manufacturer = systeminfo.Manufacturer
    Model = systeminfo.Model
    

    ...

    类似地,操作系统相关信息可以从 osinfo = c.Win32_OperatingSystem()[0] system info is here os info is here

        2
  •  2
  •   Community c0D3l0g1c    7 年前

    有人问了一个类似的问题:

    How to get current CPU and RAM usage in Python?

        3
  •  2
  •   AWainb    15 年前

    您可以尝试使用我不久前创建的systeminfo.exe包装器,这有点非正统,但它似乎很容易做到这一点,而且不需要太多代码。

    import os, re
    
    def SysInfo():
        values  = {}
        cache   = os.popen2("SYSTEMINFO")
        source  = cache[1].read()
        sysOpts = ["Host Name", "OS Name", "OS Version", "Product ID", "System Manufacturer", "System Model", "System type", "BIOS Version", "Domain", "Windows Directory", "Total Physical Memory", "Available Physical Memory", "Logon Server"]
    
        for opt in sysOpts:
            values[opt] = [item.strip() for item in re.findall("%s:\w*(.*?)\n" % (opt), source, re.IGNORECASE)][0]
        return values
    

    您可以轻松地将其余的数据字段附加到sysOpts变量,不包括那些为其结果提供多行的字段,如CPU&网卡信息。regexp行的一个简单mod应该能够处理这个问题。

    享受

        4
  •  0
  •   B.R.    3 年前

    如果操作系统语言不是母语英语,给出的一些答案可能会带来麻烦。我想找个办法把包装纸包起来 systeminfo.exe

    import os
    import tempfile
    
    def get_system_info_dict():
    
        tmp_dir=tempfile.gettempdir()
        file_path=os.path.join(tmp_dir,'out')
        # Call the system command that delivers the needed information
        os.system('powershell -Command gcim WIN32_ComputerSystem -Property * >%s'%file_path)
    
        with open(file_path,'r') as fh:
            data=fh.read()
        os.remove(file_path)
    
        data_dict={}
        for line in data.split('\n'):
            try:
                k,v=line.split(':')
            except ValueError:
                continue
            k = k.strip(' ')
            v = v.strip(' ')
            if v!='':
                data_dict[k]=v
    
        return data_dict
    

    结果字典的每个键都是一个属性(英文!),相关值是为该属性存储的数据。