【问题标题】:importing from source results in parent module not found while handling absolute import从源导入导致在处理绝对导入时找不到父模块
【发布时间】:2018-12-12 02:02:07
【问题描述】:

我有以下文件夹结构;

app/
ext/
  gredis/
    gredis.py

我在/Users/blah/blah/blah/ext/gredis/gredis.py中有gredis.py的完整路径

但是,当我尝试通过使用导入ext.gredis.gredis 模块时;

imp.load_source('ext.gredis.gredis', path)

我有以下错误;

RuntimeWarning: Parent module 'ext.gredis' not found while handling absolute import

我需要先导入 ext.gredis 吗?

注意:所有文件夹都有__init__.py

【问题讨论】:

    标签: python


    【解决方案1】:

    你能发布重现错误的代码吗?这对我有用:

    $ tree
    .
    +-- app
    ¦   +-- test.py
    +-- ext
    ¦   +-- gredis
    ¦   ¦   +-- gredis.py
    ¦   ¦   +-- gredis.pyc
    ¦   +-- test.py
    +-- test.py
    
    $ for path in test.py app/test.py ext/test.py; do python $path; done;
    <module 'ext.gredis.gredis' from '/tmp/bla/ext/gredis/gredis.pyc'>
    <module 'ext.gredis.gredis' from '/tmp/bla/ext/gredis/gredis.pyc'>
    <module 'ext.gredis.gredis' from '/tmp/bla/ext/gredis/gredis.pyc'>
    

    而 test.py 包含:

    import imp
    print(imp.load_source('ext.gredis.gredis', '/tmp/bla/ext/gredis/gredis.py'))
    

    这适用于 python 2.x 和 3.x。

    【讨论】:

      【解决方案2】:

      我发现的解决方案是确保 imp.load_source 的第一个参数(即您的模块的名称)不包含句点。不知道为什么这很重要,但希望它可以帮助某人

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2022-07-15
        • 2014-05-02
        • 1970-01-01
        • 2020-05-06
        • 2013-10-06
        • 1970-01-01
        • 2011-01-17
        相关资源
        最近更新 更多