6

how do i call a python script from crontab that requires using activate (source env/bin/active)?

unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677
Timmy
  • 12,468
  • 20
  • 77
  • 107

2 Answers2

18

Virtualenv's activate script is pretty simple. It mostly sets the path to your virtualenv's Python interpreter; the other stuff that it does (setting PS1, saving old variables, etc.) aren't really necessary if you're not in an interactive shell. So the easiest way is just to launch your Python script with the correct Python interpreter, which can be done in one of two ways:

1. Set up your Python script to use your virtualenv's Python interpreter

Assuming your virtualenv's interpreter is at ~/virtualenv/bin/python, you can put that path at the top of your Python script:

#!/home/user/virtualenv/bin/python

And then launch your script from your crontab, as normal.

2. Launch the script with the proper Python interpreter in your cronjob

Assuming your script is at ~/bin/cronjob and your virtualenv's Python interpreter is at ~/virtualenv/python, you could put this in your crontab:

* * * * * /home/user/virtualenv/python /home/user/bin/cronjob
dangel
  • 7,238
  • 7
  • 48
  • 74
mipadi
  • 398,885
  • 90
  • 523
  • 479
  • what about the paths to easy_install libraries? – Timmy May 27 '10 at 19:58
  • 2
    If they're installed in the virtual environment as well, or the "global" site-packages directory, they should be found; otherwise, you will have to put them in your `$PYTHONPATH`, which gets a bit uglier but can be accomplished by launching the Python bin with `/usr/bin/env` or somesuch. – mipadi May 27 '10 at 20:09
  • 1
    the last code block should probably end with "/home/bin/cronjob" – Van Nguyen Aug 06 '10 at 22:06
1

My approach is always to keep crontab as simple as possible and treat all configurations inside scripts called by crontab.

1) Create a shell script: for example /var/webapp/cron.sh

#!/bin/sh
PATH="/var/webapp/.env/bin:$PATH"
export PATH
cd /var/webapp/
python test.py

where /var/webapp/.env/bin is the virtualenv location. Setting PATH, you don't need to run source ../activate

2) Set properly your environment. For example, for a Django application:

#!/usr/bin/env python

import os
from datetime import datetime

os.environ['DJANGO_SETTINGS_MODULE'] = 'settings.production'
os.environ['DJANGO_CONF'] = 'settings.production'

from util.models import Schedule

dset = Schedule.objects.all()
for rec in dset:
    print rec

print 'cron executed %s' % datetime.today()

On this example, django settings are located on settings/production.py

3) Finally, edit /etc/crontab. For example, to be execute each half hour, every day:

1,31 * * * *  root   /var/webapp/cron.sh >> /var/webapp/cron.log

Notice that it's important to generate logs to help you find errors or debug messages.

Josir
  • 1,282
  • 22
  • 35