I am trying to run a python script on my Raspberry Pi (Stretch OS) as a cron job but the script fails to run fully.
On crontab -e, it reads like this:
*/1 * * * * python /home/pi/project/myfile.py >> /home/pi/project/logerrorfile.txt
The log file shows me that the script fails to run when it tries to import a variable from a text file (ie. variable.txt) as shown in a segment of myfile.py code below:
print("reading txt file for variable now") #log file prints this
text_file = open('variable.txt')
try:
variable = text_file.readlines()
except:
print("Error: unable to read variable from txt file") #This is not printed in the log file
print("variable read successfully from txt file") #This is also not printed in the log file
However, when I run this script as a bash command on terminal, it goes smoothly and the entire script is executed. Why does this work properly as a bash command on terminal but fails to work as a cron job? I have also tried to state the absolute path of my python executer in my cron job command to: #0,30 * * * * /usr/bin/python /home/pi/project/myfile.py >> /home/pi/project/logerrorfile.txt
but the script still does not work as a cron job. It therefore appears as if using cron to run a script that reads a variable from a text file becomes problematic. I appreciate any advice on this.
PWD
, use the absolute path to thevariable.txt
filevariable.txt
file for it to work