Fix sys.prefix in case of a Nix env

The prefix will now be correct in case of Nix env.

Note, however, that creating a venv from a Nix env still does not function. This does not seem to be possible
with the current approach either, because venv will copy or symlink our Python wrapper. In case it symlinks
(the default) it won't see a pyvenv.cfg. If it is copied I think it should function but it does not...
This commit is contained in:
Frederik Rietdijk 2020-03-14 16:22:36 +01:00 committed by adisbladis
parent 753122388d
commit 7447fff95a
No known key found for this signature in database
GPG key ID: 110BFAD44C6249B7
2 changed files with 17 additions and 8 deletions

View file

@ -21,10 +21,19 @@ paths = os.environ.pop('NIX_PYTHONPATH', None)
if paths:
functools.reduce(lambda k, p: site.addsitedir(p, k), paths.split(':'), site._init_pathinfo())
prefixes = os.environ.pop('NIX_PYTHONPREFIX', None)
if prefixes:
site.PREFIXES.extend(prefixes.split(':'))
# Check whether we are in a venv.
# Note Python 2 does not support base_prefix so we assume we are not in a venv.
in_venv = sys.version_info.major == 3 and sys.prefix != sys.base_prefix
executable = os.environ.pop('NIX_PYTHONEXECUTABLE', None)
if 'PYTHONEXECUTABLE' not in os.environ and executable:
sys.executable = executable
if not in_venv:
executable = os.environ.pop('NIX_PYTHONEXECUTABLE', None)
prefix = os.environ.pop('NIX_PYTHONPREFIX', None)
if 'PYTHONEXECUTABLE' not in os.environ and executable is not None:
sys.executable = executable
if prefix is not None:
# Because we cannot check with Python 2 whether we are in a venv,
# creating a venv from a Nix env won't work as well with Python 2.
# Also, note that sysconfig does not like it when sys.prefix is set to None
sys.prefix = sys.exec_prefix = prefix
site.PREFIXES.insert(0, prefix)

View file

@ -27,7 +27,7 @@ class TestCasePython(unittest.TestCase):
def test_interpreter(self):
self.assertEqual(sys.executable, INTERPRETER)
@unittest.skipIf(IS_NIXENV or IS_PYPY, "Prefix is incorrect and needs to be fixed.")
@unittest.skipIf(IS_PYPY, "Prefix is incorrect and needs to be fixed.")
def test_prefix(self):
self.assertEqual(sys.prefix, ENV)
self.assertEqual(sys.prefix, sys.exec_prefix)
@ -37,7 +37,7 @@ class TestCasePython(unittest.TestCase):
@unittest.skipIf(IS_PYPY or sys.version_info.major==2, "Python 2 does not have base_prefix")
def test_base_prefix(self):
if IS_VENV:
if IS_VENV or IS_NIXENV:
self.assertNotEqual(sys.prefix, sys.base_prefix)
else:
self.assertEqual(sys.prefix, sys.base_prefix)