activate_this.py 1.2 KB

1234567891011121314151617181920212223242526272829303132
  1. # -*- coding: utf-8 -*-
  2. """Activate virtualenv for current interpreter:
  3. Use exec(open(this_file).read(), {'__file__': this_file}).
  4. This can be used when you must use an existing Python interpreter, not the virtualenv bin/python.
  5. """
  6. import os
  7. import site
  8. import sys
  9. try:
  10. abs_file = os.path.abspath(__file__)
  11. except NameError:
  12. raise AssertionError("You must use exec(open(this_file).read(), {'__file__': this_file}))")
  13. bin_dir = os.path.dirname(abs_file)
  14. base = bin_dir[: -len("Scripts") - 1] # strip away the bin part from the __file__, plus the path separator
  15. # prepend bin to PATH (this file is inside the bin directory)
  16. os.environ["PATH"] = os.pathsep.join([bin_dir] + os.environ.get("PATH", "").split(os.pathsep))
  17. os.environ["VIRTUAL_ENV"] = base # virtual env is right above bin directory
  18. # add the virtual environments libraries to the host python import mechanism
  19. prev_length = len(sys.path)
  20. for lib in "..\Lib\site-packages".split(os.pathsep):
  21. path = os.path.realpath(os.path.join(bin_dir, lib))
  22. site.addsitedir(path.decode("utf-8") if "" else path)
  23. sys.path[:] = sys.path[prev_length:] + sys.path[0:prev_length]
  24. sys.real_prefix = sys.prefix
  25. sys.prefix = base