0

I'm trying to use a crontab to execute a python script periodically. I followed the solution given here to execute the command using virtualenv. Following is my crontab

SHELL=/bin/bash
HOME=/
MAILTO="myid@example.com"
* * * * * cd /home/jaskaran/edmhunters && /home/jaskaran/edmhunters/env/bin/python /home/jaskaran/edmhunters/scripts/db/songlist.py

I keep getting this ImportError

Traceback (most recent call last):
 File "/home/jaskaran/edmhunters/scripts/db/songlist.py", line 4, in <module>
   from hunt.models import DJ, Song
ImportError: No module named hunt.models

The script works fine when run from the shell. What am I missing?

Community
  • 1
  • 1
Yin Yang
  • 1,776
  • 3
  • 26
  • 48
  • Try putting those two lines into a shell script then run that, see if the error pop up while running from shell, then try again inside the cronjob. – metatoaster Aug 25 '14 at 09:18
  • 1
    @metatoaster I get the same error if run from a shell script. It seems `source env/bin/activate` and `/home/jaskaran/edmhunters/env/bin/python` don't work the same way. – Yin Yang Aug 25 '14 at 09:22
  • Try going into some other directory and run the script via absolute path, with that virtualenv active. I am suspecting that the `hunt.models` does not have an `.egg-link` of some sort. – metatoaster Aug 25 '14 at 09:32

1 Answers1

0

Django import errors are often misleading due to how Django loads its INSTALLED_APPLICATIONS and all implicit code what comes when Django tries to access its settings.

To work around, create a Django management command out of your script.

Then try this syntax if you need to run virtualenv'ed Django script or management command from shell script or cron:

 export DJANGO_SETTINGS_MODULE=mymodule.settings ; /srv/django/myproject/venv/bin/python /srv/django/myproject/manage.py MyManagementCommand
Mikko Ohtamaa
  • 82,057
  • 50
  • 264
  • 435