使用Python获取CPU、内存和硬盘等windowns系统信息的2个例子


Posted in Python onApril 15, 2014

例子一:

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资源过高的情况。

Python 相关文章推荐
Python使用xlrd读取Excel格式文件的方法
Mar 10 Python
Python的Bottle框架的一些使用技巧介绍
Apr 08 Python
Python 利用pydub库操作音频文件的方法
Jan 09 Python
Python实现的爬取小说爬虫功能示例
Mar 30 Python
基于Python实现签到脚本过程解析
Oct 25 Python
python异常处理try except过程解析
Feb 03 Python
如何使用pandas读取txt文件中指定的列(有无标题)
Mar 05 Python
使用Python实现将多表分批次从数据库导出到Excel
May 15 Python
Python selenium如何打包静态网页并下载
Aug 12 Python
Python卷积神经网络图片分类框架详解分析
Nov 07 Python
Python使用永中文档转换服务
May 06 Python
pytest实现多进程与多线程运行超好用的插件
Jul 15 Python
python中使用sys模板和logging模块获取行号和函数名的方法
Apr 15 #Python
python 动态获取当前运行的类名和函数名的方法
Apr 15 #Python
python使用百度翻译进行中翻英示例
Apr 14 #Python
python使用xauth方式登录饭否网然后发消息
Apr 11 #Python
python判断、获取一张图片主色调的2个实例
Apr 10 #Python
Python使用新浪微博API发送微博的例子
Apr 10 #Python
一个检测OpenSSL心脏出血漏洞的Python脚本分享
Apr 10 #Python
You might like
使用php实现截取指定长度
2013/08/06 PHP
zf框架的session会话周期及次数限制使用示例
2014/03/13 PHP
如何使用php脚本给html中引用的js和css路径打上版本号
2015/11/18 PHP
深入浅析php json 格式控制
2015/12/24 PHP
thinkphp,onethink和thinkox中验证码不显示的解决方法分析
2016/06/06 PHP
jQuery判断当前点击的是第几个li的代码
2014/09/26 Javascript
Javascript URI 解析介绍
2015/03/15 Javascript
jQuery中JSONP的两种实现方式详解
2016/09/26 Javascript
javascript 内置对象及常见API详细介绍
2016/11/01 Javascript
jQuery居中元素scrollleft计算方法示例
2017/01/16 Javascript
理解 Node.js 事件驱动机制的原理
2017/08/16 Javascript
Windows下Node爬虫神器Puppeteer安装记
2019/01/09 Javascript
vue中$nextTick的用法讲解
2019/01/17 Javascript
详解微信小程序-扫一扫 wx.scanCode() 扫码大变身
2019/04/30 Javascript
vue中datepicker的使用教程实例代码详解
2019/07/08 Javascript
vue webpack重写cookie路径的方法
2019/07/10 Javascript
Nuxt.js 静态资源和打包的操作
2020/11/06 Javascript
[39:52]2018DOTA2亚洲邀请赛 4.3 突围赛 EG vs Newbee 第一场
2018/04/04 DOTA
跟老齐学Python之Import 模块
2014/10/13 Python
详解Python中 __get__和__getattr__和__getattribute__的区别
2016/06/16 Python
python 调用win32pai 操作cmd的方法
2017/05/28 Python
利用Python将时间或时间间隔转为ISO 8601格式方法示例
2017/09/05 Python
使用Python操作excel文件的实例代码
2017/10/15 Python
Python3中lambda表达式与函数式编程讲解
2019/01/14 Python
pytorch numpy list类型之间的相互转换实例
2019/08/18 Python
Python网络编程之使用TCP方式传输文件操作示例
2019/11/01 Python
Jmeter HTTPS接口测试证书导入过程图解
2020/07/22 Python
python实现简单遗传算法
2020/09/18 Python
安全的后院和健身蹦床:JumpSport
2019/07/15 全球购物
北欧最好的童装网上商店:Babyshop
2019/09/15 全球购物
Groupon荷兰官方网站:高达70%的折扣
2019/11/01 全球购物
车工岗位职责
2013/11/26 职场文书
职工运动会邀请函
2014/01/19 职场文书
优秀毕业自我鉴定
2014/02/15 职场文书
pytorch 实现在测试的时候启用dropout
2021/05/27 Python
MySQL实现用逗号进行拼接、以逗号进行分割
2022/12/24 MySQL