Permalink
Browse files

Add simple support for running inside a virtualenv.

  • Loading branch information...
1 parent c1c517a commit 826ee2d905b2c856c80bea137189495182222dac @takluyver committed Feb 7, 2012
Showing with 34 additions and 0 deletions.
  1. +34 −0 IPython/core/interactiveshell.py
View
34 IPython/core/interactiveshell.py
@@ -410,6 +410,9 @@ def __init__(self, config=None, ipython_dir=None, profile_dir=None,
self.init_profile_dir(profile_dir)
self.init_instance_attrs()
self.init_environment()
+
+ # Check if we're in a virtualenv, and set up sys.path.
+ self.init_virtualenv()
# Create namespaces (user_ns, user_global_ns, etc.)
self.init_create_namespaces(user_module, user_ns)
@@ -661,6 +664,37 @@ def init_reload_doctest(self):
doctest_reload()
except ImportError:
warn("doctest module does not exist.")
+
+ def init_virtualenv(self):
+ """Add a virtualenv to sys.path so the user can import modules from it.
+ This isn't perfect: it doesn't use the Python interpreter with which the
+ virtualenv was built, and it ignores the --no-site-packages option. A
+ warning will appear suggesting the user installs IPython in the
+ virtualenv, but for many cases, it probably works well enough.
+
+ Adapted from code snippets online.
+
+ http://blog.ufsoft.org/2009/1/29/ipython-and-virtualenv
+ """
+ if 'VIRTUAL_ENV' not in os.environ:
+ # Not in a virtualenv
+ return
+
+ if sys.executable.startswith(os.environ['VIRTUAL_ENV']):
+ # Running properly in the virtualenv, don't need to do anything
+ return
+
+ warn("Attempting to work in a virtualenv. If you encounter problems, please "
+ "install IPython inside the virtualenv.\n")
+ if sys.platform == "win32":
+ virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'Lib', 'site-packages')
+ else:
+ virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'lib',
+ 'python%d.%d' % sys.version_info[:2], 'site-packages')
+
+ import site
+ sys.path.insert(0, virtual_env)
+ site.addsitedir(virtual_env)
#-------------------------------------------------------------------------
# Things related to injections into the sys module

0 comments on commit 826ee2d

Please sign in to comment.