Python script not running from cron

Several times, your python script end-up not running via crontab. You check your ENV and permissions of your HOME directory and the script. Everything looks good, but still your script won’t run via crontab but it runs fine when you run it from command line. In this case, how shall we find what causing the script not to run from crontab and how do we fix it  ?

Below is a small shell script which can help  you in checking whats going wrong when crontab fires a Python script. Put this script in your HOME dirctory and change RED colored lines accordingly.

#!/bin/bash
exec >/tmp/debug.stdout
exec 2>/tmp/debug.stderr
set -x
PATH=$PATH
cd /path/to/your/script/folder
/your/python/interpreter/path /path/to/your/script/python_script.py

Then, run this script from your crontab. After script completes its execution, check “/tmp/debug.stderr” file for any errors which is reported by your Python script because of which, it got failed. Fix the issue/error reported in the file first.

Once you fix it, now its time to run the script from crontab. Python script relays on PYTHONPATH variable. Most of the time, the script fails to run because PYTHONPATH variable isn’t accessible to crontab. To fix it, just add PYTHONPATH variable inside crontab and your script should be able to kick off. Below is how you can setup PYTHONPATH inside cron.

30 20 * * 4 PYTHONPATH=/home/MYHOMEDIR/pycrypto-2.4.1/lib/python2.7/site-packages:/home/MYHOMEDIR/paramiko-1.7.7/lib/python2.7/site-packages; export PYTHONPATH; /path/to/your/python/script/my_python_script.py

Leave a comment