Raspberry Pi を入れたので、一旦ログを取るようにしました
取るのは、CPU 温度
今回は python で取得することにしました
取得したデータは Google SpreadSheet に保存するようにしました
1. gspread のインストール
今回は python の gspread を pip を使ってインストールします
$ sudo python-pip install gspread
もし、「python-pip: command not found」が表示された場合、
python-pip が存在しないので、そちらをまず入れましょう
$ sudo yum install python-pip
2. コード
動きとしては下記のような感じ
- 環境変数 G_USER と G_PASS を用いて、Google に接続します
- Google ドキュメントに準備しておいた raspberrypi という spread sheet を開きます
- 現在の年月を用いて cpu_temp__%Y%m というワークシートを開きます
アカウントとパスワードは環境変数から取得するようになってます
直接書いてもいいですね
#!/usr/bin/python2.6 # -*- coding: utf-8 -*- import gspread import sqlite3 import sys import datetime reload(sys) sys.setdefaultencoding('utf-8') # google spread にログイン gc = gspread.login(os.environ["G_USER"], os.environ["G_PASS"]) # google spread sheet をオープン ss = gc.open("raspberrypi") # worksheet をオープン tdatetime = datetime.datetime.now() print tdatetime.strftime('%Y%m') try: ws = ss.worksheet("cpu_temp__" + tdatetime.strftime('%Y%m')) except gspread.exceptions.WorksheetNotFound: ss.add_worksheet("cpu_temp__" + tdatetime.strftime('%Y%m'), 100, 100) ws = ss.worksheet("cpu_temp__" + tdatetime.strftime('%Y%m')) ws.update_cell(1, 1, "no") ws.update_cell(1, 2, "temp") ws.update_cell(1, 3, "updateddate") if ws.cell(ws.row_count, 1).value is not None: ws.resize( ws.row_count + 100) f = open("/sys/class/thermal/thermal_zone0/temp", "r") temp="" for t in f: temp=t[:2]+"."+t[2:5] f.close() col_num = len(ws.col_values(1)) ws.update_cell(col_num + 1, 1, col_num) ws.update_cell(col_num + 1, 2, temp) ws.update_cell(col_num + 1, 3, ws.updated)
3. cron への登録
書いたコードを cputemp.py として保存し、crontab に登録します
$ crontab -e */5 * * * * /usr/bin/python /home/example/bin/cputemp.py
ピンバック:Raspberry Pi2に最新のNode.jsインストール & Googleスプレッドシートにアクセス | eye4brain
確かにデータベース作成時に小文字大文字区別の設定は必要ですね!
ピンバック:boto + gspreadでAWSのデータをGoogleSpreadsheetに入れる - TECHBIRD | TECHBIRD - プログラミングを楽しく学ぼう