How to import a module from a different folder?

后端 未结 2 1144
走了就别回头了
走了就别回头了 2020-12-14 15:52

I have a project which I want to structure like this:

myproject
  __init__.py
  api
    __init__.py
    api.py
  backend
    __init__.py
    backend.py
  mod         


        
2条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-14 16:32

    Firstly, this import statement:

    from models import some_model
    

    should be namespaced:

    # in myproject/backend/backend.py or myproject/api/api.py
    from myproject.models import some_model
    

    Then you will need to get the directory which contains myproject, let's call this /path/to/parent, into the sys.path list. You can do this temporarily by setting an environment variable:

    export PYTHONPATH=/path/to/parent
    

    Or, preferably, you can do it by writing a setup.py file and installing your package. Follow the PyPA packaging guide. After you have written your setup.py file, from within the same directory, execute this to setup the correct entries in sys.path:

    pip install --editable .
    

提交回复
热议问题