Environment
- Raspberry Pi 2
- raspbian-jessie-lite
- Windows 8.1
- PuTTY 0.66 (SSH)
Issue
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.
crontab
sudo crontab -e
* * * * * python /home/dixhom/Adafruit_Python_DHT/examples/temphumid.py 1>>/tmp/cronoutput.log 2>>/tmp/cronerror.log
python script
#!/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)
cronerror.log and cronoutput.log
(empty)
What I tried
sudo crontab -e
/usr/bin/python
in cronchkconfig cron
(cron on)sudo apt-get update
sudo apt-get upgrade
sudo reboot
Any help would be appreciated. Thanks.
Advertisement
Answer
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.)