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.

  • Unless you are sure that it's located in cron's PWD, use the absolute path to the variable.txt file – steeldriver Sep 14 at 13:45
  • Thank you, it is working now. There is a need to state the absolute path to the variable.txt file for it to work – Craver2000 Sep 14 at 13:56

As steeldriver mentioned, the solution is to state the absolute path to the variable.txt file in the script for cron to work.

Your Answer

 

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.