python导入钩子处理复杂的路径

时间:2016-09-04 16:30:41

标签: python

我有当前的测试导入钩子:

class TestImporter(object):


    def find_module(self, fullname, path):
        print "finding ", fullname
        print "in path ", path
        return None

    def load_module(self, fullname):
        print "loading ", fullname
        return None



sys.meta_path.append(TestImporter())
import xml.etree.ElementTree

输出

finding  xml
in path  None
finding  xml._xmlplus
in path  ['/usr/lib64/pypy-5.0.1/lib-python/2.7/xml']
finding  _xmlplus
in path  None
finding  xml.etree
in path  ['/usr/lib64/pypy-5.0.1/lib-python/2.7/xml']
finding  xml.etree.ElementTree
in path  ['/usr/lib64/pypy-5.0.1/lib-python/2.7/xml/etree']
finding  xml.etree.sys
in path  ['/usr/lib64/pypy-5.0.1/lib-python/2.7/xml/etree']
finding  xml.etree.re
in path  ['/usr/lib64/pypy-5.0.1/lib-python/2.7/xml/etree']
finding  xml.etree.warnings
in path  ['/usr/lib64/pypy-5.0.1/lib-python/2.7/xml/etree']
finding  xml.etree.ElementPath
in path  ['/usr/lib64/pypy-5.0.1/lib-python/2.7/xml/etree']
finding  xml.etree.ElementC14N
in path  ['/usr/lib64/pypy-5.0.1/lib-python/2.7/xml/etree']
finding  ElementC14N
in path  None

注意我的代码load_module基本上是空白的,而find_module没有返回自己的实例来加载它。要加载任何模块,可以调用:

importlib.import_module("module_name")

然而;根据输出结果,这些模块中的一些甚至不是有效的,例如:

xml.etree.sys

xml.etree.re

导入xml.etree.ElementTree时,加载程序会尝试导入模块也导入的任何内容(在本例中为sys和re)。这显然会连接到模块的全名。加载器如何处理,因为xml.etree.re和xml.etree.re不是要加载的有效模块,但是" sys"和"重新"是有效的。如何创建一个加载器来处理上面输出创建的一些路径/名称?

0 个答案:

没有答案