1from __future__ import annotations
2
3import logging
4import os
5import re
6import sys
7
8logger = logging.getLogger(__name__)
9_INCLUDE_SYSTEM_SITE_PACKAGES_REGEX = re.compile(
10 r"include-system-site-packages\s*=\s*(?P<value>true|false)"
11)
12
13
14def running_under_virtualenv() -> bool:
15 """Checks if sys.base_prefix and sys.prefix match.
16
17 This handles PEP 405 compliant virtual environments.
18 """
19 return sys.prefix != getattr(sys, "base_prefix", sys.prefix)
20
21
22def _get_pyvenv_cfg_lines() -> list[str] | None:
23 """Reads {sys.prefix}/pyvenv.cfg and returns its contents as list of lines
24
25 Returns None, if it could not read/access the file.
26 """
27 pyvenv_cfg_file = os.path.join(sys.prefix, "pyvenv.cfg")
28 try:
29 # Although PEP 405 does not specify, the built-in venv module always
30 # writes with UTF-8. (pypa/pip#8717)
31 with open(pyvenv_cfg_file, encoding="utf-8") as f:
32 return f.read().splitlines() # avoids trailing newlines
33 except OSError:
34 return None
35
36
37def _no_global_under_venv() -> bool:
38 """Check `{sys.prefix}/pyvenv.cfg` for system site-packages inclusion
39
40 PEP 405 specifies that when system site-packages are not supposed to be
41 visible from a virtual environment, `pyvenv.cfg` must contain the following
42 line:
43
44 include-system-site-packages = false
45
46 Additionally, log a warning if accessing the file fails.
47 """
48 cfg_lines = _get_pyvenv_cfg_lines()
49 if cfg_lines is None:
50 # We're not in a "sane" venv, so assume there is no system
51 # site-packages access (since that's PEP 405's default state).
52 logger.warning(
53 "Could not access 'pyvenv.cfg' despite a virtual environment "
54 "being active. Assuming global site-packages is not accessible "
55 "in this environment."
56 )
57 return True
58
59 for line in cfg_lines:
60 match = _INCLUDE_SYSTEM_SITE_PACKAGES_REGEX.match(line)
61 if match is not None and match.group("value") == "false":
62 return True
63 return False
64
65
66def virtualenv_no_global() -> bool:
67 """Returns a boolean, whether running in venv with no system site-packages."""
68 if running_under_virtualenv():
69 return _no_global_under_venv()
70
71 return False