zipimporter 不能 find/load 子模块

zipimporter can't find/load sub-modules

我正在尝试从 ZIP 包加载子模块,但它不起作用。怎么做才对?

foo.zip

foo/
    __init__.py
   bar.py

test.py

import os
import zipimport

dirname = os.path.dirname(__file__)
importer = zipimport.zipimporter(os.path.join(dirname, 'foo.zip'))
print importer.is_package('foo')
print importer.load_module('foo')
print importer.load_module('foo.bar')

输出

$ python test.py
True
<module 'foo' from 'foo.zip/foo/__init__.py'>
Traceback (most recent call last):
  File "test.py", line 8, in <module>
    print importer.load_module('foo.bar')
zipimport.ZipImportError: can't find module 'foo.bar'

更新 2015/04/11 06:30 太平洋时间上午

下面的方法可行,但这是解决问题的真正方法吗? zipimport.zipimporter 文档明确指出 "fullname must be the fully qualified (dotted) module name." 并且有一个 is_package() 方法似乎可以正常运行。

import os
import zipimport

dirname = os.path.dirname(__file__)
importer = zipimport.zipimporter(os.path.join(dirname, 'foo.zip'))

def load_module(name):
    parts = name.split('.')
    module = importer.load_module(parts[0])
    full_name = parts[0]
    for part in parts[1:]:
        full_name += '.' + part
        if not hasattr(module, '__path__'):
            raise ImportError('%s' % full_name)
        path = module.__path__[0]
        module = zipimport.zipimporter(path).load_module(part)

    return module

print load_module('foo.bar')

如果您将 importer.load_module('foo.bar') 更改为 importer.load_module('foo/bar'),它将加载。我不确定为什么,因为文档显示

load_module(fullname)

Load the module specified by fullname. fullname must be the fully qualified (dotted) module name. It returns the imported module, or raises ZipImportError if it wasn’t found.