使用Python擷取CPU、記憶體和硬碟等windowns系統資訊的2個例子_python

來源:互聯網
上載者:User

例子一:

Python用WMI模組擷取windowns系統的硬體資訊:硬碟分區、使用方式,記憶體大小,CPU型號,當前啟動並執行進程,自啟動程式及位置,系統的版本等資訊。

複製代碼 代碼如下:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import wmi
import os
import sys
import platform
import time

def sys_version(): 
    c = wmi.WMI ()
    #擷取作業系統版本
    for sys in c.Win32_OperatingSystem():
        print "Version:%s" % sys.Caption.encode("UTF8"),"Vernum:%s" % sys.BuildNumber
        print  sys.OSArchitecture.encode("UTF8")#系統是32位還是64位的
        print sys.NumberOfProcesses #當前系統啟動並執行進程總數

def cpu_mem():
    c = wmi.WMI ()       
    #CPU類型和記憶體
    for processor in c.Win32_Processor():
        #print "Processor ID: %s" % processor.DeviceID
        print "Process Name: %s" % processor.Name.strip()
    for Memory in c.Win32_PhysicalMemory():
        print "Memory Capacity: %.fMB" %(int(Memory.Capacity)/1048576)

def cpu_use():
    #5s取一次CPU的使用率
    c = wmi.WMI()
    while True:
        for cpu in c.Win32_Processor():
             timestamp = time.strftime('%a, %d %b %Y %H:%M:%S', time.localtime())
             print '%s | Utilization: %s: %d %%' % (timestamp, cpu.DeviceID, cpu.LoadPercentage)
             time.sleep(5)    

def disk():
    c = wmi.WMI ()   
    #擷取硬碟分區
    for physical_disk in c.Win32_DiskDrive ():
        for partition in physical_disk.associators ("Win32_DiskDriveToDiskPartition"):
            for logical_disk in partition.associators ("Win32_LogicalDiskToPartition"):
                print physical_disk.Caption.encode("UTF8"), partition.Caption.encode("UTF8"), logical_disk.Caption

    #擷取硬碟使用百分情況
    for disk in c.Win32_LogicalDisk (DriveType=3):
        print disk.Caption, "%0.2f%% free" % (100.0 * long (disk.FreeSpace) / long (disk.Size))

def network():
    c = wmi.WMI ()    
    #擷取MAC和IP地址
    for interface in c.Win32_NetworkAdapterConfiguration (IPEnabled=1):
        print "MAC: %s" % interface.MACAddress
    for ip_address in interface.IPAddress:
        print "ip_add: %s" % ip_address
    print

    #擷取自啟動程式的位置
    for s in c.Win32_StartupCommand ():
        print "[%s] %s <%s>" % (s.Location.encode("UTF8"), s.Caption.encode("UTF8"), s.Command.encode("UTF8")) 

    
    #擷取當前啟動並執行進程
    for process in c.Win32_Process ():
        print process.ProcessId, process.Name

def main():
    sys_version()
    #cpu_mem()
    #disk()
    #network()
    #cpu_use()

if __name__ == '__main__':
    main()
    print platform.system()
    print platform.release()
    print platform.version()
    print platform.platform()
    print platform.machine()

例子二:

由於我用到的不多,所以只擷取的CPU、記憶體和硬碟,如果需要其它資源,請參照msdn。

複製代碼 代碼如下:

import os
import win32api
import win32con
import wmi
import time

def getSysInfo(wmiService = None):
    result = {}
    if wmiService == None:
        wmiService = wmi.WMI()
    # cpu
    for cpu in wmiService.Win32_Processor():
        timestamp = time.strftime('%a, %d %b %Y %H:%M:%S', time.localtime())
        result['cpuPercent'] = cpu.loadPercentage
    # memory
    cs = wmiService.Win32_ComputerSystem()
    os = wmiService.Win32_OperatingSystem()
    result['memTotal'] = int(int(cs[0].TotalPhysicalMemory)/1024/1024)
    result['memFree'] = int(int(os[0].FreePhysicalMemory)/1024)
    #disk
    result['diskTotal'] = 0
    result['diskFree'] = 0
    for disk in wmiService.Win32_LogicalDisk(DriveType=3):
        result['diskTotal'] += int(disk.Size)
        result['diskFree'] += int(disk.FreeSpace)
    result['diskTotal'] = int(result['diskTotal']/1024/1024)
    result['diskFree'] = int(result['diskFree']/1024/1024)
    return result

if __name__ == '__main__':
    wmiService = wmi.WMI()
    while True:
        print getSysInfo(wmiService)
        time.sleep(3)

採用的wmi模組擷取的,由於wmi初始化時佔用系統資源太高,所以如果需要迴圈擷取,請在迴圈體外面把wmi對象初始化好,然後傳入函數裡面,這樣就不會產生CPU資源過高的情況。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.