How to activate/deactivate a virtualenv from python code?

python, virtualenv

Solution

From part of the VirtualEnv homepage.

You must use the custom Python interpreter to install libraries. But to use libraries, you just have to be sure the path is correct. A script is available to correct the path. You can setup the environment like:

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

Problem

For activation there is a script that activates a virtualenv from an already running python interpeter using `execfile('C:/path/to/virtualev/Scripts/activate_this.py', dict(__file__='C:/path/to/virtualev/Scripts/activate_this.py'))`. However since I can still import packages that are not in the virtualenv from the current python script I am confused about how it works. For deactivation there is no python script at all. What should I do?

Original source

Related problems