1"""
2This is a Nix-specific module for discovering modules built with Nix.
3
4The module recursively adds paths that are on `NIX_PYTHONPATH` to `sys.path`. In
5order to process possible `.pth` files `site.addsitedir` is used.
6
7The paths listed in `PYTHONPATH` are added to `sys.path` afterwards, but they
8will be added before the entries we add here and thus take precedence.
9
10Note the `NIX_PYTHONPATH` environment variable is unset in order to prevent leakage.
11
12Similarly, this module listens to the environment variable `NIX_PYTHONEXECUTABLE`
13and sets `sys.executable` to its value.
14"""
15import site
16import sys
17import os
18import functools
19
20paths = os.environ.pop('NIX_PYTHONPATH', None)
21if paths:
22 functools.reduce(lambda k, p: site.addsitedir(p, k), paths.split(':'), site._init_pathinfo())
23
24# Check whether we are in a venv.
25# Note Python 2 does not support base_prefix so we assume we are not in a venv.
26in_venv = sys.version_info.major == 3 and sys.prefix != sys.base_prefix
27
28if not in_venv:
29 executable = os.environ.pop('NIX_PYTHONEXECUTABLE', None)
30 prefix = os.environ.pop('NIX_PYTHONPREFIX', None)
31
32 if 'PYTHONEXECUTABLE' not in os.environ and executable is not None:
33 sys.executable = executable
34 if prefix is not None:
35 # Because we cannot check with Python 2 whether we are in a venv,
36 # creating a venv from a Nix env won't work as well with Python 2.
37 # Also, note that sysconfig does not like it when sys.prefix is set to None
38 sys.prefix = sys.exec_prefix = prefix
39 site.PREFIXES.insert(0, prefix)