Can't get cron to execute a python script with sudo. The script deals with GPIO input so it should be called with sudo. The program is supposed to save temperature and humidity to files but cat temp.txt and cat humid.txt gave me empty strings.
sudo crontab -e
* * * * * python /home/dixhom/Adafruit_Python_DHT/examples/temphumid.py 1>>/tmp/cronoutput.log 2>>/tmp/cronerror.log
#!/usr/bin/python
import sys
import Adafruit_DHT
import datetime
# Adafruit_DHT.DHT22 : device name
# 4 : pin number
humidity, temperature = Adafruit_DHT.read_retry(Adafruit_DHT.DHT22, 4)
if humidity is not None:
f = open("humid.txt","w")
str = '{0}, {1}'.format(datetime.datetime.now().strftime("%Y/%m/%d %H:%M:%S"), humidity)
f.write(str)
else:
print 'Failed to get reading. Try again!'
sys.exit(1)
if temperature is not None:
f = open("temp.txt","w")
str = '{0}, {1}'.format(datetime.datetime.now().strftime("%Y/%m/%d %H:%M:%S"), temperature)
f.write(str)
else:
print 'Failed to get reading. Try again!'
sys.exit(1)
(empty)
sudo crontab -e/usr/bin/python in cronchkconfig cron (cron on)sudo apt-get update sudo apt-get upgradesudo rebootAny help would be appreciated. Thanks.
Option 1: You can edit /etc/crontab. There you can specify which user shall execute the respective job in a column right after the schedule.
Option 2: Edit the crontab of root using
sudo su
crontab -e
I would go for the second option because this is what the docs suggest...
(Disclaimer: No warranties taken regarding the GPIO stuff. I just assume you are right with the "needs sudo", because I never do GPIO on the raspi. So I referred to running a script as root only.)
The issue was the relative paths. The data was save to a place different from what I was looking at.
Changing
f = open("humid.txt","w")
to
f = open("/home/dixhom/Adafruit_Python_DHT/examples/humid.txt","w")
solve the issue.