我正在做一些不那么标准的python模块导入。我正在向sys.meta_path添加一个finder对象来执行诸如通过http / ssh / svn / etc导入模块之类的操作。我能够使用如下代码成功导入模块:
def load_module(self, fullname, some_path=None):
"""
fullname is something like: this.is.a.module
"""
is_package = figure_out_if_this_is_a_package(fullname)
file_contents = get_file_contents(fullname) # via http/ssh/svn, whatever
mod = sys.modules.setdefault(fullname, imp.new_module(fullname))
mod.__file__ = "<MyFancyMagicImporter>"
mod.__loader__ = self
if is_package:
mod.__path__ = []
mod.__package__ = fullname
else:
mod.__package__ = fullname.rpartition(".")[0]
exec(file_contents, mod.__dict__)
return mod
当动态导入的模块(让我们称之为ssh.test_module
)尝试导入某些内容时,会出现问题。如果ssh.test_module
执行类似import os
的操作,则实际上最终会尝试执行import ssh.test_module.os
之类的相对导入。如果此相对外观导入失败,则导入将完全失败。
帮助?
更新:BTW,我正在使用python 2.7
更新以下是一个更好的示例,演示了我遇到的问题:
#!/usr/bin/env python
import sys
import imp
class Loader(object):
def load_module(self, fullname, some_path=None):
file_contents = ""
if fullname == "loader_testing":
file_contents = "import os"
elif fullname == "loader_testing.blah":
file_contents = "import sys\nimport os\nimport loader_testing.halb"
elif fullname == "loader_testing.halb":
file_contents = "print('HALBHALBHALB')"
mod = sys.modules.setdefault(fullname, imp.new_module(fullname))
mod.__file__ = "<%s>" % self.__class__.__name__
mod.__loader__ = self
is_package = fullname.count(".") == 0
if is_package:
mod.__path__ = []
mod.__package__ = fullname
else:
mod.__package__ = fullname.rpartition('.')[0]
mod.__path__ = []
exec(file_contents, mod.__dict__)
return mod
def find_module(self, fullname, path=None):
if fullname.find("loader_testing") == 0:
print "loader_testing, fullname: %s" % fullname
return self
return None
sys.meta_path.append(Loader())
import loader_testing.blah
我希望上面的代码输出如下内容:
loader_testing, fullname: loader_testing
loader_testing, fullname: loader_testing.blah
loader_testing, fullname: loader_testing.halb
HALBHALBHALB
相反,你得到了这个:
loader_testing, fullname: loader_testing
loader_testing, fullname: loader_testing.os
loader_testing, fullname: loader_testing.blah
loader_testing, fullname: loader_testing.sys
loader_testing, fullname: loader_testing.loader_testing
loader_testing, fullname: loader_testing.loader_testing.halb
注意看似与loader_testing.loader_testing.halb
相关导入的内容
答案 0 :(得分:1)
最终解决此问题的方法是从将来导入absolute_path
。我认为默认情况下它在python 2.7.3中已经处于活动状态,但我想我错了:
from __future__ import absolute_path