让树莓派定时说出温度和CPU使用情况

让树莓派定时说出温度和CPU使用情况

乱凑凑出来的,能达到我想要的目的就行_(:з」∠)_

前几天看到了一个利用百度语音接口让树莓派定时说天气的功能,所以我就想着,能不能让他定时说出温度,于是就抱着试一试的心态折腾了半天。。。因为我完全不会Python,全是靠百度和谷歌凑出来的,可能脚本有点滑稽,但能达到我想要的目的就行_(:з」∠)_,能够定时说出温度和cpu使用情况,就随便分享一下吧~

环境

  • 音箱*1
  • 树莓派*1
  • Python3.4
  • 依赖:Requests

脚本内容

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import requests
import os

headers = {
  'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit'
  '/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safar'
  'i/537.36',
}
def getCPUtemperature():
  res = os.popen('vcgencmd measure_temp').readline()
  return(res.replace("temp=","").replace("'C\n",""))
  
def getCPUuse():
  return(str(os.popen("top -n1 | awk '/Cpu\(s\):/ {print $2}'").readline().strip()))

CPU_temp = getCPUtemperature()
CPU_usage = getCPUuse()

text = '树莓派现在的CPU温度为%s度,CPU使用百分之%s' % \
  (CPU_temp, CPU_usage)
url = u'http://tts.baidu.com/text2audio?idx=1&tex={0}&cuid=baidu_speech_' \
  u'demo&cod=2&lan=zh&ctp=1&pdt=1&spd=4&per=4&vol=5&pit=5'.format(text)
res = requests.get(url, headers=headers)
with open(u'1.mp3', u'wb') as f:
  f.write(res.content)
def main():
  mp3path2 = os.path.join(os.path.dirname(__file__), '2.mp3')
  os.system('mplayer %s' % mp3path2)
  mp3path1 = os.path.join(os.path.dirname(__file__), '1.mp3')
  os.system('mplayer %s' % mp3path1)
if __name__ == '__main__':
  main()

定时任务

  • crontab -e
  • 1 */3 * * * python /root/cpu.py #每三小时报告一次
署名 - 非商业性使用 - 禁止演绎 4.0