Skip to content

Instantly share code, notes, and snippets.

@moreati
Last active February 29, 2024 13:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save moreati/184bdbd10a18a88df37242bc711318d1 to your computer and use it in GitHub Desktop.
Save moreati/184bdbd10a18a88df37242bc711318d1 to your computer and use it in GitHub Desktop.
importlib PathFinder monkeypatch for Python issue 115911 (getcwd() EACCESS)
# Monkeypatch that replaces the importlib PathFinder in sys.meta_path
# with one that handles EACCES returned by libc getcwd() on macOS.
# Workaround for https://github.com/python/cpython/issues/115911
import errno
import sys
try:
import _frozen_importlib_external
except ImportError:
pass
else:
class MonkeyPatchedPathFinder(_frozen_importlib_external.PathFinder):
@classmethod
def _path_importer_cache(cls, path):
if path == '':
try:
path = _frozen_importlib_external._os.getcwd()
except OSError as exc:
if exc.errno in (errno.EACCES, errno.ENOENT):
return None
return _frozen_importlib_external.PathFinder._path_importer_cache(path)
for i, mpf in enumerate(sys.meta_path):
if mpf is _frozen_importlib_external.PathFinder:
sys.meta_path[i] = MonkeyPatchedPathFinder
del i, mpf
@moreati
Copy link
Author

moreati commented Feb 29, 2024

Caveat: this only works for Python < 3.12. At time of writing Python 3.13 suffers the PermissionError before any user code is executed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment