简体   繁体   中英

Imported module fails to import sub-module

I have the following folder-structure

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

In cli_stats.py I have the following import:

from get_data.get_stats import SeasonStats

In get_stats.py I have the following import:

from api_scraper.api_scraper import Football .

When running python cli_stats.py from the cli_stats folder the following error occurs.

  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'

But when running python get_stats.py from the get_data folder, the import is successful. Why does the import not work when running cli_stats.py from the cli_stats folder?

You have to adjust the import to a relativ one. From the get_stats.py you have to step into the directory. The error is that from api_scraper.api_scraper import Football is an absolut import.

Try: in get_stats.py

from .api_scraper.api_scraper import Football

(1 dot before the api_scraper)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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