Python 导入具有不同的目录结构
我正在开发一个 项目,其中源树中的所有代码都分为模块目录,例如:
modules/check/lib/check.py
modules/edit/lib/edit.py
在安装过程中,Python 文件被放置在 Python 的 site-packages
下的同一目录 program_name
中。因此,所有模块都使用语法import program_name.edit
。
由于目录和导入结构的原因,源模块无法相互导入,因此每次要运行源树中的任何内容时都必须安装它们。
因此,我的问题是:在不修改目录结构的情况下,如何确保 modules/check/lib/check.py
从 modules/edit/lib/edit.py
导入> 并且 site-packages/program_name/check.py
从 site-packages/program_name/edit.py
导入?对于可能的重组,在这样的环境中目录结构和导入的最佳实践是什么?
I'm working on a project where all the code in the source tree is separated into module directories, e.g.:
modules/check/lib/check.py
modules/edit/lib/edit.py
During installation, the Python files are put in the same directory program_name
under Python's site-packages
. All the modules therefore use the syntax import program_name.edit
.
Because of the directory and import structure, the source modules are unable to import each other, so you'd have to install them each time you want to run anything in the source tree.
My questions are therefore: Without modifying the directory structure, how can I make sure that modules/check/lib/check.py
imports from modules/edit/lib/edit.py
and that site-packages/program_name/check.py
imports from site-packages/program_name/edit.py
? And for a possible reorganization, what are best practices for the directory structure and imports in an environment like this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您只需将
/modules/
目录添加到开发环境中的 PYTHONPATH 中即可。一旦安装在站点包中,在 check.py 中调用import edit
将导入正确的模块,因为它们位于同一目录中。从您的开发环境中调用import edit
将导入您添加到 PYTHONPATH 中的内容You can just add the
/modules/
directories to your PYTHONPATH in your dev environment. Once installed in site-packages, callingimport edit
inside check.py will import the correct module since they are in the same directory. Callingimport edit
from your dev environ will import the one you added to your PYTHONPATH为什么不在开发机器上的
prog_name
下安装符号链接?Why don't you install symlinks underneath
prog_name
on your dev machine?