venv.py 1.2 KB

123456789101112131415161718192021222324252627282930313233343536
  1. # -*- coding: utf-8 -*-
  2. """Activate venv for current interpreter:
  3. Use `from vtk.web import venv` along one of the following
  4. - `--venv /path/to/venv/base` argument
  5. - environment variable `VTK_VENV=/path/to/venv/base`
  6. This can be used when you must use an existing Python interpreter, not the venv bin/python.
  7. """
  8. import os
  9. import site
  10. import sys
  11. VENV_BASE = None
  12. VENV_LOADED = False
  13. if "--venv" in sys.argv:
  14. VENV_BASE = os.path.abspath(sys.argv[sys.argv.index("--venv") + 1])
  15. if os.environ.get("VTK_VENV"):
  16. VENV_BASE = os.path.abspath(os.environ.get("VTK_VENV"))
  17. if not VENV_LOADED and VENV_BASE and os.path.exists(VENV_BASE):
  18. VENV_LOADED = True
  19. # Code inspired by virutal-env::bin/active_this.py
  20. bin_dir = os.path.join(VENV_BASE, "bin")
  21. os.environ["PATH"] = os.pathsep.join([bin_dir] + os.environ.get("PATH", "").split(os.pathsep))
  22. os.environ["VIRTUAL_ENV"] = VENV_BASE
  23. prev_length = len(sys.path)
  24. python_libs = os.path.join(VENV_BASE, f"lib/python{sys.version_info.major}.{sys.version_info.minor}/site-packages")
  25. site.addsitedir(python_libs)
  26. sys.path[:] = sys.path[prev_length:] + sys.path[0:prev_length]
  27. sys.real_prefix = sys.prefix
  28. sys.prefix = VENV_BASE
  29. #
  30. print(f"VTK is using venv: {VENV_BASE}")