问题描述
我一直在寻找解决这个问题的方法.
I have been looking for a way to solve this.
我有一个python项目,这是我想要的文件夹结构:
I have a python project, and this is the folder structure I want:
/project/main.py
/project/src/models.py
/project/test/tests.py
我希望能够通过在终端中执行 tests.py 来运行测试. tests.py在/project/src/中导入模块以进行测试.首先我通过添加解决 tests.py中的sys.path.insert(0, '..')
.但是,然后 models.py 中用于打开文本文件的路径必须相对于 tests.py 等.这意味着该程序从以下位置执行后将无法运行 main.py ,原因.
I want to be able to run the tests by executing the tests.py in terminal. tests.py imports modules in /project/src/ for testing. First I solved this by adding sys.path.insert(0, '..')
in tests.py. But then the paths used in models.py for opening text files had to be relative to the tests.py, etc. Which means the program wouldn't run when excecuted from main.py, cause of the paths.
在将模块导入到tests.py中时,我也尝试过使用点,例如from ..src.models import *
,但这给出了错误消息尝试在非软件包中进行相对导入".
I also tried with dots when importing modules into tests.py, like from ..src.models import *
, but that gave error message saying "Attempted relative import in non-package".
我应该在tests.py的顶部放置什么以便能够从models.py导入模块?
What should I put in the top of tests.py to be able to import the modules from models.py?
推荐答案
您所使用的结构不是我推荐的结构,但对于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.
这篇关于Python导入模块,文件夹结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!