venv.py 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. # -*- coding: utf-8 -*-
  2. """Activate venv for current interpreter:
  3. Use `from paraview.web import venv` along one of the following
  4. - `--venv /path/to/venv/base` argument
  5. - environment variable `PV_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("PV_VENV"):
  16. VENV_BASE = os.path.abspath(os.environ.get("PV_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. if sys.platform == "win32":
  25. python_libs = os.path.join(VENV_BASE, "Lib/site-packages")
  26. else:
  27. python_libs = os.path.join(VENV_BASE, f"lib/python{sys.version_info.major}.{sys.version_info.minor}/site-packages")
  28. site.addsitedir(python_libs)
  29. sys.path[:] = sys.path[prev_length:] + sys.path[0:prev_length]
  30. sys.real_prefix = sys.prefix
  31. sys.prefix = VENV_BASE
  32. #
  33. print(f"ParaView is using venv: {VENV_BASE}")