Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why am I not able to use Python 3 in a Crontab?

As an example, I've placed a simple program on on the path home/pi to test.

My crontab script is

* * * * * /pi/testcron.py

and I haven`t got any results. I've tried other scripts -recommended here- but without success.

I appreciate any support I can receive.

like image 381
Fermar Avatar asked Feb 05 '26 09:02

Fermar


2 Answers

Cron runs scripts using sh shell. It doesn't know about your python configuration. Put full path to python before your script.

* * * * * /path/to/python3/python/Python-3.6.1/python /home/pi/testcron.py

If you don't know python path, use which python to get it.

like image 74
mx0 Avatar answered Feb 07 '26 23:02

mx0


Based on the comments, it looks like you're expecting to see output from the print function. The problem is, since cron is running the script in another shell/terminal, you won't see print output even if it is running correctly. For example, if you open up two terminal windows, and run your script manually in one window, you won't see your print output in the other. In order to leave a lasting effect, use a redirect for the print output. This will open a new file that you'll be able to inspect after the cronjob has run.

As others have said, you'll likely need to include the full path to your python installation. The common sys install path is /usr/bin/python3. So, you should do something like:

* * * * * /usr/bin/python3 /home/pi/testcron.py > /home/my_output.txt

The last part > /home/my_output.txt will redirect the output of the print function to the file /home/my_output.txt. After the crontab runs, you should be able to open the file and the output of the print command.

Please do not copy/paste this exactly as-is and expect it to work without doing some sanity checking! Make sure that the directories are correct! For example, /home/pi/testcron.py should be the full path to your python file. We are just guessing at your file structure, we don't know what it looks like.

like image 29
Matt Messersmith Avatar answered Feb 07 '26 21:02

Matt Messersmith