简体   繁体   English

从python3.10中的同级目录导入模块

[英]import module from a sibling directory in python3.10

There are 10+ SO posts about this already, none of the answers works for me and I still haven't seen an example of someone importing something from a sibling directory.已经有 10 多篇关于此的帖子,没有一个答案对我有用,而且我还没有看到有人从同级目录导入某些内容的示例。

src
    __init__.py
    test.py
    package1
        __init__.py
        module1.py
    package2
        __init__.py
        module2.py

(_ init _.py should not be necessary on python versions greater than 3.3 but I still have them there as they make no difference) (_ init _.py 在大于 3.3 的 python 版本上不需要,但我仍然有它们,因为它们没有区别)

in test.py I have在 test.py 我有

import package1.module2

and it works fine however the problem is when I want to import something from package2 to package1, and vice versa.它工作正常但是问题是当我想从package2导入一些东西到package1,反之亦然。 I have tried different import methods in module2.py and I receive these different error messages:我在 module2.py 中尝试了不同的导入方法,并且收到了这些不同的错误消息:

import src.package1.module1.py

with the error:出现错误:

ModuleNotFoundError: No module named 'src'

and

from .. import package1

with the error:出现错误:

ImportError: attempted relative import with no known parent package

The top answer here: How do I import a Python script from a sibling directory?这里的最佳答案是: 如何从同级目录导入 Python 脚本? also give me the exact error message as I showed above.还给我上面显示的确切错误消息。 The answers here: How to import a Python module from a sibling folder?这里的答案: 如何从同级文件夹中导入 Python 模块? changes nothing.什么都没有改变。 Am I missing something or should it not be possible to import stuff between different folders/packages?我是否遗漏了某些东西,或者不能在不同的文件夹/包之间导入东西? Do I need the "sys.path hack"?我需要“sys.path hack”吗?

I gave almost all of the solutions given for similar questions, but none of them worked for me, However, after banging my head to the wall, I found out that this solution does work by just removing one dot :我给出了针对类似问题的几乎所有解决方案,但没有一个对我有用,但是,在我把头撞到墙上之后,我发现这个解决方案只需删除一个点就可以工作:

import sys
sys.path.append('..')

Just remove one dot from string within append method, ie:只需从 append 方法中的字符串中删除一个点,即:

sys.path.append('.')

or your can use:或者您可以使用:

sys.path.insert(0, '.')

Then you can import any module from a sibling folder.然后您可以从同级文件夹中导入任何模块。 I tried this using python 3.9.13 and it worked well.我使用 python 3.9.13 进行了尝试,效果很好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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