【问题标题】:python import module from parent packagepython从父包导入模块
【发布时间】:2012-12-24 09:01:44
【问题描述】:

我有以下目录结构

foo/
    __init__.py
    settings.py
    bar/
        __init__.py
        myfile.py

在 myfile.py 我有: 导入设置

我收到以下错误:ImportError: No module named settings,为什么?如何有效地从myfile.py 导入settings 文件

【问题讨论】:

    标签: python import module package parent


    【解决方案1】:

    来自http://docs.python.org/2/tutorial/modules.html#intra-package-references

    from .. import settings
    

    希望对你有帮助

    【讨论】:

    • 我试过了,但我得到 ValueError: Attempted relative import in non-package
    • @danielrvt:您是否将myfile.py 作为脚本运行? Python 并不真正支持包中的脚本(尽管它经常被请求)。在顶层创建一个导入 foo.bar.myfile 的帮助脚本,一切就绪。
    • 是的,我将它作为脚本运行,没有得到关于制作帮助脚本的部分
    • @danielrvt:将其放入 foo 父目录中的脚本中:from foo.bar.myfile import main; main()(setuptools 会根据 setup.py 中指定的入口点自动生成类似的脚本)
    • 谢谢@Blckknght。终于回答了我的问题!
    【解决方案2】:

    这是另一种看起来更清楚的方法:

    foo.__init__.py

      __all__ = ['settings', ..(all other modules at 'foo' level you want to show)...]
    

    myfile.py

    # instead of "from .. import..." 
      from foo import settings 
      print settings.theThing
    

    【讨论】:

      猜你喜欢
      • 2019-05-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-15
      • 2016-07-30
      • 2020-08-27
      • 1970-01-01
      • 2017-10-05
      相关资源
      最近更新 更多