简体   繁体   English

Python:如何从子目录导入 package

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM