···21if paths:
22 functools.reduce(lambda k, p: site.addsitedir(p, k), paths.split(':'), site._init_pathinfo())
2324-# 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.
26-in_venv = sys.version_info.major == 3 and sys.prefix != sys.base_prefix
002728if not in_venv:
29 executable = os.environ.pop('NIX_PYTHONEXECUTABLE', None)
···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)
···21if paths:
22 functools.reduce(lambda k, p: site.addsitedir(p, k), paths.split(':'), site._init_pathinfo())
2324+# 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
28+in_venv = (sys.version_info.major == 3 and sys.prefix != sys.base_prefix) or (sys.version_info.major == 2 and hasattr(sys, "real_prefix"))
2930if not in_venv:
31 executable = os.environ.pop('NIX_PYTHONEXECUTABLE', None)
···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
0038 sys.prefix = sys.exec_prefix = prefix
39 site.PREFIXES.insert(0, prefix)
+1-3
pkgs/development/interpreters/python/tests.nix
···19 is_nixenv = "False";
20 is_virtualenv = "False";
21 };
22- } // lib.optionalAttrs (python.isPy3k && !python.isPyPy) {
23 # Use virtualenv from a Nix env.
24- # Does not function with Python 2
25- # ValueError: source and destination is the same /nix/store/38kz3j1a87cq5y59k5w7k9yk4cqgc5b2-python-2.7.18/lib/python2.7/os.py
26 nixenv-virtualenv = rec {
27 env = runCommand "${python.name}-virtualenv" {} ''
28 ${pythonVirtualEnv.interpreter} -m virtualenv $out
···43 else:
44 self.assertEqual(sys.prefix, sys.base_prefix)
4546+ @unittest.skipIf(sys.version_info.major==3, "sys.real_prefix is only set by virtualenv in case of Python 2.")
47+ def test_real_prefix(self):
48+ self.assertTrue(hasattr(sys, "real_prefix") == IS_VIRTUALENV)
49+50 def test_python_version(self):
51 self.assertTrue(platform.python_version().startswith(PYTHON_VERSION))
52