···2121if paths:
2222 functools.reduce(lambda k, p: site.addsitedir(p, k), paths.split(':'), site._init_pathinfo())
23232424-# Check whether we are in a venv.
2525-# Note Python 2 does not support base_prefix so we assume we are not in a venv.
2626-in_venv = sys.version_info.major == 3 and sys.prefix != sys.base_prefix
2424+# Check whether we are in a venv or virtualenv.
2525+# For Python 3 we check whether our `base_prefix` is different from our current `prefix`.
2626+# For Python 2 we check whether the non-standard `real_prefix` is set.
2727+# https://stackoverflow.com/questions/1871549/determine-if-python-is-running-inside-virtualenv
2828+in_venv = (sys.version_info.major == 3 and sys.prefix != sys.base_prefix) or (sys.version_info.major == 2 and hasattr(sys, "real_prefix"))
27292830if not in_venv:
2931 executable = os.environ.pop('NIX_PYTHONEXECUTABLE', None)
···3234 if 'PYTHONEXECUTABLE' not in os.environ and executable is not None:
3335 sys.executable = executable
3436 if prefix is not None:
3535- # Because we cannot check with Python 2 whether we are in a venv,
3636- # creating a venv from a Nix env won't work as well with Python 2.
3737- # Also, note that sysconfig does not like it when sys.prefix is set to None
3737+ # Sysconfig does not like it when sys.prefix is set to None
3838 sys.prefix = sys.exec_prefix = prefix
3939 site.PREFIXES.insert(0, prefix)
+1-3
pkgs/development/interpreters/python/tests.nix
···1919 is_nixenv = "False";
2020 is_virtualenv = "False";
2121 };
2222- } // lib.optionalAttrs (python.isPy3k && !python.isPyPy) {
2222+ } // lib.optionalAttrs (!python.isPyPy) {
2323 # Use virtualenv from a Nix env.
2424- # Does not function with Python 2
2525- # ValueError: source and destination is the same /nix/store/38kz3j1a87cq5y59k5w7k9yk4cqgc5b2-python-2.7.18/lib/python2.7/os.py
2624 nixenv-virtualenv = rec {
2725 env = runCommand "${python.name}-virtualenv" {} ''
2826 ${pythonVirtualEnv.interpreter} -m virtualenv $out
···4343 else:
4444 self.assertEqual(sys.prefix, sys.base_prefix)
45454646+ @unittest.skipIf(sys.version_info.major==3, "sys.real_prefix is only set by virtualenv in case of Python 2.")
4747+ def test_real_prefix(self):
4848+ self.assertTrue(hasattr(sys, "real_prefix") == IS_VIRTUALENV)
4949+4650 def test_python_version(self):
4751 self.assertTrue(platform.python_version().startswith(PYTHON_VERSION))
4852