简体   繁体   English

无法在同一 package 中导入 Python 模块

[英]Cannot import Python module in same package

I have a Python 3.9.2 project with the following directory structure:我有一个 Python 3.9.2 项目,其目录结构如下:

lib/
├─ mod1.py
├─ mod2.py
├─ __init__.py
main.py

In /main.py , I have from lib import mod1 ./main.py中,我有from lib import mod1 In /lib/mod1.py , I have import mod2 ./lib/mod1.py中,我有import mod2 When I run /main.py , I receive the following error:当我运行/main.py时,我收到以下错误:

Traceback (most recent call last):
  File "/main.py", line 1, in <module>
    from lib import mod1
  File "/lib/init.py", line 1, in <module>
    import mod2
ModuleNotFoundError: No module named 'mod2'

Why is this happening?为什么会这样? When I change the code in /lib/mod1.py to say from lib import mod2 , the code works fine, but I don't understand why that fixes it.当我将/lib/mod1.py中的代码更改为from lib import mod2时,代码工作正常,但我不明白为什么会修复它。 Shouldn't I be able to import /lib/mod2.py the way I originally tried, since both mod1.py and mod2.py are in the same directory?我不应该能够以我最初尝试的方式导入/lib/mod2.py ,因为mod1.pymod2.py都在同一个目录中吗?

In /lib/mod1.py , you probably want to do:/lib/mod1.py中,您可能想要这样做:

# relative import - entire module
from . import mod2

# relative import - specific piece
from .mod2 import foo 

or或者

# absolute import - entire module
from lib import mod2

# absolute import - specific piece
from lib.mod2 import foo

The correct way to import things is really tricky in Python because it depends on where you run the script from.在 Python 中导入东西的正确方法非常棘手,因为它取决于您从哪里运行脚本。

  • If you run the code from the root directory, import mod2 causes problems, but如果从根目录运行代码, import mod2会出现问题,但是
  • If you were to run /lib/mod1.py (say it were run-able) from inside lib , then import mod2 would be correct and the alternatives above would cause errors.如果您要从lib内部运行/lib/mod1.py (说它是可运行的),那么import mod2将是正确的,并且上述替代方案会导致错误。

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

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