This paper presents an example of how Python obtains computer hardware information and its status, and is a useful technique in Python programming. Share it for everyone's reference. Here's how:
The main function code is as follows:
#!/usr/bin/env python# encoding:utf-8from optparse import optionparserimport osimport reimport jsondef Main (): Try:p Arser = 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 () ResU lt= "" If Options.machine:options.machine=options.machine.replace (". Baidu.com", "") Result=os.popen ("Meta-quer Y 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,cpuph Ysicalcores,netidc,status-f "+options.filE+ "-j"). Read () elif options.noah:result=os.popen ("Get_instance_by_service" +options.noah+ "|meta-query entity Ho St-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", "Max", "CPU", "Memery", "Ten", "Disk", "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 ' Values ' [' item[' Memtotal (float ( item[' Values ' [' memtotal '])/1024/1000.0) [0:5] print "%-*s%-*s%-*s%-*s%-*s%-*s"% (40,item[' Name '],10,item[' Valu Es ' [' 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:returnif __name__ = = "__main__": Main ()
I hope this article is helpful to the study of Python program design.