The virtualenv documentation includes a Using virtualenv without bin/python section that hints at how to configure a virtual environment once the interpreter is already running.
To avoid hardcoding the path to the activate_this.py script, I use the following snippet:
def resolve_virtual_environment(override=None):
"""Fetch the virtual environment path in the
process' environment or use an override."""
path = os.getenv('VIRTUAL_ENV')
if override:
path = os.path.join(os.getcwd(), override)
return path
def activate_virtual_environment(environment_root):
"""Configures the virtual environment starting at ``environment_root``."""
activate_script = os.path.join(
environment_root, 'Scripts', 'activate_this.py')
execfile(activate_script, {'__file__': activate_script})
And you can use it like so:
if __name__ == '__main__':
# use first argument is provided.
override = None
if len(sys.argv) > 1:
override = sys.argv[1]
environment_root = resolve_virtual_environment(override)
You can fetch the override value from a configuration file or something instead of from the command-line argument.
Note that you can only still use a single virtual environment pre-process.
Note: in contrast with using the interpreter bundled in the virtual environment, you have access to the packages installed for the interpreter you started. For example, when using a globally-installed Python, you will have access to the globally-installed packages.
Also make sure that you use a Python interpreter with a version that matches whatever version you used to create the virtual environment to make sure that the standard library (copied into the virtual environment) version matches the Python interpreter version.