tags:

views:

107

answers:

1

I am trying to have a Django script run every 5 minutes via cron on my dev laptop (Mac OS X). Here is the code in the script:

import sys
import os

def setup_environment():
    pathname = os.path.dirname(sys.argv[0])
    sys.path.append(os.path.abspath(pathname))
    sys.path.append(os.path.normpath(os.path.join(os.path.abspath(pathname), '../')))
    os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'

setup_environment()


from common.models import TweetCache
import datetime

def main():
    print "(%s) Caching tweets..." % str(datetime.datetime.now()) 
    previous_tweets = TweetCache.objects.filter(username='atmospherian')
    for prev in previous_tweets:
        prev.delete()

    import twitter

    api = twitter.Api()
    tweets = api.GetUserTimeline('atmospherian')
    for t in tweets:
        tc = TweetCache(username='atmospherian', date=t.created_at, text=t.text)
        tc.save()

if __name__ == '__main__':
    main()

crontab:

*/5 * * * * python /absolute/path/to/tweet_cache.py

error from system mail:

X-Cron-Env: <SHELL=/bin/sh>
X-Cron-Env: <PATH=/usr/bin:/bin>
X-Cron-Env: <LOGNAME=jason>
X-Cron-Env: <USER=jason>
X-Cron-Env: <HOME=/Users/jason>
Date: Tue, 16 Feb 2010 17:45:00 -0500 (EST)

Traceback (most recent call last):
  File "/Users/jason/Development/bandistry/tweet_cache.py", line 22, in <module>
    from common.models import TweetCache
  File "/Users/jason/Development/bandistry/common/models.py", line 1, in <module>
    from django.db import models
ImportError: No module named django.db

can anyone tell me what im doing wrong?

+1  A: 

sys.argv[0] isn't always the most reliable way to get the current file's path. I recommend this modification:

pathname = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, pathname)
sys.path.insert(0, os.path.abspath(os.path.join(pathname, '..')))

Note the use of sys.path.insert instead of sys.path.append, and the use of file. Also, using abspath on file -before- dirname reduces the chance you reduce the entire filename down to the empty string or simply '.' which may not even be accurate.

Also, is the django package installed in one of those two paths you add? If not, you sill need to add that path

Finally, a minor quip, probably unrelated to your django import issue, but you really should be doing:

os.environ['DJANGO_SETTINGS_MODULE'] = 'bandistry.settings'

It may work without, but it's better if you put your entire django application in a package. This reduces the chance of you obscuring other package names.

Crast
so would the path to my django install be: /Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django?
Jason Miesionczek
that did the trick, i think i was missing having django on the path as it seems cron creates its own environment where you have to specify the PATH independently of the system.
Jason Miesionczek