Search code examples
python-3.xlinuxcrondebiancron-task

crontab failed to run python script at reboot


I have a raspberry pi zero with a python script located in

/home/pi/Documents/camProject

that writes the date and time to a log.txt file.

import datetime
import json
now = datetime.datetime.now()
now = str(now)

with open('log.txt','w') as f:
    json.dump(now, f)
    
print('script complete')
print(now)

I can call and execute the script from the console when I am standing in camProject folder.

pi@raspberrypi:~/Documents/camProject $ sudo python3 "/home/pi/Documents/camProject/test.py"
script complete
2020-10-17 08:39:46.238224

I want this test.py script to run on every reboot, so from the command console I did

sudo crontab -e

In the bottom of the crontab script I wrote

@reboot sudo python3 "/home/pi/Documents/camProject/test.py"

Upon reboot the raspberry pi device nothing happened and the date is not written into the log.txt file. I have tried executing

sudo python3 "/home/pi/Documents/camProject/test.py"

from my home directory

/home/pi

and I see the print out from my test.py in the console but the log.txt is not updated. However, if I execute the same script from the folder where test.py is located, everything works fine. I then checked the permission and in my camProject folder

pi@raspberrypi:~/Documents/camProject $ ls -l
totalt 20
-rwxrwxrwx 1 pi pi   66 okt 17 00:00 camVision.py
-rwxrwxrwx 1 pi pi   28 okt 17 08:50 log.txt
-rwxrwxrwx 1 pi pi  167 okt 17 08:33 test.py
-rwxrwxrwx 1 pi pi  115 okt 17 07:45 test.pyc
drwxrwxrwx 2 pi pi 4096 okt 16 14:50 Video

I guess the problem is related to log.txt is not writeable when test.py is executed from command console when the execution happened to be outside the camProject folder and therefore not by crontab either. I don't know how to fix this problem?


Solution

  • Your program creates the file in the current working directory. cron jobs run in the invoking user's home directory; thus your cron job writes the file in the home directory of root (probaby /root on Debian-based platforms).

    Once you create a file as root, it is only writable by root (unless you specifically set permissions to make it world-writable, or assign write access to a specific user group)

    Probably change your script to write to /home/pi/log.txt (if that's where you want the file) and make sure the file already exists, or maybe switch to the pi user before creating it if you are running as root. (Once the file exists with the correct owner and permissions, root can append to it without changing the owner or permissions.)

    Tangentially, there is no need to use sudo in a cron Job which is already running with full root privileges.