Python 导入具有不同的目录结构

发布于 2024-08-21 16:27:42 字数 655 浏览 4 评论 0原文

我正在开发一个 项目,其中源树中的所有代码都分为模块目录,例如:

modules/check/lib/check.py
modules/edit/lib/edit.py

在安装过程中,Python 文件被放置在 Python 的 site-packages 下的同一目录 program_name 中。因此,所有模块都使用语法import program_name.edit

由于目录和导入结构的原因,源模块无法相互导入,因此每次要运行源树中的任何内容时都必须安装它们。

因此,我的问题是:在不修改目录结构的情况下,如何确保 modules/check/lib/check.pymodules/edit/lib/edit.py 导入> 并且 site-packages/program_name/check.pysite-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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

坦然微笑 2024-08-28 16:27:42

您只需将 /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, calling import edit inside check.py will import the correct module since they are in the same directory. Calling import edit from your dev environ will import the one you added to your PYTHONPATH

等数载,海棠开 2024-08-28 16:27:42

为什么不在开发机器上的 prog_name 下安装符号链接?

Why don't you install symlinks underneath prog_name on your dev machine?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文