Search code examples
python-3.xcronraspberry-piinfluxdb-python

Cron a Python3 script


I cannot cron job a python3 script, it does not work, what i've tried :

*/1 * * * * python3 /home/pi/pythons/bmp280_influxdb.py

*/1 * * * * /usr/bin/python3.7 /home/pi/pythons/bmp280_influxdb.py

i've tried to create a .sh file which contains : python3 /home/pi/pythons/bmp280_influxdb.py and cron the .sh file but it did not work either.

I also tried to make the bmp280_influxdb.py executable with chmod +x bmp280_influxdb.py and use */1 * * * * /home/pi/pythons/bmp280_influxdb.py directly

knowing that :

*/2 * * * * sh /home/pi/scripts/cputemp.sh works

I can't figure out what to do

I've triple checked paths and the scipt works when I call it via python3

The script sends data of a sensor to influxdb :

#!/usr/bin/python3
#import influxdb libs
import time
import sys
import datetime
import json
from influxdb import InfluxDBClient
#import bmp280 libs
import board
import busio
import digitalio
import adafruit_bmp280

# Create the InfluxDB client object
client = InfluxDBClient(host='localhost', port=8086) #address
client.switch_database("weather")

#sensor details
spi = busio.SPI(board.SCK, MOSI=board.MOSI, MISO=board.MISO)
cs = digitalio.DigitalInOut(board.D5)
sensor = adafruit_bmp280.Adafruit_BMP280_SPI(spi, cs)

#building data
iso = time.ctime()

temp = float(sensor.temperature)
pres = float(sensor.pressure)

temp = round(temp, 2)
pres = round(pres, 3)

json_body = [
{
    "measurement": "bmp280",
    "fields": {
        "exttemp": temp,
        "extpres": pres
    }
}
]

#sending data
client.write_points(json_body)

Solution

  • I finally found the solution, it has to do with the comportment of crontab, when it is executing a script, it is doing so with sudo "user". Therefore pythons libraries must also be installed with "sudo" user : sudo pip3 install <libs> and not simply pip3 install <libs> as I used to.