简体   繁体   中英

How to add modules from external directories in Python

I know this must be fairly easy but I cannot make it work for my case. I have the following structure:

project_root
    __init__.py
    backend
        __init__.py
        application
            __init__.py
            admin
                __init__.py
                models
    scheduling
        __init__.py
        my_script.py

I want to load some objects from __init.py__ file under application as well as some other objects from models.py file under application.admin .

How to do that without using sys.path or similar technique?

You can set the environment variable PYTHONPATH to the root directory of your project. Python will look for modules there.

It depends on your entry point.

If I am reading your question correctly, you would like to access objects in application/__init__.py from code within admin/models.py?

If your entry point is __init__.py in the project_root folder ie.

user@host:/$python project_root/__init__.py

Then from within your models.py code you can simply write:

from backend.application import myobject

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM