Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set virtualenv for a crontab?

I want to set up a crontab to run a Python script.

Say the script is something like:

#!/usr/bin/python
print "hello world"

Is there a way I could specify a virtualenv for that Python script to run in? In shell I'd just do:

~$ workon myenv

Is there something equivalent I could do in crontab to activate a virtualenv?

like image 324
Continuation Avatar asked Nov 11 '10 01:11

Continuation


People also ask

How do I activate Virtualenv?

To install virtualenv, just use pip install virtualenv . To create a virtual environment directory with it, type virtualenv /path/to/directory . Activating and deactivating the virtual environment works the same way as it does for virtual environments in Python 3 (see above).

Can we run Python script in crontab?

You should use Cron any time you want to automate something, like an OS job or a Python script. Needless to say, but an automated Python script can do basically anything. On Linux and macOS, the Crontab consists of six fields.


2 Answers

Is there something equivalent I could do in crontab to activate a virtualenv?

This works well for me...

## call virtualenv python from crontab
0    9    *    *    *    /path/to/virtenv/bin/python /path/to/your_cron_script.py

I prefer using python directly from the virtualenv instead of hard-coding the virtualenv $PATH into the script's shebang... or sourcing the venv activate

like image 169
Mike Pennington Avatar answered Oct 19 '22 20:10

Mike Pennington


If you're using "workon" you're actually using "virtualenv wrapper" which is another layer of abstraction that sits on top of virtualenv. virtualenv alone can be activated by cd'ing to your virtualenv root directory and running:

source bin/activate

workon is a command provided by virtualenv wrapper, not virtualenv, and it does some additional stuff that is not necessarily required for plain virtualenv. All you really need to do is source the bin/activate file in your virtualenv root directory to "activate" a virtualenv.

You can setup your crontab to invoke a bash script which does this:

#! /bin/bash    
cd my/virtual/env/root/dir
source bin/activate

# virtualenv is now active, which means your PATH has been modified.
# Don't try to run python from /usr/bin/python, just run "python" and
# let the PATH figure out which version to run (based on what your
# virtualenv has configured).

python myScript.py
like image 84
Andy White Avatar answered Oct 19 '22 19:10

Andy White