Python accessing modules from package that is distributed over different directories

后端 未结 4 506
说谎
说谎 2021-01-19 17:29

I have a question regarding one single module that is distributed over multiple directories.

Let\'s say I have these two file and directories:

~/lib/         


        
4条回答
  •  醉话见心
    2021-01-19 18:19

    This is an adaptation of an answer to a similar question.

    Following up on @Gary's answer, the PEP 420 page says to use the following code on shared __init__.py packages.

    __init__.py:

    from pkgutil import extend_path
    __path__ = extend_path(__path__, __name__)
    

    This code should be placed inside the xxx directory's __init__.py. See the *s below

    someroot/
    ├── graphics
    │   └── python
    │       └── xxx
    │           ├── ****__init__.py****
    │           └── misc
    │               ├── __init__.py
    │               ├── module3.py
    │               └── module4.py
    └── lib
        └── python
            └── xxx
                ├── ****__init__.py****
                └── util
                    ├── __init__.py
                    ├── module1.py
                    └── module2.py
    

    Some setup.sh file to add to the Python Path:

    libPath=someroot/lib/python/
    graphicsPath=someroot/graphics/python/
    export PYTHONPATH=$PYTHONPATH:$libPath:$graphicsPath
    

    Python test code (tested on Python versions 2.7.14 and 3.6.4 using pyenv):

    import xxx.util.module1
    import xxx.misc.module3 # No errors
    

提交回复
热议问题