使用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 相关文章推荐
zbar解码二维码和条形码示例
Feb 07 Python
Python实现的几个常用排序算法实例
Jun 16 Python
在Python中操作字符串之replace()方法的使用
May 19 Python
python django 增删改查操作 数据库Mysql
Jul 27 Python
matplotlib实现热成像图colorbar和极坐标图的方法
Dec 13 Python
django项目中使用手机号登录的实例代码
Aug 15 Python
python json load json 数据后出现乱序的解决方案
Feb 27 Python
python微信公众号开发简单流程实现
Mar 09 Python
python三引号如何输入
Jul 06 Python
Django返回HTML文件的实现方法
Sep 17 Python
python中绕过反爬虫的方法总结
Nov 25 Python
Python tensorflow卷积神经Inception V3网络结构
May 06 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
实战mysql导出中文乱码及phpmyadmin导入中文乱码的解决方法
2010/06/11 PHP
CodeIgniter安全相关设置汇总
2014/07/03 PHP
Javascript实现滚动图片新闻的实例代码
2013/11/27 Javascript
eclipse导入jquery包后报错的解决方法
2014/02/17 Javascript
jquery动态更换设置背景图的方法
2014/03/25 Javascript
简介JavaScript中Math.LOG10E属性的使用
2015/06/14 Javascript
JavaScript编写页面半透明遮罩效果的简单示例
2016/05/09 Javascript
JS控制HTML元素的显示和隐藏的两种方法
2016/09/27 Javascript
详解js中call与apply关键字的作用
2016/11/21 Javascript
浅谈jQuery中Ajax事件beforesend及各参数含义
2016/12/03 Javascript
JS闭包与延迟求值用法示例
2016/12/22 Javascript
jquery+css实现简单的图片轮播效果
2017/08/07 jQuery
JavaScript获取移动设备型号的实现代码(JS获取手机型号和系统)
2018/03/10 Javascript
AngularJS模态框模板ngDialog的使用详解
2018/05/11 Javascript
在vue中使用回调函数,this调用无效的解决
2020/08/11 Javascript
[02:33]2018 DOTA2亚洲邀请赛回顾视频 再次拾起那些美妙的时刻
2018/04/10 DOTA
Python中pip安装非PyPI官网第三方库的方法
2015/06/02 Python
python 内置函数filter
2017/06/01 Python
Django与JS交互的示例代码
2017/08/23 Python
python字典快速保存于读取的方法
2018/03/23 Python
python解决js文件utf-8编码乱码问题(推荐)
2018/05/02 Python
python selenium 获取标签的属性值、内容、状态方法
2018/06/22 Python
Python Flask前后端Ajax交互的方法示例
2018/07/31 Python
Python的log日志功能及设置方法
2019/07/11 Python
如何利用python之wxpy模块玩转微信
2020/08/17 Python
学习Python需要哪些工具
2020/09/04 Python
AmazeUI 折叠面板的实现代码
2020/08/17 HTML / CSS
美国职棒大联盟的官方手套、球和头盔:Rawlings
2020/02/15 全球购物
政治思想表现评语
2014/05/04 职场文书
销售人员管理制度
2015/08/06 职场文书
女人创业励志语录,句句蕴含能量,激发你的潜能
2019/08/20 职场文书
使用springboot暴露oracle数据接口的问题
2021/05/07 Oracle
特别篇动画《总之就是非常可爱 ~制服~》PV公开,2022年夏季播出
2022/04/04 日漫
详解Alibaba Java诊断工具Arthas查看Dubbo动态代理类
2022/04/08 Java/Android
MySQ InnoDB和MyISAM存储引擎介绍
2022/04/26 MySQL
mysql sock 文件解析及作用讲解
2022/07/15 MySQL