How to have multi-directory or multi-package python project?

人走茶凉 提交于 2019-12-24 18:42:44

问题


I have project structure like this:

package1/__init__.py
package1/file1.py
package1/file2.py

package2/__init__.py
package2/file1.py
package2/file2.py

__init__.py
script1.py
script2.py

Unfortunately, I found that I can run code only from root directory, for example, from script1.py. If I run say from pakage2/file2.py, all links between files are lost, i.e. all imports of package1 from package2 becomes not found.

What is the correct directory structure in Python, which constraints package structure over all directories?


回答1:


You either need both package1 and package2 to be inside a package, in which case they can both import from each other:

root_package/
    __init__.py
    package1/
    package2/

Or add the packages to your PYTHONPATH, in which case any python script on your system can import from them:

export PYTHONPATH="$PYTHONPATH:/path/to/package1:/path/to/package2"

Update: you cannot import as part of a package if you are running the scripts directly. What you should do is define classes and functions in your packages as desired, then import them from another script:

root_package/
    __init__.py
    my_script.py
    package1/
    package2/

script.py:

from package1 import ...
from package2 import ...


来源:https://stackoverflow.com/questions/46215769/how-to-have-multi-directory-or-multi-package-python-project

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