__import__ vs imp.load_module

2019-06-22 08:59发布

问题:

I got an error while trying to install autopep8 with ironpython:

ImportError: No module named logilab

The code snippet it failed is:

def load_module(self, fullname):
    self._reopen()
    try:
        mod = imp.load_module(fullname, self.file, self.filename, self.etc)
    finally:
        if self.file:
            self.file.close()
    # Note: we don't set __loader__ because we want the module to look
    # normal; i.e. this is just a wrapper for standard import machinery
    return mod

using the interpreter ipy64 importing logilab did not fail. I added a print statement for the filename and it showed:

C:\Program Files (x86)\IronPython 2.7\Lib\site-packages\logilab_common-0.59.1-py2.7.egg\logilab

The path exists and it contains a init.py with the following content:

"""generated file, don't modify or your data will be lost"""
try:
    __import__('pkg_resources').declare_namespace(__name__)
except ImportError:
    pass

I fixed the error quick and dirty by adding

except ImportError:
    mod = __import__(fullname)

but I do not have a good feeling about this fix as I don't know the possible impacts.

Now, why does using imp.load_module fail and what is the difference using import ?