Activating a workingenv from Python
It can, under some circumstances, be useful to be able to activate a workingenv from Python. Here's a quick function to achieve that:
import sys import os def activate_workingenv(root): """Make modules in a self-contained workingenv available.""" # Add ./bin directory to path. bin_dir = os.path.join(root, './bin') try: os.environ['PATH'] = os.path.pathsep.join([bin_dir, os.environ['PATH']]) except KeyError: os.environ['PATH'] = bin_dir # Add ./lib to linker path lib_dir = os.path.join(root, './lib') try: os.environ['LD_LIBRARY_PATH'] = \ os.path.pathsep.join([lib_dir, os.environ['LD_LIBRARY_PATH']]) except KeyError: os.environ['LD_LIBRARY_PATH'] = lib_dir # Find the workingenv Python package root python_version = '.'.join(map(str, sys.version_info[:2])) package_root = os.path.join(root, './lib/python' + python_version) # Find and insert setuptools into sys.path sys.path.insert(0, package_root) real_setuptools = open(os.path.join(package_root, 'setuptools.pth')).read().strip() sys.path.insert(0, os.path.join(package_root, real_setuptools)) # Load all distributions into the working set. from pkg_resources import working_set, Environment env = Environment(root) env.scan() distributions, errors = working_set.find_plugins(env) for dist in distributions: working_set.add(dist) return distributions, errors
It's UNIX-centric due to the use of LD_LIBRARY_PATH, but if you're not using shared libraries it's not really necessary anyway.
Use it like so:
from activate_workingenv import activate_workingenv activate_workingenv('./wenv') import some_module_from_the_workingenv
