Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running crontab with python

Tags:

python

linux

cron

Python crontab script doesnt seem to work. When i run it manually,

python /home/ec2-user/code1.py

it works fine but when put into cron.txt file for the crontab, doesnt.

My crontab file is:

 @hourly python /home/ec2-user/code1.py >/dev/null 2>&1

i also tried

0    *    *    *    * python /home/ec2-user/code1.py >/dev/null 2>&1

But neither have much luck.

sudo crontab -l
@hourly python /home/ec2-user/code1.py >/dev/null 2>&1

Shows everything functional. I tried Crontab not running my python script and couple others with not much luck either.

EDIT:

With

PATH=/opt/python2.7/bin  
MAILTO=my@email
*/5 * * * * /home/ec2-user/code1.py

Email i get is:

 /bin/sh: /home/ec2-user/code1.py : No such file or directory

Yet I can open and edit the file no problem. I tried many different thing but it comes down to this: cron doesnt see the file.

Feels like I went through entire https://askubuntu.com/questions/23009/reasons-why-crontab-does-not-work and still no luck

like image 436
rodling Avatar asked Feb 03 '26 09:02

rodling


2 Answers

  1. Verify cron is running: ps aux | grep [c]ron should show a running cron process
  2. Remove the redirects from the command so that cron emails you the output
  3. Add a MAILTO=<email address> to your crontab, so that you get the email
  4. Put the full path to python (/opt/python2.7/bin/python) instead of just python in the command
  5. Add another command to crontab such as echo FOOBAR and verify that you get the email.
  6. ls -l /homeec2-user/code1.py ? Should that be /home/ec2-user/code1.py
  7. Only ever edit a user's crontab with crontab -e never from another platform, or by editing the file directly.
  8. Run crontab -l | cat -A so that we can verify all the control characters are correct.
like image 104
Douglas Leeder Avatar answered Feb 04 '26 21:02

Douglas Leeder


did you check the following points?

  • is your script executable? chmod 700 code1.py

  • the first line in your code should be, in most cases the python is installed at this place

    • #!/usr/bin/python

after that the crontab as follow should execute

0    *    *    *    * /home/ec2-user/code1.py >/dev/null 2>&1
like image 28
Thor Avatar answered Feb 04 '26 23:02

Thor