Python script call from crontab with activation

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

+6
python crontab virtualenv
source share
2 answers

virtualenv activating a script is pretty simple. It basically sets the path to your virtual Python interpreter; other things that it does (setting PS1 , saving old variables, etc.) are really not needed if you are not in an interactive shell. Therefore, the easiest way is to run a Python script using the correct Python interpreter, which can be executed in one of two ways:

1. Set up your Python script to use your Python virtual translator

Assuming your virtualenv interpreter is in ~/virtualenv/bin/python , you can put this path at the beginning of your Python script:

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

And then run your script from your crontab, as usual.

2. Run the script using the appropriate Python interpreter in your cronjob

Assuming your script is in ~/bin/cronjob and your python virtualenv interpreter is in ~/virtualenv/python , you can put this in your crontab:

 * * * * * /home/user/virtualenv/python /home/user/bin/crontab 
+15
source share

My approach should always keep crontab as simple as possible and consider all the configurations inside scripts called crontab.

1) Create a shell script: e.g. /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 virtual location. When installing PATH you do not need to start the source ../ activate

2) Set the environment correctly. 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() 

In this example, the django settings are in the /production.py settings

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

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

Please note that it is important to generate logs to help you find errors or debug messages.

+1
source share

All Articles