描述:之前查看树莓派的温度一直都需要输命令: cd /sys/class/thermal/thermal_zone0 然后cat temp 才能给出数据比如45084,给出的数据需要除以1000才是实际温度值,路径太长很不方便,因此想写个脚本运行后自动给出结果。
网上已经有相关的帖子,作为小白自然是拿来先跑一跑试试
参考文章 http://shumeipai.nxez.com/2014/10/04/get-raspberry-the-current-status-and-data.html
http://blog.csdn.net/xukai871105/article/details/38349209
网络源码如下:
def getCPUtemperature():
res = os.popen(' cd sys/class/thermal/thermal_zone0/temp').readline()
return(res.replace("temp=","").replace("'C\n",""))
提示没有权限
3
def getCPUtemperature():
res = os.popen(' sudo cd sys/class/thermal/thermal_zone0/temp').readline()
return(res.replace("temp=","").replace("'C\n",""))
执行结果显示的温度是五位整数,显然除以1000才合适
刚开始试图直接用res除以1000,若干次失败尝试之后发现:提示真的是个好东西
系统早就提示了,字符串不能进行算术运算.....
接着:我详细了解了
def函数 (自定义函数)
return()(每个函数都必须有的返回值)
res (列表)
os.popen 格式: os.popen(command[, mode[, bufsize]])括号内是执行的一段程序,程序的值返回给变量
详情链接 http://www.runoob.com/python/os-popen.html
readline() read() readlines() 的区别 ,在这里os.popen()括号内的程序实现的功能是读取temp文件的内容并转换成
string格式(字符串格式),replace()在这里的功能是将所读取内容中的逗号和空格删除(thermal_zone0路径下的temp
中只有一个五位数,用不着去空格)
另外,read()readline()readlines()是文件的属性,是用来读写文件内容的
print('CPU Temperature = '+CPU_temp) 在打印结束阶段,print()中的+号起到了字符串连接的功能,
因为temp中的数字是以字符串的形式保存的,不能直接进行除以1000这样的运算,必须将字符串转换成浮点型再做运算
运算完成后还需要将浮点型的结果再转换成字符串,配合打印阶段的字符串连接。也就形成了下面的这段程序:
def getCPUtemperature():
res = os.popen('sudo cat /sys/class/thermal/thermal_zone0/temp').readline()
tempfloat=float(res) / 1000
temp=str(tempfloat)
return(temp)
修改完后运行成功。