python – zipimporter无法找到/加载子模块

我正在尝试从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 AM

以下是可行的,但这是问题的真正解决方案吗? zipimport.zipimporter文档明确声明“fullname必须是完全限定(虚线)模块名称.”并有一个似乎正常运行的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.

转载注明原文:python – zipimporter无法找到/加载子模块 - 代码日志