【问题标题】:cannot import name 'a' from 'tools'无法从“工具”导入名称“a”
【发布时间】:2021-06-12 08:07:01
【问题描述】:

我可以运行 test_pkg1.py 和 test_pkg2.py 但是当我运行 test.py test_pkg1.py 发生错误

发生异常:ImportError 无法从“工具”(未知位置)导入名称“a”

root
├─ pkg1
│  ├─ tools
│  │  ├─ __init__.py
│  │  └─ a.py
│  ├─ __init__.py.py
│  └─ test_pkg1.py
├─ pkg2
│  ├─ tools
│  │  ├─ __init__.py
│  │  └─ b.py
│  ├─ __init__.py.py
│  └─ test_pkg2.py
├─ test.py
└─ d.py

test_pkg1.py 
   from tools import a  

test_pkg2.py
   from tools import b  

test.py 
   from pkg2 import test_pkg2
   from pkg1 import test_pkg1

【问题讨论】:

  • 这可能是因为您在test.py 所在的目录下没有__init__.py 文件

标签: python python-3.x import


【解决方案1】:

在 Python 中,导入路径总是相对于执行主程序的目录,除非您通过在包名称前加一个点来显式使用 relative import,这会使解释器在同一目录中查找包作为进行导入的模块:

test_pkg1.py:

from .tools import a

您还需要在主程序运行的目录中创建一个__init__.py 文件,以便将该目录视为可以进行相对导入的包。

【讨论】:

  • 但是当我用点导入时,运行 test_pgk1.py 时出现错误。发生异常:ImportError 尝试使用没有已知父包的相对导入
  • 我明白了。您还需要在主目录中创建一个__init__.py 文件。我已经相应地更新了我的答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-14
  • 2021-02-27
  • 2020-09-22
  • 2021-12-04
  • 2021-05-30
相关资源
最近更新 更多