In this paper, a practical method of Python acquiring computer hardware information and state is presented in an instance form, which is a useful technique in Python programming. Share for everyone to use for reference. The specific methods are as follows:
The main functional code is as follows:
#!/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,cpuphysicalc Ores,netidc,status-j "). Read () elif Options.file:result=os.popen (" meta-query entity host-f Syssuit,memtotal,di Sktotal,cpufrequency,cpuphysicalcores,netidc, status-f "+options.file+" "-j"). Read () elif options.noah:result=os.popen ("Get_instance_by_service" +options.no
ah+ "|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"% (+, "Name", "CPU", "Memery", 10 , "Disk", "IDC", "status") for the item in Result:if item[' Values ' [' cpufrequency ']!= ' null ': item[' Value S ' ['] cpufrequency ']=str (float (item[' values ' [' cpufrequency '])/1000.0) [0:3] else:item[' values '] [' Cpufrequenc Y ']= ' 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,ite m[' 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 ()
I hope this article will help you with your study of Python programming.