__import__ vs imp.load_module

夙愿已清 提交于 2020-01-14 10:04:10

问题


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 ?

来源:https://stackoverflow.com/questions/16775674/import-vs-imp-load-module

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!