virtualenv.py 3.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  1. from __future__ import absolute_import
  2. import logging
  3. import os
  4. import re
  5. import site
  6. import sys
  7. from pip._internal.utils.typing import MYPY_CHECK_RUNNING
  8. if MYPY_CHECK_RUNNING:
  9. from typing import List, Optional
  10. logger = logging.getLogger(__name__)
  11. _INCLUDE_SYSTEM_SITE_PACKAGES_REGEX = re.compile(
  12. r"include-system-site-packages\s*=\s*(?P<value>true|false)"
  13. )
  14. def _running_under_venv():
  15. # type: () -> bool
  16. """Checks if sys.base_prefix and sys.prefix match.
  17. This handles PEP 405 compliant virtual environments.
  18. """
  19. return sys.prefix != getattr(sys, "base_prefix", sys.prefix)
  20. def _running_under_regular_virtualenv():
  21. # type: () -> bool
  22. """Checks if sys.real_prefix is set.
  23. This handles virtual environments created with pypa's virtualenv.
  24. """
  25. # pypa/virtualenv case
  26. return hasattr(sys, 'real_prefix')
  27. def running_under_virtualenv():
  28. # type: () -> bool
  29. """Return True if we're running inside a virtualenv, False otherwise.
  30. """
  31. return _running_under_venv() or _running_under_regular_virtualenv()
  32. def _get_pyvenv_cfg_lines():
  33. # type: () -> Optional[List[str]]
  34. """Reads {sys.prefix}/pyvenv.cfg and returns its contents as list of lines
  35. Returns None, if it could not read/access the file.
  36. """
  37. pyvenv_cfg_file = os.path.join(sys.prefix, 'pyvenv.cfg')
  38. try:
  39. with open(pyvenv_cfg_file) as f:
  40. return f.read().splitlines() # avoids trailing newlines
  41. except IOError:
  42. return None
  43. def _no_global_under_venv():
  44. # type: () -> bool
  45. """Check `{sys.prefix}/pyvenv.cfg` for system site-packages inclusion
  46. PEP 405 specifies that when system site-packages are not supposed to be
  47. visible from a virtual environment, `pyvenv.cfg` must contain the following
  48. line:
  49. include-system-site-packages = false
  50. Additionally, log a warning if accessing the file fails.
  51. """
  52. cfg_lines = _get_pyvenv_cfg_lines()
  53. if cfg_lines is None:
  54. # We're not in a "sane" venv, so assume there is no system
  55. # site-packages access (since that's PEP 405's default state).
  56. logger.warning(
  57. "Could not access 'pyvenv.cfg' despite a virtual environment "
  58. "being active. Assuming global site-packages is not accessible "
  59. "in this environment."
  60. )
  61. return True
  62. for line in cfg_lines:
  63. match = _INCLUDE_SYSTEM_SITE_PACKAGES_REGEX.match(line)
  64. if match is not None and match.group('value') == 'false':
  65. return True
  66. return False
  67. def _no_global_under_regular_virtualenv():
  68. # type: () -> bool
  69. """Check if "no-global-site-packages.txt" exists beside site.py
  70. This mirrors logic in pypa/virtualenv for determining whether system
  71. site-packages are visible in the virtual environment.
  72. """
  73. site_mod_dir = os.path.dirname(os.path.abspath(site.__file__))
  74. no_global_site_packages_file = os.path.join(
  75. site_mod_dir, 'no-global-site-packages.txt',
  76. )
  77. return os.path.exists(no_global_site_packages_file)
  78. def virtualenv_no_global():
  79. # type: () -> bool
  80. """Returns a boolean, whether running in venv with no system site-packages.
  81. """
  82. # PEP 405 compliance needs to be checked first since virtualenv >=20 would
  83. # return True for both checks, but is only able to use the PEP 405 config.
  84. if _running_under_venv():
  85. return _no_global_under_venv()
  86. if _running_under_regular_virtualenv():
  87. return _no_global_under_regular_virtualenv()
  88. return False