导入模块导入子模块失败

Imported module fails to import sub-module

我有以下文件夹结构

premier_league/
 |_cli_stats/
    |__ __init__.py
    |__cli_stats.py
    |__get_data/
         |__get_stats.py
         |__get_id.py
         |__api_scraper/
              |__api_scraper.py

cli_stats.py 我有以下导入:

from get_data.get_stats import SeasonStats

get_stats.py 我有以下导入:

from api_scraper.api_scraper import Football.

当 运行 python cli_stats.py 来自 cli_stats 文件夹时,出现以下错误。

  File "cli_stats.py", line 36, in <module>
    from get_data.get_stats import SeasonStats
  File "/Users/name/Desktop/Projekt/premier_league_api/cli_stats/get_data/get_stats.py", line 12, in <module>
    from api_scraper.api_scraper import Football
ModuleNotFoundError: No module named 'api_scraper'

但是从get_data文件夹中运行python get_stats.py时,导入成功。为什么当 运行 cli_stats.py 来自 cli_stats 文件夹时导入不起作用?

您必须将导入调整为相对导入。从get_stats.py你必须进入目录。错误是 from api_scraper.api_scraper import Football 是绝对导入。

尝试:在get_stats.py

from .api_scraper.api_scraper import Football

(api_scraper 前 1 点)