Python获取电脑硬件信息及状态的实现方法

yipeiwu_com5年前Python基础

本文以实例形式展示了Python获取电脑硬件信息及状态的实现方法,是Python程序设计中很有实用价值的技巧。分享给大家供大家参考之用。具体方法如下:

主要功能代码如下:

#!/usr/bin/env python
# encoding: utf-8

from optparse import OptionParser
import os
import re
import json

def main():
  try:
    parser = OptionParser(usage="%prog [options]")
    reg_result=re.compile('\[(.*)\]')
    #add option
    parser.add_option("-m","--machine",action="store",type="string",dest="machine",help="the machine to be check")
    parser.add_option("-f","--file",action="store",type="string",dest="file",help="the file with machine list")
    parser.add_option("-n","--noah_path",action="store",type="string",dest="noah",help="the bns path or group")
    (options,args)=parser.parse_args()

    result=""
    if options.machine:
      options.machine=options.machine.replace(".baidu.com","")
      result=os.popen("meta-query entity host "+options.machine+" -f sysSuit,memTotal,diskTotal,cpuFrequency,cpuPhysicalCores,netIdc,status -j").read()
    elif options.file:
      result=os.popen("meta-query entity host -f sysSuit,memTotal,diskTotal,cpuFrequency,cpuPhysicalCores,netIdc,status -F "+options.file+" -j").read()
    elif options.noah:
      result=os.popen("get_instance_by_service "+options.noah+" |meta-query entity host -f sysSuit,memTotal,diskTotal,cpuFrequency,cpuPhysicalCores,netIdc,status -F -j").read()
    else:
      return

    result=json.loads(result)
    print "%-*s%-*s%-*s%-*s%-*s%-*s"%(40,"Name",10,"CPU",10,"memery",10,"disk",10,"IDC",10,"status")
    for item in result:
      if item['Values']['cpuFrequency']!="null":
        item['Values']['cpuFrequency']=str(float(item['Values']['cpuFrequency'])/1000.0)[0:3]
      else:
        item['Values']['cpuFrequency']="0"
      item['Values']['diskTotal']=str(float(item['Values']['diskTotal'])/1000000000.0)[0:5]
      item['Values']['memTotal']=str(float(item['Values']['memTotal'])/1024/1000.0)[0:5]
      
      print "%-*s%-*s%-*s%-*s%-*s%-*s" % (40,item['Name'],10,item['Values']['cpuFrequency']+" x"+item['Values']['cpuPhysicalCores'],10,item['Values']['memTotal']+"G",10,item['Values']['diskTotal']+"T",10,item['Values']['netIdc'],10,item['Values']['status'])
  except Exception,e:
    return

if __name__ =="__main__":
  main()

希望本文所述对大家Python程序设计的学习有所帮助。

相关文章

Python 专题四 文件基础知识

前面讲述了函数、语句和字符串的基础知识,该篇文章主要讲述文件的基础知识(与其他语言非常类似). 一. 文件的基本操作 文件是指存储在外部介质(如磁盘)上数据的集合.文件的操作流程为: 打...

Centos7 下安装最新的python3.8

Python 3.8是Python语言的最新版本,它适合用于编写脚本、自动化以及机器学习和Web开发等各种任务。现在Python 3.8已经进入官方的beta阶段,这个版本带来了许多语法...

详解Python基础random模块随机数的生成

随机数参与的应用场景大家一定不会陌生,比如密码加盐时会在原密码上关联一串随机数,蒙特卡洛算法会通过随机数采样等等。Python内置的random模块提供了生成随机数的方法,使用这些方法时...

Python标准库之多进程(multiprocessing包)介绍

Python标准库之多进程(multiprocessing包)介绍

在初步了解Python多进程之后,我们可以继续探索multiprocessing包中更加高级的工具。这些工具可以让我们更加便利地实现多进程。 进程池 进程池 (Process Pool)...

python获取元素在数组中索引号的方法

本文实例讲述了python获取元素在数组中索引号的方法。分享给大家供大家参考。具体如下: 这里python是通过index方法获取索引号的 li = ['a', 'b', 'new'...