1

我正在做一些不那么标准的python模块导入。我正在向 sys.meta_path 添加一个查找器对象,以执行诸如通过 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。如果此相对外观的导入失败,则导入将完全失败。

帮助?

更新:顺便说一句,我正在使用 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和这样的

4

1 回答 1

1

最终解决这个问题的是absolute_pathfuture导入。我认为在 python 2.7.3 中默认情况下它已经处于活动状态,但我想我错了:

from __future__ import absolute_path
于 2012-10-19T15:23:22.443 回答