Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Crontab fails to execute Python script

Tags:

python

crontab

crontab fails to execute a Python script. The command line I am using to run the Python script is ok.

These are solutions I had tried:

  • add #!/usr/bin/env python at the top of the main.py
  • add PATH=/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin at the top of crontab
  • chmod 777 to the main.py file
  • service cron restart

my crontab is:

PATH=/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin

*/1 * * * * python /home/python_prj/main.py

and the log in /var/log/syslog is:

Nov  6 07:08:01 localhost CRON[28146]: (root) CMD (python /home/python_prj/main.py)

and nothing else.

The main.py script calls some methods from other modules under python_prj, does that matter?

Anyone can help me?

like image 448
yebw Avatar asked Nov 06 '12 11:11

yebw


People also ask

Why does my cron job not run?

Check permissionsAnother user might have created the cron job and you may not be authorized to execute it. Note that the root must own jobs added as files in a /etc/cron. */ directory. That means that if you don't have root permissions, you might not be able to access the job.

What is the use of * * * * * In cron?

* * * * * is a cron schedule expression wildcard, meaning your cron job should run every minute of every hour of every day of every month, each day of the week.


2 Answers

The main.py script calls some methods from other modules under python_prj, does that matter?

Yes, it does. All modules need to be findable at run time. You can accomplish this in several ways, but the most appropriate might be to set the PYTHONPATH variable in your crontab.

You might also want to set the MAILTO variable in crontab so you get emails with any tracebacks.

[update] here is the top of my crontab:

www:~# crontab -l

DJANGO_SETTINGS_MODULE=djangocron.settings
PATH=...
PYTHONPATH=/home/django
MAILTO="[email protected]"
...
# m h  dom mon dow   command
10-50/10 * * * *               /home/django/cleanup_actions.py
...

(running cleanup actions every 10 minutes, except at the top of the hour).

like image 94
thebjorn Avatar answered Sep 24 '22 13:09

thebjorn


Any file access in your scripts? And if so, have you used relative paths (or even: no explicit path) in your script?
When run from commandline, the actual folder is 'your path', where you start the script from. When run by cron, 'your path' may be different depending on environment variables.
So try using absolute paths to any files you access.

like image 21
user3229464 Avatar answered Sep 22 '22 13:09

user3229464