python / cpython

The Python programming language
https://www.python.org
Other
63.39k stars 30.36k forks source link

dynamic import of module fails from readonly location #124168

Open thiri42 opened 1 month ago

thiri42 commented 1 month ago

Bug report

Bug description:


# Source https://medium.com/@Doug-Creates/dynamically-import-a-module-by-full-path-in-python-bbdf4815153e
# Function to dynamically import a module given its full path
def import_module_from_path(module_name, path):
    # Create a module spec from the given path
    spec = importlib.util.spec_from_file_location(module_name, path)

    # Load the module from the created spec
    module = importlib.util.module_from_spec(spec)

    # Execute the module to make its attributes accessible
    spec.loader.exec_module(module)

    # Return the imported module
    return module

The problem is that the method exec_module tries to write the pyc file and throws an Exception when the permission for the module path is readonly.

I would suggest to check the write permission before creating the pyc file.

CPython versions tested on:

3.11

Operating systems tested on:

Linux

graingert commented 1 month ago

@thiri42 can you show the full traceback? importlib has code to defend against this case https://github.com/python/cpython/blob/28aea5d07d163105b42acd81c1651397ef95ea57/Lib/importlib/_bootstrap_external.py#L996