How to Import python package from another directory?

后端 未结 2 1721
灰色年华
灰色年华 2021-01-06 09:13

I have a project that is structured as follows:

project
├── api
│   ├── __init__.py
│   └── api.py
├── instance
│   ├── __init__.py
│   └── config.py
├── pac         


        
2条回答
  •  别那么骄傲
    2021-01-06 09:36

    In Python 3.3 onwards you don't need __init__.py files in your subdirectories for the purpose of imports. Having them can actually be misleading as it causes the creation of package namespaces in each folder containing an init file, as described here.

    By removing all those __init__.py files you will be able to import files in the namespace package (including subdirectories) when running app.py, but that's still not want we want.

    The Python interpreter still doesn't know how to reach your instance namespace. In order to do that you can use the PYTHONPATH environment variable, including a path that is parent to config.py. You can do that as suggested in @RMPR's answer with sys.path, or by directly setting the environment variable, for instance:

    PYTHONPATH=/home/csymvoul/projects/project python3 /home/csymvoul/projects/project/package/app.py
    

    Then importing the dependency like from instance import config.

提交回复
热议问题