Beaucoup utilisent la bibliothèque MySQLdb comme client SQL.
Récemment j'ai mis une requète SQL en service incluant un "SELECT" au lieur d'un "INSERT".
Le script se lance et fonctionne en IDLE (F5), en console aussi.
Si je le programme avec crontab, ou avec un "executer" qui suit un "sudo chmod +x test.py", eh ben là ça ne marche plus...
tests infructueux :
- changer le crontab en "sudo crontab -e"
- changer la ligne en "*/1 * * * * sudo /usr/bin/python /home/pi/Documents/mon_test.py..."
- changer de bibliothèque (MySQLdb --> pymysql, dispo avec pip d'ailleur)
- lancer le script avec un script shell
- lancer le script en temps que service
Ci dessous un code test pour un serveur SQL sur le réseau local :
Code : Tout sélectionner
#! /usr/bin/python
# -*- coding: utf-8 -*-
# importations
import os
import time
import sys
import pymysql as sql # or MySQLdb as...
from os import path as os_path
# constants
PATH_THERM = "/home/pi/Documents/" #path to this script
DB_SERVER ='192.168.0.59' # MySQL : IP server
DB_USER='user' # MySQL : user
DB_PWD='password' # MySQL : password
DB_BASE='capteurs' # MySQL : database name
def log(texte):
datation = time.strftime('%d-%m-%Y %H:%M:%S')
logue = open('log_test.txt','a')
txt = "\n" + datation + "\t" + texte
txt = txt.encode('utf-8')
logue.write(txt)
logue.close()
def query_temp():
datebuff = time.strftime('%d-%m-%Y')
db = sql.connect(DB_SERVER, DB_USER, DB_PWD, DB_BASE)
cursor = db.cursor()
cursor.execute("""SELECT sonde2,date FROM `PiTemp` ORDER BY date DESC LIMIT 0, 1""")
rows = cursor.fetchall()
print datebuff, u" : Dernière température de l'eau :", rows[0][0], u"°C"
log(u"lecture température SQL - ok")
a = rows[0][0]
b = rows[0][1]
return (a, b)
# principal code
#-------------------------------------
PATH=os_path.abspath(os_path.split(__file__)[0])
os.chdir(PATH)
log('start')
log(PATH)
txt = str(query_temp()[0])
log(txt)
Code : Tout sélectionner
*/1 * * * * python /home/pi/Documents/180623_test.py