diff --git a/IPython/core/interactiveshell.py b/IPython/core/interactiveshell.py index 804c4a4..5462c00 100644 --- a/IPython/core/interactiveshell.py +++ b/IPython/core/interactiveshell.py @@ -410,6 +410,9 @@ class InteractiveShell(SingletonConfigurable, Magic): 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 @@ class InteractiveShell(SingletonConfigurable, Magic): 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