You can either follow the VirtualEnvironments instructions, or you can replicate what virtualenv
's activate_this.py
script does:
import sys
import os
old_os_path = os.environ['PATH']
os.environ['PATH'] = os.path.dirname(os.path.abspath(__file__)) + os.pathsep + old_os_path
base = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
if sys.platform == 'win32':
site_packages = os.path.join(base, 'Lib', 'site-packages')
else:
site_packages = os.path.join(base, 'lib', 'python%s' % sys.version[:3], 'site-packages')
prev_sys_path = list(sys.path)
import site
site.addsitedir(site_packages)
sys.real_prefix = sys.prefix
sys.prefix = base
# Move the added items to the front of the path:
new_sys_path = []
for item in list(sys.path):
if item not in prev_sys_path:
new_sys_path.append(item)
sys.path.remove(item)
sys.path[:0] = new_sys_path
You could make this a more general function:
import sys
import os
def activate_venv(path):
if sys.platform == 'win32':
bin_dir = os.path.join(path, 'Scripts')
site_packages = os.path.join(base, 'Lib', 'site-packages')
else:
bin_dir = os.path.join(path, 'bin')
site_packages = os.path.join(BASE, 'lib', 'python%s' % sys.version[:3], 'site-packages')
os.environ['PATH'] = bin_dir + os.pathsep + os.environ['PATH']
prev_sys_path = list(sys.path)
import site
site.addsitedir(site_packages)
sys.prefix, sys.real_prefix = path, sys.prefix
# Move the added items to the front of the path:
new_sys_path = []
for item in list(sys.path):
if item not in prev_sys_path:
new_sys_path.append(item)
sys.path.remove(item)
sys.path[:0] = new_sys_path
Put that in a module on your default Python module search path, import activate_venv
and pass in the result of os.path.dirname(os.path.abspath(__file__))
:
from somemodule import activate_venv
import os.path
activate_venv(os.path.dirname(os.path.abspath(__file__)))