Using Virtualenv from Within Python

by James Johnson

Virtual environments are an ideal way to isolate your Python environments without polluting your host system. While typically created through the command-line utility virtualenv, virtual environments can also be created and activated programmatically in Python. This post details how this can be done.

Virtualenv In Python

Creating a Virtual Environment in Python

The virtualenv module can be imported directly in Python. Several methods are available within the virtualenv module, however we will only be using the create_environment() method:

def create_environment(home_dir, site_packages=False, clear=False,
                       unzip_setuptools=False,
                       prompt=None, search_dirs=None, download=False,
                       no_setuptools=False, no_pip=False, no_wheel=False,
                       symlink=True)

All of the options that you would be able to provide to the virtualenv utility should be available via keyword arguments to create_environment() command.

Activating a Virtual Environment in Python

Normally one would source the bin/activate script in the virtual environment folder to activate the environment. However, this won’t work from within a python script.

The virtualenv package provides a python script that can be exec’d in order to activate the environment. This is found at bin/activate_this.py:

venv_dir = "PATH_TO_VENV"
activate_script = os.path.join(venv_dir, "bin", "activate_this.py")
execfile(activate_script, dict(__file__=activate_script))

Example with Virtualenv and Pip

The example below will create a virtual environment and pip install a package using the virtual environment:

import virtualenv
import pip
import os

# create and activate the virtual environment
venv_dir = os.path.join(os.path.expanduser("~"), ".venv")
virtualenv.create_environment(venv_dir)
execfile(os.path.join(venv_dir, "bin", "activate_this.py"))

# pip install a package using the venv as a prefix
pip.main(["install", "--prefix", venv_dir, "xmltodict"])

import xmltodict

One example of using and activating virtual environments from within python can be seen in my autopypi.py script, where packages are automatically installed if they’re available in PyPi (see my post on auto installing PyPi packages for more details).