virtualenv 

Send to Kindle
home » snippets » python » virtualenv


Pages
create_virtualenv_bootstrap.py        
default_virtualenv_bootstrap.py        



My Tips

Basic Usage

python virtualenv.py --distribute ENV

or

# Use python2.6
python --python=python2.6 virtualenv.py --distribute ENV

or

# Run from python2.6 – even better.
python -m virtualenv --distribute ENV

or

python -m virtualenv --distribute --no-site-packages --unzip-setuptools <name_of_directory>

Creating a bootstrap script

import virtualenv
# extra_text is any python code you want included.
virtualenv.create_bootstrap_script(extra_text or "")

This returns a string that (written to disk of course) can be used as a bootstrap script with your own customizations. The script will be the standard virtualenv.py script, with your extra text added (your extra text should be Python code).

The --no-site-packages Option

If you build with virtualenv --no-site-packages ENV it will not inherit any packages from /usr/lib/python2.5/site-packages (or wherever your global site-packages directory is). This can be used if you don’t have control over site-packages and don’t want to depend on the packages there, or you just want more isolation from the global system.

Using from mod_python, uwsgi, etc.

Sometimes you can’t or don’t want to use the Python interpreter created by the virtualenv.

Luckily, it’s easy. 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))

This will change sys.path and even change sys.prefix, but also allow you to use an existing interpreter. Items in your environment will show up first on sys.path, before global items. However, this cannot undo the activation of other environments, or modules that have been imported.

Create your own bootstrap scripts

Example

import virtualenv, textwrap
output = virtualenv.create_bootstrap_script(textwrap.dedent("""
    import os, subprocess
    def after_install(options, home_dir):
        etc = join(home_dir, 'etc')
        if not os.path.exists(etc):
            os.makedirs(etc)
        subprocess.call([join(home_dir, 'bin', 'easy_install'),
                         'BlogApplication'])
        subprocess.call([join(home_dir, 'bin', 'paster'),
                         'make-config', 'BlogApplication',
                         join(etc, 'blog.ini')])
        subprocess.call([join(home_dir, 'bin', 'paster'),
                         'setup-app', join(etc, 'blog.ini')])
"""))
f = open('blog-bootstrap.py', 'w').write(output)