好记性不如铅笔头

linux, 操作系统, 树莓派

树莓派学习笔记:获取运行状态

最近在一边学习树莓派一边学习python,恰好在网上找到了一些获取树莓派运行状态的代码。这里就拿来备份一下。

说明:

由于查找的资料比较多,网址记不全了,就没在这里附上参考网址,如果原作者看到,请联系我,我把网址附上

网上的代码很多是python2的,我自己改成了python3。

源码:

#获取cpu温度
def get_cpu_temp():
    tempFile = open("/sys/class/thermal/thermal_zone0/temp");
    cpu_temp = tempFile.read();
    tempFile.close();
    return float(cpu_temp)/1000;

#获取gpu温度 
def get_gpu_temp():
	import subprocess; 
	outputStr = str(subprocess.check_output(["/opt/vc/bin/vcgencmd", "measure_temp"]), encoding = "utf-8");
	outputStr = outputStr.replace('temp=','');
	gpu_temp = outputStr.replace('\'C','');
	return float(gpu_temp);
	
#获取上一分钟负载
def get_load_avg():
    f = open("/proc/loadavg");
    con = f.read().split();
    f.close();
    return float(con[0]);

#获取CPU使用率
def readCpuInfo():
	f = open('/proc/stat');
	lines = f.readlines();
	f.close();
	for line in lines:
		line = line.lstrip();
		counters = line.split();
		if len(counters) < 5:
			continue;
		if counters[0].startswith('cpu'):
			break;
	total = 0;
	for i in range(1, len(counters)):
		total = total + int(counters[i]);
	idle = int(counters[4]);

	return float(1- idle/total);
#  return {'total':total, 'idle':idle}

#获取内存使用率
def readMemInfo():
	res = {'total':0, 'free':0, 'buffers':0, 'cached':0};
	f = open('/proc/meminfo');
	lines = f.readlines();
	f.close();

	i = 0;
	for line in lines:
		if i == 4:
			break;
		line = line.lstrip();
		memItem = line.lower().split();
		if memItem[0] == 'memtotal:':
			res['total'] = int(memItem[1]);
			i = i + 1;
			continue;
		elif memItem[0] == 'memfree:':
			res['free'] = int(memItem[1]);
			i = i +1;
			continue;
		elif memItem[0] == 'buffers:':        
			res['buffers'] = int(memItem[1]);
			i = i +1;
			continue;
		elif memItem[0] == 'cached:':
			res['cached'] = int(memItem[1]);
			i = i +1;
			continue;
	
	used = res['total'] - res['free'] - res['buffers'] - res['cached'];
	total = res['total'];
	return float(used/total);    

def printPiInfo():
	print("CPU temp: " + str(get_cpu_temp()) );
	print("GPU temp: " + str(get_gpu_temp()) );
	print("LoadAvg:" + str(get_load_avg()) );
	print("CPU Usage:" + str(readCpuInfo()) );
	print("MEM Usage:" + str(readMemInfo()) );
	  
if __name__ == '__main__':
	printPiInfo();

运行结果:

pi@raspberrypi ~ $ python3 printInfo.py 
CPU temp: 43.312
GPU temp: 43.3
LoadAvg:0.19
CPU Usage:0.0617740033280737
MEM Usage:0.14175680982471173

 

Leave a Reply

13 + 2 =

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据