Often running a python script via crontab does not work as expected. The most common problem is with permissions, I am sure everybody is aware of.
Here are some other reasons why calling a python program from crontab may fail:
- The last line in the crontab file needs to be a newline
- Scripts called from within crontab may not contain a “.” (dot) character. This is weird and almost unknown to most users.
- crontab scripts may not have all PATH environments you have while testing your python program
So what to do about it? Here’s an easy solution:
Suppose you have added an import-path to your python installation like I did in this quick-tip. We are going to “wrap” the call to “ourprogram.py” in a bash script and name that script “ourprogram_starter”. No dots, crontab is happy. In this script we export the PATH variable so that crontab and the “ourprogram_starter” can find all our custom modules.
#!/bin/bash export PYTHONPATH="$HOME/some_Directory_Name" python /full/path/to/ourprogram.py
Make sure that this file is executable and you’re good to go. Now crontab can call this script which sets all needed environment variables and then calls the python program.