Python: Import file in grandparent directory

北城以北 提交于 2020-01-02 03:40:12

问题


Hierarchy:

scripts/
    web/
        script1.py
    tests/
        script2.py
common/
    utils.py

How would I import utils in script1 and script2, and still be able to run those scripts seperately (i.e., python script1.py). Where would I place the __init__.py files, and is that the correct way to go about this? Thank you!


回答1:


package/
    __init__.py
    scripts/
        web/
            __init__.py
            script1.py
        tests/
            __init__.py
            script2.py
    common/
        __init__.py
        utils.py

I've added a bunch of empty __init__.py files to your package. Now you have 2 choices, you can use an absolute import:

 from package.common import utils

or equivalently:

 import package.common.utils as utils

The downside here is that package must somehow be on PYTHONPATH. The other option is to use relative imports:

from ....common import utils

I would generally discourage this approach... It just gets too hard to tell where things are coming from (is that 4 periods or 6?).



来源:https://stackoverflow.com/questions/17730135/python-import-file-in-grandparent-directory

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