bpo-46049: Fixes ._pth support on non-Windows (GH-30051)

This commit is contained in:
Steve Dower 2021-12-11 15:06:17 +00:00 committed by GitHub
parent 971ece8e17
commit bfc59ed0a0
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 52 additions and 41 deletions

View File

@ -564,26 +564,39 @@ class StartupImportTests(unittest.TestCase):
'import site, sys; site.enablerlcompleter(); sys.exit(hasattr(sys, "__interactivehook__"))']).wait() 'import site, sys; site.enablerlcompleter(); sys.exit(hasattr(sys, "__interactivehook__"))']).wait()
self.assertTrue(r, "'__interactivehook__' not added by enablerlcompleter()") self.assertTrue(r, "'__interactivehook__' not added by enablerlcompleter()")
@unittest.skipUnless(sys.platform == 'win32', "only supported on Windows")
class _pthFileTests(unittest.TestCase): class _pthFileTests(unittest.TestCase):
def _create_underpth_exe(self, lines, exe_pth=True): if sys.platform == 'win32':
import _winapi def _create_underpth_exe(self, lines, exe_pth=True):
temp_dir = tempfile.mkdtemp() import _winapi
self.addCleanup(os_helper.rmtree, temp_dir) temp_dir = tempfile.mkdtemp()
exe_file = os.path.join(temp_dir, os.path.split(sys.executable)[1]) self.addCleanup(os_helper.rmtree, temp_dir)
dll_src_file = _winapi.GetModuleFileName(sys.dllhandle) exe_file = os.path.join(temp_dir, os.path.split(sys.executable)[1])
dll_file = os.path.join(temp_dir, os.path.split(dll_src_file)[1]) dll_src_file = _winapi.GetModuleFileName(sys.dllhandle)
shutil.copy(sys.executable, exe_file) dll_file = os.path.join(temp_dir, os.path.split(dll_src_file)[1])
shutil.copy(dll_src_file, dll_file) shutil.copy(sys.executable, exe_file)
if exe_pth: shutil.copy(dll_src_file, dll_file)
_pth_file = os.path.splitext(exe_file)[0] + '._pth' if exe_pth:
else: _pth_file = os.path.splitext(exe_file)[0] + '._pth'
_pth_file = os.path.splitext(dll_file)[0] + '._pth' else:
with open(_pth_file, 'w') as f: _pth_file = os.path.splitext(dll_file)[0] + '._pth'
for line in lines: with open(_pth_file, 'w') as f:
print(line, file=f) for line in lines:
return exe_file print(line, file=f)
return exe_file
else:
def _create_underpth_exe(self, lines, exe_pth=True):
if not exe_pth:
raise unittest.SkipTest("library ._pth file not supported on this platform")
temp_dir = tempfile.mkdtemp()
self.addCleanup(os_helper.rmtree, temp_dir)
exe_file = os.path.join(temp_dir, os.path.split(sys.executable)[1])
os.symlink(sys.executable, exe_file)
_pth_file = exe_file + '._pth'
with open(_pth_file, 'w') as f:
for line in lines:
print(line, file=f)
return exe_file
def _calc_sys_path_for_underpth_nosite(self, sys_prefix, lines): def _calc_sys_path_for_underpth_nosite(self, sys_prefix, lines):
sys_path = [] sys_path = []
@ -605,7 +618,7 @@ class _pthFileTests(unittest.TestCase):
output = subprocess.check_output([exe_file, '-c', output = subprocess.check_output([exe_file, '-c',
'import sys; print("\\n".join(sys.path) if sys.flags.no_site else "")' 'import sys; print("\\n".join(sys.path) if sys.flags.no_site else "")'
], encoding='ansi') ], encoding='utf-8', errors='surrogateescape')
actual_sys_path = output.rstrip().split('\n') actual_sys_path = output.rstrip().split('\n')
self.assertTrue(actual_sys_path, "sys.flags.no_site was False") self.assertTrue(actual_sys_path, "sys.flags.no_site was False")
self.assertEqual( self.assertEqual(
@ -630,10 +643,10 @@ class _pthFileTests(unittest.TestCase):
env = os.environ.copy() env = os.environ.copy()
env['PYTHONPATH'] = 'from-env' env['PYTHONPATH'] = 'from-env'
env['PATH'] = '{};{}'.format(exe_prefix, os.getenv('PATH')) env['PATH'] = '{}{}{}'.format(exe_prefix, os.pathsep, os.getenv('PATH'))
output = subprocess.check_output([exe_file, '-c', output = subprocess.check_output([exe_file, '-c',
'import sys; print("\\n".join(sys.path) if sys.flags.no_site else "")' 'import sys; print("\\n".join(sys.path) if sys.flags.no_site else "")'
], env=env, encoding='ansi') ], env=env, encoding='utf-8', errors='surrogateescape')
actual_sys_path = output.rstrip().split('\n') actual_sys_path = output.rstrip().split('\n')
self.assertTrue(actual_sys_path, "sys.flags.no_site was False") self.assertTrue(actual_sys_path, "sys.flags.no_site was False")
self.assertEqual( self.assertEqual(
@ -666,7 +679,6 @@ class _pthFileTests(unittest.TestCase):
)], env=env) )], env=env)
self.assertTrue(rc, "sys.path is incorrect") self.assertTrue(rc, "sys.path is incorrect")
def test_underpth_dll_file(self): def test_underpth_dll_file(self):
libpath = test.support.STDLIB_DIR libpath = test.support.STDLIB_DIR
exe_prefix = os.path.dirname(sys.executable) exe_prefix = os.path.dirname(sys.executable)

View File

@ -0,0 +1 @@
Ensure :file:`._pth` files work as intended on platforms other than Windows.

View File

@ -141,7 +141,7 @@ getpath_hassuffix(PyObject *Py_UNUSED(self), PyObject *args)
if (path) { if (path) {
suffix = PyUnicode_AsWideCharString(suffixobj, &suffixLen); suffix = PyUnicode_AsWideCharString(suffixobj, &suffixLen);
if (suffix) { if (suffix) {
if (suffixLen < len || if (suffixLen > len ||
#ifdef MS_WINDOWS #ifdef MS_WINDOWS
wcsicmp(&path[len - suffixLen], suffix) != 0 wcsicmp(&path[len - suffixLen], suffix) != 0
#else #else

View File

@ -407,24 +407,22 @@ pth_dir = None
# Calling Py_SetPythonHome() or Py_SetPath() will override ._pth search, # Calling Py_SetPythonHome() or Py_SetPath() will override ._pth search,
# but environment variables and command-line options cannot. # but environment variables and command-line options cannot.
if not py_setpath and not home_was_set: if not py_setpath and not home_was_set:
# Check adjacent to the main DLL/dylib/so # 1. Check adjacent to the main DLL/dylib/so (if set)
if library: # 2. Check adjacent to the original executable
try: # 3. Check adjacent to our actual executable
pth = readlines(library.rpartition('.')[0] + '._pth') # This may allow a venv to override the base_executable's
pth_dir = dirname(library) # ._pth file, but it cannot override the library's one.
except FileNotFoundError: for p in [library, executable, real_executable]:
pass if p:
if os_name == 'nt' and (hassuffix(p, 'exe') or hassuffix(p, 'dll')):
# Check adjacent to the original executable, even if we p = p.rpartition('.')[0]
# redirected to actually launch Python. This may allow a p += '._pth'
# venv to override the base_executable's ._pth file, but try:
# it cannot override the library's one. pth = readlines(p)
if not pth_dir: pth_dir = dirname(p)
try: break
pth = readlines(executable.rpartition('.')[0] + '._pth') except OSError:
pth_dir = dirname(executable) pass
except FileNotFoundError:
pass
# If we found a ._pth file, disable environment and home # If we found a ._pth file, disable environment and home
# detection now. Later, we will do the rest. # detection now. Later, we will do the rest.