Set PYTHONPATH for cron jobs in shared hosting

apadana picture apadana · Jul 15, 2016 · Viewed 7.2k times · Source

I had issues running my python script on shared hosting (bluehost), and with the help of other SO threads I was able to set PYTHONPATH and run the script with no issues.

Now I need to run the script via a cron job. The cron jobs in shared hosting environment are just one line which I can call the script, but can't figure out how to set PYTHONPATH before calling the script.

Example:

python /path/to/my/script.py

I am sure this issue should be common but I couldn't find any answer in other threads.

Any idea how to set PYTHONPATH for the cron jobs?

Also the codebase is developed in a local environment and the server gets a copy through git pull. So my preferred solution is not to change the source code for the server. It's ok to call another script from cron job which calls the main script and set the variables there, but changing the main script I prefer not to happen so that I don't need to maintain two versions of the code one for local and one for the server.

Answer

John Gordon picture John Gordon · Jul 15, 2016

Change your cron job to run a shell script. Inside the shell script, set PYTHONPATH and then call the python program.

Change your cron job to this:

/path/to/my_shell_script.sh

Contents of my_shell_script.sh:

export PYTHONPATH=something
python /path/to/py/python/program.py

If you don't want to have a separate shell script, you can cram it all into the cron entry, although it can get very long:

PYTHONPATH=something python /path/to/py/python/program.py