使用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函数嵌套实例
Sep 23 Python
python之matplotlib学习绘制动态更新图实例代码
Jan 23 Python
利用python打开摄像头及颜色检测方法
Aug 03 Python
详解python爬虫系列之初识爬虫
Apr 06 Python
python 实现返回一个列表中出现次数最多的元素方法
Jun 11 Python
python常用库之NumPy和sklearn入门
Jul 11 Python
Django密码存储策略分析
Jan 09 Python
使用AJAX和Django获取数据的方法实例
Oct 25 Python
python用700行代码实现http客户端
Jan 14 Python
python中最小二乘法详细讲解
Feb 19 Python
详解Python requests模块
Jun 21 Python
python和C/C++混合编程之使用ctypes调用 C/C++的dll
Apr 29 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
环境会对咖啡种植有什么影响
2021/03/03 咖啡文化
PHP4实际应用经验篇(9)
2006/10/09 PHP
Gambit vs ForZe BO3 第三场 2.13
2021/03/10 DOTA
javascript一些不错的函数脚本代码
2008/09/10 Javascript
jquery一句话全选/取消全选
2011/03/01 Javascript
JavaScript中json使用自己总结
2013/08/13 Javascript
使用js的replace()方法查找字符示例代码
2013/10/28 Javascript
javascript日期计算实例分析
2015/06/29 Javascript
浅谈angularJS中的事件
2016/07/12 Javascript
原生js实现无限循环轮播图效果
2017/01/20 Javascript
Vue from-validate 表单验证的示例代码
2017/09/26 Javascript
Angular2的管道Pipe的使用方法
2017/11/07 Javascript
Vue实现双向绑定的原理以及响应式数据的方法
2018/07/02 Javascript
js+css实现红包雨效果
2018/07/12 Javascript
node和vue实现商城用户地址模块
2018/12/05 Javascript
使用layui的router来进行传参的实现方法
2019/09/06 Javascript
layer.alert回调函数执行关闭弹窗的实例
2019/09/11 Javascript
VUE渲染后端返回含有script标签的html字符串示例
2019/10/28 Javascript
axios封装与传参示例详解
2020/10/18 Javascript
Vue select 绑定动态变量的实例讲解
2020/10/22 Javascript
微信小程序视频弹幕发送功能的实现
2020/12/28 Javascript
[28:48]《真视界》- 2017年国际邀请赛
2017/09/27 DOTA
Python中的引用和拷贝浅析
2014/11/22 Python
Flask模拟实现CSRF攻击的方法
2018/07/24 Python
Python 3.8 新功能全解
2019/07/25 Python
Python目录和文件处理总结详解
2019/09/02 Python
python判断两个序列的成员是否一样的实例代码
2020/03/01 Python
python怎么判断模块安装完成
2020/06/19 Python
详解selenium + chromedriver 被反爬的解决方法
2020/10/28 Python
Herschel Supply Co.美国:背包、手提袋及配件
2020/11/24 全球购物
营销与策划个人求职信
2013/09/22 职场文书
经济与贸易专业应届生求职信
2013/11/19 职场文书
四好少年事迹材料
2014/01/12 职场文书
新郎新娘答谢词
2015/01/04 职场文书
MySql存储过程之逻辑判断和条件控制
2021/05/26 MySQL
JS实现刷新网页后之前浏览位置保持不变示例详解
2022/08/14 Javascript