I have a python script I wish to call each day with a cron job. Because the .py script loads several files from it's directory, rather than change all the file paths within the .py script to be full paths, I instead called a .sh script with the cronjob that changes the dir. Here's the .sh script.

cd /home/ubuntu/ga_data/gaV4
python gaAPIWorkingVersion.py
echo "ran cron at" | tee -a  "$tvaUpdater.log"
echo $(date) | tee -a  "$tvaUpdater.log"

I know that the cronjob ran because I see the right date in the log file. However, the log file contains a message:

Traceback (most recent call last): File "gaAPIWorkingVersion.py", line 13, in from apiclient.discovery import build ImportError: No module named apiclient.discovery

The package is installed. When I call the .sh script directly, outwith cron, everything works as expected.

/home/ubuntu/ga_data/myscript.sh # works

It's only when the script is called from the cron that this error happens.

What could be causing this and is there anything I can add to my crontab or .sh script to successfully run the script?

Note, if it's useful or important, I'm using Anaconda python.

  • Yes it is important - cron runs in a very limited environment, which almost certainly won't include any PATH and/or PYTHONPATH that you have set to allow you to run anaconda python from your interactive shell Aug 5 '18 at 15:31
  • @steeldriver thanks for the information here. Are you abel to advise how I can correct for this? Is there a line I need to add to my .sh script?
    – Doug Fir
    Aug 5 '18 at 15:35
  • Find out what relevant variables Anaconda has set (likely added to your ~/.bashrc file by the Anaconda installation process) and add the same to the top of your bash script Aug 5 '18 at 15:37

Had to prepend the python path in the crontab per this SO answer.

e.g. 01 00 * * * /usr/bin/python /home/ubuntu/data_scripts/test.py

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.