The Python script works perfectly fine when ran from the command line while signed in as the "pi" user, with this command:
python3 /home/pi/www/main.py &
But from the crontab, it just doesn't work at all. Logging errors reveals that OpenCV4 cannot find a shared object, because obviously, it's not running in the correct environment it was installed for. I've tried several things to schedule it to run at boot time and as much as possible as the "pi" user, namely:
1) Under the "pi" user: crontab -e
2) Under the root user: sudo crontab -e
3) By directly editing the crontab (sudo nano /etc/crontab) and specifying the user "pi": @reboot pi python3 /home/pi/www/main.py &
4) By sourcing the "pi" user's bashrc: @reboot source /home/pi/.bashrc && python3 /home/pi/www/main.py &
5) By calling a .sh file containing the python3 command
6) By sudo'ing the pi user to run the python command but as you can see, OpenCV is not happy, because shared objects are missing: (Under: sudo crontab -e) @reboot sudo -u pi /usr/bin/python3 /home/pi/www/main.py >>/home/pi/www/logs/cron_log.txt 2>&1
The cron_log.txt file now contains:
Traceback (most recent call last):
File "/home/pi/www/main.py", line 4, in <module>
import cv2
File "/usr/lib/python3/dist-packages/cv2/__init__.py", line 89, in <module>
bootstrap()
File "/usr/lib/python3/dist-packages/cv2/__init__.py", line 79, in bootstrap
import cv2
ImportError: libopencv_quality.so.4.1: cannot open shared object file: No such file or directory
Kind of out of ideas...
EDIT: OK, so by adding this single command to the chain (as per seen at the bottom of /home/pi/.bashrc) it resolved the whole thing: export LD_LIBRARY_PATH=/opt/opencv-4.1.0/lib:$LD_LIBRARY_PATH
So basically, source /home/pi/.bashrc
does not seem to work in providing the necessary environment variable for OpenCV 4 to run from cron. But why? Is there a different command that would work instead of source /home/pi/.bashrc
?