【问题标题】:How can I read system information in Python on Windows?如何在 Windows 上读取 Python 中的系统信息?
【发布时间】:2010-10-02 19:52:58
【问题描述】:

根据这个OS-agnostic question,特别是this response,类似于Linux上的/proc/meminfo之类的数据,我如何使用Python从Windows读取系统信息(包括但不限于内存使用) .

【问题讨论】:

标签: python windows operating-system


【解决方案1】:

在 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 hereos info is here 的完整列表

【讨论】:

    【解决方案2】:

    有人问过类似的问题:

    How to get current CPU and RAM usage in Python?

    有很多答案告诉你如何在 windows 中完成此操作。

    【讨论】:

      【解决方案3】:

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

      这应该可以在 2000/XP/2003 服务器上运行,并且应该可以在 Vista 和 Win7 上运行,前提是它们带有 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 和 NIC 信息。对正则表达式行的简单修改应该能够处理。

      享受吧!

      【讨论】:

        【解决方案4】:

        如果操作系统语言不是母语英语,则给出的某些答案可能会造成麻烦。我搜索了一种方法来包装 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
        

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

        【讨论】:

          猜你喜欢
          • 2010-10-02
          • 1970-01-01
          • 2010-09-25
          • 2022-06-17
          • 2011-03-07
          • 1970-01-01
          • 2010-10-02
          • 2010-11-09
          • 1970-01-01
          相关资源
          最近更新 更多