我正在尝试使用python脚本对我的MySQL服务器进行一些温度采样。启动树莓派时,当我运行脚本时,脚本可以正常记录温度到我的MySQL服务器。脚本:
#!/usr/bin/python3
# Import packages
import os
import time
import datetime
import MySQLdb
from w1thermsensor import W1ThermSensor
# Global variables
global c
global db
# Variables
sensor = W1ThermSensor()
# Defining functions
def insert_to_db():
# Values
temperature = sensor.get_temperature()
thetime = (datetime.datetime.fromtimestamp(time.time()).strftime("%H:%M:%S"))
date = (datetime.datetime.fromtimestamp(time.time()).strftime("%Y-%m-%d"))
# Print to console
#print ("Temperature is %s celsius degree at the date %s and time %s " % (temperature, thetime, date))
# Perfom SQL and insert
sql = "INSERT INTO tab_room (Temperature, Date, Time) VALUES (%s, %s, %s)"
try:
c.execute(sql,( str(temperature) , str(date), str(thetime)))
db.commit()
except:
db.rollback()
print("did not insert")
#db.close()
def main():
while 1:
insert_to_db()
time.sleep(600)
if __name__ == '__main__':
try:
db = MySQLdb.connect("localhost","pi","secretpassword","db_temp")
c= db.cursor()
except:
print ("Ingen forbindelse til serveren...")
try:
main()
except KeyboardInterrupt:
print ("bye bye...")
pass
我正在使用etc / profile,但我也尝试过rc.local和crontab ... 但是在etc / profile中,我添加了以下行:
sudo python /home/pi/temp_sampler.py &
当我sudo重新启动时,我的MySQL服务器上没有温度,并且在提示符下收到以下错误消息,当我手动启动pi时,如果我可以完美地运行它,这是没有意义的。
Traceback (most recent call last):
File "/home/pi/temp_sampler.py", line 8, in <module>
from w1thermsensor import W1ThermSensor
ImportError: No module named w1thermsensor
[1]+ Exit 1 sudo python /home/pi/temp_sampler.py
我希望那里有个骑士可以帮助我!