What is the equivalent of imp.find_module in importlib

Same folder

If the module is in your working directory, importlib.util.find_spec probably suffices for your purposes.

For example if you just want to load the module, you can use:

  • deprecated in Python 3.5 and higher:

    toolbox_specs = importlib.util.find_spec("Tools")
    toolbox = toolbox_specs.loader.load_module()
    
  • introduced in Python 3.5 and higher:

    toolbox_specs = importlib.util.find_spec("Tools")
    toolbox = importlib.util.module_from_spec(toolbox_specs)
    toolbox_specs.loader.exec_module(toolbox)
    

    Caveat: I haven’t tested this, but it’s straight from the documentation, so I suppose it works.

You can assess several other properties with the toolbox_specs object.
However, e.g., a corresponding file object is not amongst them.
If you really need this in Python 3, you probably have to obtain the file’s path and open it with other methods.

Different folder

To find a module in a different folder, you have to work with a FileFinder, which in turn needs to know the module’s type. For example, if your module is an extension, you can find the specs as follows:

loader_details = (
    importlib.machinery.ExtensionFileLoader,
    importlib.machinery.EXTENSION_SUFFIXES
    )

toolsfinder = importlib.machinery.FileFinder("Folder_of_Tools", loader_details)
toolbox_specs = toolsfinder.find_spec("Tools")

You can then process toolbox_specs as described above.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)