When the name variable is of the form
package.module, normally, the
top-level package (the name up till
the first dot) is returned, not the
module named by name. However, when a
non-empty fromlist argument is given,
the module named by name is returned.
This is done for compatibility with
the bytecode generated for the
different kinds of import statement;
when using "import spam.ham.eggs", the
top-level package spam must be placed
in the importing namespace, but when
using "from spam.ham import eggs", the
spam.ham subpackage must be used to
find the eggs variable. As a
workaround for this behavior, use
getattr() to extract the desired
components. For example, you could
define the following helper:
def my_import(name):
mod = __import__(name)
components = name.split('.')
for comp in components[1:]:
mod = getattr(mod, comp)
return mod
python 2.7具有importlib,点路径按预期解析
来自
__import__
上的python文档:意译如下:
当您请求
somepackage.somemodule
时,__import__
返回somepackage.__init__.py
,通常是空的。如果您提供
fromlist
(您想要的somemodule
内的变量名列表,它将返回somemodule
(实际上没有返回)你也可以像我一样,使用他们建议的功能。
注:我问这个问题完全是想自己回答。我的代码中有一个很大的错误,由于被误诊了,我花了很长时间才弄明白,所以我想我应该帮助so社区解决这个问题,把我遇到的问题贴在这里。
有一个更简单的解决方案,如文档中所述:
如果您只想按名称导入模块(可能在包中),可以调用“导入”,然后在sys.modules中查找它:
相关问题 更多 >
编程相关推荐