python擷取系統資訊(系統版本,CPU資訊,記憶體資訊,硬碟資訊)

來源:互聯網
上載者:User

代碼如下:

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變數中

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.