且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Python导入模块,文件夹结构

更新时间:2022-12-08 13:28:34

您所使用的结构不是我推荐的结构,但对于Python项目通常的结构,我是一个比较新手.我相信这会满足您的要求:

The structure you're using is not one I would recommend, but I'm a comparaitive newb to how Python projects are usually structured. I believe this will do what you're after:

1)将__init__.py文件放在/project/project/src/project/test内,以确保将它们视为软件包.

1) Place an __init__.py file inside /project, /project/src, and /project/test to make sure they're treated as packages.

2)将from __future__ import absolute_import放在每个Python文件的顶部.

2) Place from __future__ import absolute_import at the top of each Python file.

3)然后使用相对导入:

3) Then use relative imports:

test.py:

from ..src import models

main.py:

from .src import models

4)您需要以其他方式启动应用程序.确保当前目录是/project(似乎是文件系统根目录)的父目录,并以这种方式运行项目:

4) You'll need to start your application differently. Ensure your current directory is the parent of /project (which appears to be the file system root) and run your project this way:

python -m project.main

对于我自己的项目,如果它是应用程序的起点,那么我肯定会将main.py放在src中.我也可以将tests.py放在src中,但是如果没有,我可以在命令行上而不是在代码中将/project/src添加到测试运行器的Python路径中.

For my own project, I would definitely put main.py inside src if it's the start point of your application. I might put tests.py in src, too, but if not, I would add /project/src to the test runner's Python path on the command line instead of in code.

无论如何,我仍然会使用absolute_import.以我的经验,这是一个非常干净的模块组织解决方案,也是默认情况下Python 3中的工作方式.

I would still use absolute_import regardless. In my experience, it's a very clean solution to module organization, and it's also how things work by default in Python 3.