##// END OF EJS Templates
Add simple support for running inside a virtualenv.
Thomas Kluyver -
Show More
@@ -411,6 +411,9 b' class InteractiveShell(SingletonConfigurable, Magic):'
411 411 self.init_instance_attrs()
412 412 self.init_environment()
413 413
414 # Check if we're in a virtualenv, and set up sys.path.
415 self.init_virtualenv()
416
414 417 # Create namespaces (user_ns, user_global_ns, etc.)
415 418 self.init_create_namespaces(user_module, user_ns)
416 419 # This has to be done after init_create_namespaces because it uses
@@ -662,6 +665,37 b' class InteractiveShell(SingletonConfigurable, Magic):'
662 665 except ImportError:
663 666 warn("doctest module does not exist.")
664 667
668 def init_virtualenv(self):
669 """Add a virtualenv to sys.path so the user can import modules from it.
670 This isn't perfect: it doesn't use the Python interpreter with which the
671 virtualenv was built, and it ignores the --no-site-packages option. A
672 warning will appear suggesting the user installs IPython in the
673 virtualenv, but for many cases, it probably works well enough.
674
675 Adapted from code snippets online.
676
677 http://blog.ufsoft.org/2009/1/29/ipython-and-virtualenv
678 """
679 if 'VIRTUAL_ENV' not in os.environ:
680 # Not in a virtualenv
681 return
682
683 if sys.executable.startswith(os.environ['VIRTUAL_ENV']):
684 # Running properly in the virtualenv, don't need to do anything
685 return
686
687 warn("Attempting to work in a virtualenv. If you encounter problems, please "
688 "install IPython inside the virtualenv.\n")
689 if sys.platform == "win32":
690 virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'Lib', 'site-packages')
691 else:
692 virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'lib',
693 'python%d.%d' % sys.version_info[:2], 'site-packages')
694
695 import site
696 sys.path.insert(0, virtual_env)
697 site.addsitedir(virtual_env)
698
665 699 #-------------------------------------------------------------------------
666 700 # Things related to injections into the sys module
667 701 #-------------------------------------------------------------------------
General Comments 0
You need to be logged in to leave comments. Login now