The virtualenv documentation includes Using virtualenv withoutbin/python , which hints at how to set up a virtual environment after the interpreter is already running.
To avoid hard coding the activate_this.pyscript path , 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 this:
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 get the value overridefrom the configuration file or something instead of the command line argument.
Please note that you can use only one preliminary process for one virtual environment.
Note : unlike using the interpreter in a virtual environment, you have access to the packages installed for the running interpreter. For example, if you use globally installed Python, you will have access to globally installed packages.
, Python , , , , ( ) Python.