使用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中使用item()方法遍历字典的例子
Aug 26 Python
详细介绍Python中的偏函数
Apr 27 Python
Pycharm远程调试openstack的方法
Nov 21 Python
Python中常见的异常总结
Feb 20 Python
python 编写简单网页服务器的实例
Jun 01 Python
Python实现聊天机器人的示例代码
Jul 09 Python
python实现反转部分单向链表
Sep 27 Python
在python2.7中用numpy.reshape 对图像进行切割的方法
Dec 05 Python
解决在Python编辑器pycharm中程序run正常debug错误的问题
Jan 17 Python
Python之lambda匿名函数及map和filter的用法
Mar 05 Python
PyQt5图形界面播放音乐的实例
Jun 17 Python
python 调用js的四种方式
Apr 11 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
支持oicq头像的留言簿(一)
2006/10/09 PHP
PHP register_shutdown_function函数的深入解析
2013/06/03 PHP
php使用curl通过代理获取数据的实现方法
2016/05/16 PHP
phpinfo()中Loaded Configuration File(none)的解决方法
2017/01/16 PHP
[原创]php使用strpos判断字符串中数字类型子字符串出错的解决方法
2017/04/01 PHP
php str_getcsv把字符串解析为数组的实现方法
2017/04/05 PHP
老生常谈PHP面向对象之解释器模式
2017/05/17 PHP
学习ExtJS Panel常用方法
2009/10/07 Javascript
JavaScript 函数参数是传值(byVal)还是传址(byRef) 分享
2013/07/02 Javascript
javaScript NameSpace 简单说明介绍
2013/07/18 Javascript
js操作模态窗口及父子窗口间相互传值示例
2014/06/09 Javascript
jQuery 仿百度输入标签插件附效果图
2014/07/04 Javascript
一个通过script自定义属性传递配置参数的方法
2014/09/15 Javascript
JavaScript数组各种常见用法实例分析
2015/08/04 Javascript
基于Vue实现页面切换左右滑动效果
2020/06/29 Javascript
fullpage.js最后一屏滚动方式
2018/02/06 Javascript
微信打开网址添加在浏览器中打开提示的办法
2019/05/20 Javascript
electron+vue实现div contenteditable截图功能
2020/01/07 Javascript
在 Vue 中编写 SVG 图标组件的方法
2020/02/24 Javascript
[00:31]DOTA2上海特级锦标赛 Fnatic战队宣传片
2016/03/04 DOTA
在Mac OS上部署Nginx和FastCGI以及Flask框架的教程
2015/05/02 Python
python matplotlib中文显示参数设置解析
2017/12/15 Python
python实现名片管理系统
2018/11/29 Python
用python写爬虫简单吗
2020/07/28 Python
编写python代码实现简单抽奖器
2020/10/20 Python
HTML5 语音搜索只需一句代码
2013/01/03 HTML / CSS
饿了么订餐官网:外卖、网上订餐
2019/06/28 全球购物
Ooni英国官网:披萨烤箱
2020/05/31 全球购物
什么是.net
2015/08/03 面试题
社区七一党员活动方案
2014/01/25 职场文书
担保书格式及范文
2014/04/01 职场文书
《草原的早晨》教学反思
2014/04/08 职场文书
个人合作协议书范本
2014/04/18 职场文书
最美家庭活动方案
2014/08/31 职场文书
2015年度护士个人工作总结
2015/04/09 职场文书
开工典礼致辞
2015/07/29 职场文书