Can't access top level python package from sub packages

北城以北 提交于 2021-01-29 12:33:19

问题


I have a directory structure like below:

chatbot/
    __init__.py
    utils/
    __init__.py
    parser.py
    nlu/
        __init__.py
        training/
                __init__.py
                module.py

I want to access parser.py from module.py. I tried using this line from module.py:

from chatbot.utils import parser

And I got this error:

ModuleNotFoundError: No module named 'chatbot'

Any pointers to what I am doing wrong? I am using python3 and trying to run the script as python3 nlu/training/module.py. Thanks in advance!


回答1:


I believe the right way of solving such problems is:

  • figure out what your top-level packages and modules are and in what directory they are
  • change to that directory
  • make all your imports absolute, i.e. always start with a top-level module or package (instead of things like from . import blah)
  • use the executable module (python -m) way of running your code, for example path/to/pythonX.Y -m top_level_package.executable_module (instead of path/to/pythonX.Y top_level_package/executable_module.py)

In case the top-level modules or packages are not all in the same directory:

  • Either work on packaging your libraries or applications correctly and install them in the site packages (eventually as editable, also known as develop mode).
  • Or, as a last resort, collect the other directories containing the top-level packages and modules in the PYTHONPATH environment variable like the following:
    • PYTHONPATH=path/to/alpha:path/to/bravo path/to/pythonX.Y -m top_level_package.executable_module



回答2:


I was able to solve the issue by adding the parent directory of chatbot package to sys.path.

Say if chatbot python package is in /home/my_project/chatbot/, I added a statement like:

sys.path.append('/home/my_project') in module.py

This made all top-level python packages visible to all lower-level python packages.



来源:https://stackoverflow.com/questions/61065184/cant-access-top-level-python-package-from-sub-packages

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