Skip to content

Instantly share code, notes, and snippets.

@bsweger
Created August 27, 2011 23:58
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save bsweger/1176035 to your computer and use it in GitHub Desktop.
Save bsweger/1176035 to your computer and use it in GitHub Desktop.
make iPython virtual env aware (Windows)
#------------------------------------------------------------------------------
# Make things VirtualEnv aware (Windows 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)
#------------------------------------------------------------------------------
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('prompt') and ')' in environ.get('prompt'):
virtual_env = join(environ.get('VIRTUAL_ENV'), 'Lib', '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
@bsweger
Copy link
Author

bsweger commented Aug 27, 2011

@fannix
Copy link

fannix commented Mar 21, 2012

environ.get('prompt') will be None on my machine. 'PS1' is used instead.

@bsweger
Copy link
Author

bsweger commented Mar 22, 2012

Thanks for the note, fannix--I should have specified (and have changed the comments to do so) that this code is intended for a Windows environment

@jaberg
Copy link

jaberg commented Nov 1, 2012

Thanks for posting. Linux users might prefer my fork for linux

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment