本文以实例形式展示了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程序设计的学习有所帮助。

numpyarraysarebetterfornumericaloperations 및 multi-dimensionaldata, mumemer-efficientArrays

numpyarraysarebetterforheavynumericalcomputing, whilearraymoduleisiMoresuily-sportainedprojectswithsimpledatatypes.1) numpyarraysofferversatively 및 formanceforgedatasets 및 complexoperations.2) Thearraymoduleisweighit 및 ep

ctypesallowscreatingandmanipulatingC-stylearraysinPython.1)UsectypestointerfacewithClibrariesforperformance.2)CreateC-stylearraysfornumericalcomputations.3)PassarraystoCfunctionsforefficientoperations.However,becautiousofmemorymanagement,performanceo

Inpython, "목록", isaversatile, mutablesequencetatcanholdmixeddatattypes, whilean "array"isamorememory-efficed, homogeneouseceenceRequiringElements ofthesAmeType.1) ListSareIdeAldiversEdatastorageandmanipulationDuetoIrflexibrieth

PythonlistsAndarraysareBotheBotheBothebothable.1) ListSareflexibleandsupporterogenousDatabutarabestemory-efficient.2) Arraysaremorememory-efforhomogeneousdatabutlessverstile, CorrectTypecodeusagetoavoidercer가 필요합니다.

Python과 C는 각각 고유 한 장점이 있으며 선택은 프로젝트 요구 사항을 기반으로해야합니다. 1) Python은 간결한 구문 및 동적 타이핑으로 인해 빠른 개발 및 데이터 처리에 적합합니다. 2) C는 정적 타이핑 및 수동 메모리 관리로 인해 고성능 및 시스템 프로그래밍에 적합합니다.

Python 또는 C를 선택하는 것은 프로젝트 요구 사항에 따라 다릅니다. 1) 빠른 개발, 데이터 처리 및 프로토 타입 설계가 필요한 경우 Python을 선택하십시오. 2) 고성능, 낮은 대기 시간 및 근접 하드웨어 제어가 필요한 경우 C를 선택하십시오.

매일 2 시간의 파이썬 학습을 투자하면 프로그래밍 기술을 효과적으로 향상시킬 수 있습니다. 1. 새로운 지식 배우기 : 문서를 읽거나 자습서를 시청하십시오. 2. 연습 : 코드를 작성하고 완전한 연습을합니다. 3. 검토 : 배운 내용을 통합하십시오. 4. 프로젝트 실무 : 실제 프로젝트에서 배운 것을 적용하십시오. 이러한 구조화 된 학습 계획은 파이썬을 체계적으로 마스터하고 경력 목표를 달성하는 데 도움이 될 수 있습니다.


핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

Video Face Swap
완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

뜨거운 도구

에디트플러스 중국어 크랙 버전
작은 크기, 구문 강조, 코드 프롬프트 기능을 지원하지 않음

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

Dreamweaver Mac版
시각적 웹 개발 도구

MinGW - Windows용 미니멀리스트 GNU
이 프로젝트는 osdn.net/projects/mingw로 마이그레이션되는 중입니다. 계속해서 그곳에서 우리를 팔로우할 수 있습니다. MinGW: GCC(GNU Compiler Collection)의 기본 Windows 포트로, 기본 Windows 애플리케이션을 구축하기 위한 무료 배포 가능 가져오기 라이브러리 및 헤더 파일로 C99 기능을 지원하는 MSVC 런타임에 대한 확장이 포함되어 있습니다. 모든 MinGW 소프트웨어는 64비트 Windows 플랫폼에서 실행될 수 있습니다.
