【问题标题】:Import from outer dir in python从python中的外部目录导入
【发布时间】:2021-02-16 15:25:44
【问题描述】:

我有这样的私有 python 项目:

application
├── src
│   └── test_import.py
│   └── __init__.py
|   
└── config
    └── conf.py
    └── __init__.py

test_import.py 内容:


if __name__ == '__main__':

    from config import conf

当我运行test_import 时出现以下错误:

ModuleNotFoundError: No module named 'config'

我在 github 上看到一些包在文件名前使用点来进行导入,如下所示:

from .foo import bar

这似乎是在 python 中相对导入的一种更 Pythonic 的方法(我真的很新)而且因为我不认为使用 sys.append('../') 是一种 Pythonic 方法,所以我想知道我应该对我的项目结构,以便进行上述“”“pythonic import”“”?

【问题讨论】:

    标签: python import python-import


    【解决方案1】:

    您可以将您的conf.py 导入到您的test_import.py 文件中

    # test_import.py file
    import sys
    from os.path import dirname, join, abspath
    
    sys.path.insert(0, abspath(join(dirname(__file__), "..")))
    
    # now you can do
    from config import conf
    
    ....
    

    【讨论】:

      猜你喜欢
      • 2020-02-27
      • 2021-03-07
      • 2020-12-06
      • 1970-01-01
      • 2017-06-26
      • 1970-01-01
      • 2013-11-09
      • 2018-11-06
      • 1970-01-01
      相关资源
      最近更新 更多