Python3从同胞目录中导入模块

发布于 2025-01-19 02:37:35 字数 1457 浏览 2 评论 0原文

对于 python 3.10 项目中的新结构,我必须将不同的模块彼此分开,并将它们移动到同一层的不同文件夹中。文件夹结构看起来有点类似于:

Root
-- main.py
-- __init__.py

-- folder1
----- __init__.py
----- a.py

-- folder2
----- __init__.py
----- b.py

我在 a.py 中定义了一个函数,如下所示:

# /root/folder1/a.py
def testFunction(text):
    print(text)

在根初始化文件中,我像这样引用了这个函数:

# /root/__init__.py
from .folder1.a import testFunction as testFunction

所以我尝试在模块folder2/中的模块folder1/a.py中使用该函数b.py:

# /root/folder2/b.py
from .. import testFunction
text = 'hello World'
testFunction(text)

我在 GitHub 上搜索了一个更大的 python 项目,并在顶部找到了模块引用的解决方案,但它对我不起作用。 我尝试了以下解决方案,但也不起作用:

所以我的问题是,出现此错误:

ImportError: attempted relative import with no known parent package

非常感谢您的每一个提示或解决方案:-)

For a new structure in the python 3.10 project I had to separate diffrent modules from each other and moved them in diffrent folders on the same layer. The folder stucture looks kinda similar to this:

Root
-- main.py
-- __init__.py

-- folder1
----- __init__.py
----- a.py

-- folder2
----- __init__.py
----- b.py

I defined a function in a.py like this:

# /root/folder1/a.py
def testFunction(text):
    print(text)

In the Root init file i referenced this function like so:

# /root/__init__.py
from .folder1.a import testFunction as testFunction

So I tried to use the function in module folder1/a.py in module folder2/b.py:

# /root/folder2/b.py
from .. import testFunction
text = 'hello World'
testFunction(text)

I searched on GitHub for a bigger python projects and found the solution on top for module references but it didn't worked for me.
I tried following solutions which also didn't worked:

So my problem is, that this Error shows up:

ImportError: attempted relative import with no known parent package

thank you verry much for every hint or solution :-)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

暮年 2025-01-26 02:37:35

我发现我可以与sys.path.append&一起工作。 OS.Path.Abs​​path。因此,解决方案就是这样:

目录构造:

Root
-- main.py
-- __init__.py

-- folder1
----- __init__.py
----- a.py

-- folder2
----- __init__.py
----- b.py

要使用folder1/a.py中的folder2/b.py中的testfunction。

import sys
import os

sys.path.append(os.path.abspath('../Root/folder1'))
from a import testFunction

I found out, that I could work with sys.path.append & os.path.abspath. So the solution is like this:

directory stucture:

Root
-- main.py
-- __init__.py

-- folder1
----- __init__.py
----- a.py

-- folder2
----- __init__.py
----- b.py

To use testFunction from folder1/a.py in folder2/b.py the code in b.py should be like this:

import sys
import os

sys.path.append(os.path.abspath('../Root/folder1'))
from a import testFunction
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文