Skip to content

Instantly share code, notes, and snippets.

@jaberg
Forked from bsweger/ipython-virtualenv.py
Created November 1, 2012 15:49
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jaberg/3994488 to your computer and use it in GitHub Desktop.
Save jaberg/3994488 to your computer and use it in GitHub Desktop.
(Linux) make iPython virtual env aware
#------------------------------------------------------------------------------
# Make things VirtualEnv aware (Linux version).
# More info: http://www.swegler.com/becky/blog/2011/08/28/python-django-mysql-on-windows-7-part-3-ipython-virtual-environments/
# add this to the end of ipython_config
# (or course, for virtualenvs created via --no-site-packages, it would
# be much easier just to install iPython)
#
# Also consider sourcing this file from ipython_config with execfile().
#
#------------------------------------------------------------------------------
import sys
import site
from os import environ
from os.path import join
#Is a virtual envrionment currently activated?. Checking VIRTUAL_ENV (see below)
#didn't work b/c that variable wasn't being cleared upon environment deactivation.
#So started using the very hacky method of checking for parens in the command prompt.
#if 'VIRTUAL_ENV' in environ:
if '(' in environ.get('PS1') and ')' in environ.get('PS1'):
pythondir = 'python%i.%i' % (sys.version_info[0], sys.version_info[1])
virtual_env = join(environ.get('VIRTUAL_ENV'), 'lib', pythondir, 'site-packages')
ALLDIRS = [virtual_env]
#sys.path is the search path for Python modules.
prev_sys_path = list(sys.path)
#Loop through virtual environment's site-packages, adding each directory to the
#import path. Note: important to use site.addsitedir instead of adding directly
#to syspath. Latter method will not interpret .pth files in site-packages dir.
for directory in ALLDIRS:
site.addsitedir(directory)
#Adddsitedir appends to the end of sys.path. Now to need to re-order
#sys.path, putting new directories at the front to ensure virtualenv
#modules take precedence over those in main python installation
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
else:
virtual_env = 'none'
print 'VIRTUAL_ENV ->', virtual_env
del virtual_env
del site, environ, join, pythondir
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment