python获取底层硬件信息
warning:
这篇文章距离上次修改已过1000天,其中的内容可能已经有所变动。
CPU 架构
import platform
print("操作系统名称及版本号:",platform.platform()) #获取操作系统名称及版本号
print("操作系统版本号:",platform.version()) #获取操作系统版本号
print("操作系统的位数:",platform.architecture()) #获取操作系统的位数
print("计算机类型:",platform.machine()) # 计算机类型
print("计算机网络名称:",platform.node()) #计算机网络名称
print("计算机处理器信息:",platform.processor()) #计算机处理器信息
print("上面所有的信息汇总:",platform.uname()) #上面所有的信息汇总
CPU 核数
# 方法一:
# 如果当前Python版本大于2.6,可以简单的通过下面模块来获取当前cpu数量,
import multiprocessing
print("CPU 核数:",multiprocessing.cpu_count())
# 如果是比较老的Python版本,可以用下面的模块来获取当前cpu数量:
import psutil
print("CPU 核数:",psutil.cpu_count())
# 方法二:
# Python可以读系统文件/proc/cpuinfo,过滤“processor”字段统计核心数。
def get_cpu_info():
processor_cnt = 0
cpu_model = ""
f_cpu_info = open("/proc/cpuinfo")
try:
for line in f_cpu_info:
# print(line)
if (line.find("processor") == 0):
processor_cnt += 1
print("cpu counts:{}" .format(processor_cnt))
finally:
f_cpu_info.close()
get_cpu_info()
内存信息
# 读取内存信息可以直接读系统文件/proc/meminfo。
def get_mem_info():
mem_info = ""
f_mem_info = open("/proc/meminfo")
try:
for line in f_mem_info:
# print(line.strip())
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()
get_mem_info()
磁盘信息
import os
import subprocess
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)
get_disc_info()
网络信息
import netifaces
routingGateway = netifaces.gateways()['default'][netifaces.AF_INET][0] #网关
routingNicName = netifaces.gateways()['default'][netifaces.AF_INET][1] #网络适配器信息
for interface in netifaces.interfaces():
if interface == routingNicName:
#print (netifaces.ifaddresses(interface))
try:
routingIPAddr = netifaces.ifaddresses(interface)[netifaces.AF_INET][0]['addr'] #获取IP
except KeyError:
pass
#print ("Routing IP Address:%s"% routingIPAddr)
return routingIPAddr
if __name__ == "__main__":
try:
print ("Routing IP Address:",GetNetworkIP())
except:
print ("Unable to get the address, there may not be installed netifaces module! command:pip install netifaces")