Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link
Owner Author

bsweger commented Aug 27, 2011

@fannix

This comment has been minimized.

Copy link

fannix commented Mar 21, 2012

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

@bsweger

This comment has been minimized.

Copy link
Owner 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

This comment has been minimized.

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
You can’t perform that action at this time.