代碼如下:
import osimport sysimport subprocessdef get_linux_version(): print("system version---- %s" % ", ".join(sys.version.split("\n")))def get_cpu_info(): processor_cnt = 0 cpu_model = "" f_cpu_info = open("/proc/cpuinfo") try: for line in f_cpu_info: if (line.find("processor") == 0): processor_cnt += 1 elif (line.find("model name") == 0): if (cpu_model == ""): cpu_model = line.split(":")[1].strip() print("cpu counts: %s, cpu model: %s" % (processor_cnt, cpu_model)) finally: f_cpu_info.close()def get_mem_info(): mem_info = "" f_mem_info = open("/proc/meminfo") try: for line in f_mem_info: if (line.find("MemTotal") == 0): mem_info += line.strip()+ ", " elif (line.find("SwapTotal") == 0): mem_info += line.strip() break print("mem_info---- {:s}".format(mem_info)) finally: f_mem_info.close()def get_disc_info(): #disc_info = os.popen("df -h").read() #disc_info = subprocess.Popen("df -h", shell=True).communicate()[0] #print(disc_info) pipe = subprocess.Popen("df -h", stdout=subprocess.PIPE, shell=True) disc_info = pipe.stdout.read() print(disc_info)
沒有注釋,方法都很簡單,擷取版本是用python內部的sys對象;擷取CPU及記憶體資訊是直接讀/proc下面的檔案,再parse;擷取硬碟資訊則是使用shell命令,再在儲存到python變數中