[英]Python: How to import package from subdirectory
I have the following project structure:我有以下项目结构:
Project/
|-- src/
| |-- package/
| |-- __init__.py
| |-- a.py
| |-- b.py
|
|-- tests/
|-- test_a.py
My __init__.py
file looks like this我的
__init__.py
文件看起来像这样
from .a import some_function
from .b import SOME_CONSTANT
But now I want to run the following code in test_a.py
:但现在我想在
test_a.py
中运行以下代码:
import package
package.some_function()
As long as it is located in the src/
directory, everything works fine, I can access all imports defined in my package.只要它位于
src/
目录中,一切正常,我可以访问 package 中定义的所有导入。 But I want it to be in the tests/
directory.但我希望它位于
tests/
目录中。
When looking at the flask repo I found that thex do it like that.在查看flask 存储库时,我发现他们就是这样做的。 For example, flasks test_appctx.py does exactly that:
例如, flasks test_appctx.py 就是这样做的:
import flask
flask.do_something()
How can I achieve this in my project as well?我怎样才能在我的项目中实现这一点?
You should add src/
to the folders where to look for the functions:您应该将
src/
添加到查找函数的文件夹中:
import sys
sys.path.append('../src')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.