Activating a virtualenv “without hands”

Virtualenv is a awesome tool to Python development.  To easier the development process there is the virtualenvwrapper:  a wrapper that allow you access the your virtualenv shell commands.

However, even with this all easies a problem rises when we deploy our code:

How to activate the virtualenv automatically?

The answer is: using the activate_this.py script.
We can found it on path:

~/.virtualenvs/<your virtualenv>/bin/activate_this.py

The script’s aim is activate the virtualenv python from “outside”. So, your environment will have access to necessary libs to run your application.

Look ma: no hands…!

To use the script put the follow code lines on file that starts your app.

If your app runs on cli (command line app) like a *nix daemon, you put the code line on your file that start your app. In case your app is a web application, then, you put the code on “*wsgi.py” – the file that is used by your webserver.

activate_this = '/path/to/env/bin/activate_this.py'
execfile(activate_this, dict(__file__=activate_this))

Note that lines above should be put on the first lines of the code.

After this, restart your service or your webserver.

Done! Your virtualenv will be start automatically ;-)

Read more:

Virtualenvwrapper – Read the docs: https://virtualenvwrapper.readthedocs.io/en/latest/

Leave a Reply

Your email address will not be published.