Python3从同胞目录中导入模块
对于 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 项目,并在顶部找到了模块引用的解决方案,但它对我不起作用。 我尝试了以下解决方案,但也不起作用:
- https: //www.geeksforgeeks.org/python-import-from-sibling-directory/?ref=lbp
- https://itsmycode.com/importerror-attempted-relative -import-with-no-known-parent-package/
- https://iq-inc.com/importerror-attempted-relative-import/
所以我的问题是,出现此错误:
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:
- https://www.geeksforgeeks.org/python-import-from-sibling-directory/?ref=lbp
- https://itsmycode.com/importerror-attempted-relative-import-with-no-known-parent-package/
- https://iq-inc.com/importerror-attempted-relative-import/
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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我发现我可以与sys.path.append&一起工作。 OS.Path.Abspath。因此,解决方案就是这样:
目录构造:
要使用folder1/a.py中的folder2/b.py中的testfunction。
I found out, that I could work with sys.path.append & os.path.abspath. So the solution is like this:
directory stucture:
To use testFunction from folder1/a.py in folder2/b.py the code in b.py should be like this: