Skip to content

Commit b74c8f5

Browse files
authored
GH-126985: Don't override venv detection with PYTHONHOME (#127968)
1 parent 46006a1 commit b74c8f5

File tree

2 files changed

+38
-3
lines changed

2 files changed

+38
-3
lines changed

Lib/test/test_getpath.py

+31
Original file line numberDiff line numberDiff line change
@@ -832,6 +832,37 @@ def test_explicitly_set_stdlib_dir(self):
832832
actual = getpath(ns, expected)
833833
self.assertEqual(expected, actual)
834834

835+
def test_PYTHONHOME_in_venv(self):
836+
"Make sure prefix/exec_prefix still point to the venv if PYTHONHOME was used."
837+
ns = MockPosixNamespace(
838+
argv0="/venv/bin/python",
839+
PREFIX="/usr",
840+
ENV_PYTHONHOME="/pythonhome",
841+
)
842+
# Setup venv
843+
ns.add_known_xfile("/venv/bin/python")
844+
ns.add_known_file("/venv/pyvenv.cfg", [
845+
r"home = /usr/bin"
846+
])
847+
# Seutup PYTHONHOME
848+
ns.add_known_file("/pythonhome/lib/python9.8/os.py")
849+
ns.add_known_dir("/pythonhome/lib/python9.8/lib-dynload")
850+
851+
expected = dict(
852+
executable="/venv/bin/python",
853+
prefix="/venv",
854+
exec_prefix="/venv",
855+
base_prefix="/pythonhome",
856+
base_exec_prefix="/pythonhome",
857+
module_search_paths_set=1,
858+
module_search_paths=[
859+
"/pythonhome/lib/python98.zip",
860+
"/pythonhome/lib/python9.8",
861+
"/pythonhome/lib/python9.8/lib-dynload",
862+
],
863+
)
864+
actual = getpath(ns, expected)
865+
self.assertEqual(expected, actual)
835866

836867
# ******************************************************************************
837868

Modules/getpath.py

+7-3
Original file line numberDiff line numberDiff line change
@@ -344,9 +344,10 @@ def search_up(prefix, *landmarks, test=isfile):
344344

345345
venv_prefix = None
346346

347-
# Calling Py_SetPythonHome(), Py_SetPath() or
348-
# setting $PYTHONHOME will override venv detection.
349-
if not home and not py_setpath:
347+
# Calling Py_SetPath() will override venv detection.
348+
# Calling Py_SetPythonHome() or setting $PYTHONHOME will override the 'home' key
349+
# specified in pyvenv.cfg.
350+
if not py_setpath:
350351
try:
351352
# prefix2 is just to avoid calculating dirname again later,
352353
# as the path in venv_prefix is the more common case.
@@ -370,6 +371,9 @@ def search_up(prefix, *landmarks, test=isfile):
370371
for line in pyvenvcfg:
371372
key, had_equ, value = line.partition('=')
372373
if had_equ and key.strip().lower() == 'home':
374+
# If PYTHONHOME was set, ignore 'home' from pyvenv.cfg.
375+
if home:
376+
break
373377
# Override executable_dir/real_executable_dir with the value from 'home'.
374378
# These values may be later used to calculate prefix/base_prefix, if a more
375379
# reliable source — like the runtime library (libpython) path — isn't available.

0 commit comments

Comments
 (0)