Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
422 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 reply this article.

OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...