Welcome to JiKe DevOps Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
407 views
in Technique[技术] by (71.8m points)

Python trying to import a folder as a module

I am having an odd error whereby when I try to import a class, from a file that is within a subfolder, I get a ModuleNotFoundError:

from petri.strategyport.strategy import Strategy
ModuleNotFoundError: No module named 'petri.strategyport'

The strategyport folder does not contain an __init__.py, and I am using python 3.8. Additionally, the petri module works in other contexts (when I get an error, I am trying to run it from a NixOS shell). The sys.path has the root folder for the petri module in it. Could anyone give me a lead as to what might be going wrong here? It seems quite mysterious.

Thanks in advance for any help, and also after the event.

EDIT: the file structure here looks like this:

petri/
    __init__.py
    /strategyport/
        strategy.py

Where __init__.py has from petri.strategyport.strategy import Strategy

A FURTHER EDIT: There are actually a number of other imports done within this package, eg from petri.asset import Asset, etcetera. All the single-level (ie, they are at the root directory level, not within their own sub-folder) ones work, whereas none of the multi-level ones do. So there seems to be some fundamental issue here with python mistaking sub-folders for modules. Switching the import syntax from from petri.xxxx.yyyy import zzzz to from xxxx.yyyy import zzzz makes no difference.

question from:https://stackoverflow.com/questions/65932828/python-trying-to-import-a-folder-as-a-module

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

Please log in or register to answer this question.

Welcome to JiKe DevOps Community for programmer and developer-Open, Learning and Share

755k questions

754k answers

5 comments

53.3k users

...