[英]Importing from one sub-module into another sub-module
I'm struggling with python's imports. 我正在努力与python的导入。
I have my repository for my python projects in which I have a collection of more or less independent programmes and tools. 我有我的python项目的存储库,其中有或多或少的独立程序和工具的集合。 There are a few sub-folders which contain the single scripts and programmes;
有几个子文件夹包含单个脚本和程序。 some can be used as helper routines for others scripts as well.
有些也可以用作其他脚本的帮助程序。 Assume that my folder structure looks like:
假设我的文件夹结构如下所示:
root
__init__.py
prog1.py
prog2.py
imaging
__init__.py
filter1.py
detect_edges.py
data_tools
__init__.py
floating_mean.py
unify_data_sources.py
prog3.py
Now assume that I want to use prog3.py
directly but need call filter1.py
. 现在假设我想直接使用
prog3.py
,但需要调用filter1.py
。 How can I import it into prog3.py
? 如何将其导入
prog3.py
?
The only way I managed to import it was giving adding to the path which needs modification of sys.path
. 我设法导入它的唯一方法是添加需要修改
sys.path
的路径。
import sys
sys.path.append("../imaging/")
from filter1 import filter1
As I know the relative way the modules are located, is there another way similar to what is described in python's module import guide ( here and here ) without changing sys.path? 据我所知,模块的相对放置方式,是否还有另一种与python的模块导入指南( 此处和此处 )中描述的方式类似的方式,而无需更改sys.path?
Assuming you need to call filter1.py for importing shared functions or classes, I would use relative imports as described in the python tutorial. 假设您需要调用filter1.py导入共享函数或类,我将使用python教程中所述的相对导入。
filter1.py filter1.py
def some_shared_func1():
pass
def some_shared_func2():
pass
prog3.py prog3.py
from ..imaging.filter1 import some_shared_func1, some_shared_func2
# filter1 is reached from prog3 by go two levels up then one level down to `imaging` folder.
if __name__ == "__main__":
# Do something with some_shared_func1
# Do something with some_shared_func2
pass
I would then run prog3.py with -m
argument to resolve relative imports but without extension: 然后,我将使用带有
-m
参数的prog3.py来解析相对导入,但不进行扩展:
python -m root.data_tools.prog3
Current directory must be the one containing root
(or be defined into PYTHONPATH variable). 当前目录必须是包含
root
(或定义为PYTHONPATH变量)。
I don't modify sys.path
. 我不修改
sys.path
。
Is that what you are looking for? 那是您要找的东西吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.