at master 1.7 kB view raw
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 or virtualenv. 25# For Python 3 we check whether our `base_prefix` is different from our current `prefix`. 26# For Python 2 we check whether the non-standard `real_prefix` is set. 27# https://stackoverflow.com/questions/1871549/determine-if-python-is-running-inside-virtualenv 28in_venv = (sys.version_info.major == 3 and sys.prefix != sys.base_prefix) or (sys.version_info.major == 2 and hasattr(sys, "real_prefix")) 29 30if not in_venv: 31 executable = os.environ.pop('NIX_PYTHONEXECUTABLE', None) 32 prefix = os.environ.pop('NIX_PYTHONPREFIX', None) 33 34 if 'PYTHONEXECUTABLE' not in os.environ and executable is not None: 35 sys.executable = executable 36 if prefix is not None: 37 # 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)