Unable to import module from another package

穿精又带淫゛_ 提交于 2019-12-11 10:39:34

问题


I have a directory structure like this

conf
    __init__.py
    settings.py
    abc.conf
    def.conf
src
    main.py
    xyz.py

src I chose not to make a package but a regular folder. I am trying to import the settings.py file in the main.py and executing the whole thing with the command python3 main.py

My import statement in main.py : import conf.settings

The error I'm getting is No module named conf.settings and I can't get my head around it.

Is python failing to recognize conf as a package? Can packages contain files other than .py files (.conf files in my case)


回答1:


When importing python search current directory and the sys.path. Since your main.py is in src folder it cannot see the conf package folder. Luckily you could update sys.path at runtime.

root
     conf
        __init__.py
        settings.py
     src
        main.py

So you could append sys.path from main.py before importing conf module. Try following:

# main.py
import os, sys
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))

from conf import settings
...

The other way is to update PYTHONPATH directly and add path to your script root directory.



来源:https://stackoverflow.com/questions/54604493/unable-to-import-module-from-another-package

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!