来自父包的python导入模块

dan*_*rvt 11 python import module parent package

我有以下目录结构

foo/
    __init__.py
    settings.py
    bar/
        __init__.py
        myfile.py
Run Code Online (Sandbox Code Playgroud)

在myfile.py我有:导入设置

我收到以下错误:ImportError: No module named settings为什么?我怎样才能有效地导入settings文件myfile.py

Adr*_*ián 18

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

from .. import settings
Run Code Online (Sandbox Code Playgroud)

希望能帮助到你

  • @danielrvt:你是在运行`myfile.py`作为脚本吗?Python中并不真正支持包中的脚本(尽管它经常被请求).在顶层创建一个帮助脚本,导入`foo.bar.myfile`,你将全部设置好. (14认同)
  • 我试过了,但我得到了 ValueError: Attempted relative import in non-package (2认同)

小智 6

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

foo.__init__.py

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

myfile.py

# instead of "from .. import..." 
  from foo import settings 
  print settings.theThing
Run Code Online (Sandbox Code Playgroud)