简体   繁体   English

Python 导入:从库模块导入时找不到模块

[英]Python Importing: Module not found when importing from library modules

I am working in python and have a project with a lib folder containing lots of modules.我在 python 工作,并且有一个项目,其中包含许多模块的 lib 文件夹。 Many of those modules call other modules within the lib folder but never in a circular fashion.其中许多模块调用 lib 文件夹中的其他模块,但从不以循环方式调用。 Unfortunately, when I call from my project directory, I get a module not found error for these imports.不幸的是,当我从我的项目目录调用时,我收到这些导入的模块未找到错误。 For example, lets consider this file structure例如,让我们考虑这个文件结构

project
|---lib
|    |   __init__.py
|    |   moduleA.py
|    |   moduleB.py
|    |   moduleC.py
|    |   ...
|
|    file.py

Now I want to run file.py.现在我想运行file.py。 And file.py looks like this file.py 看起来像这样

from lib import moduleA
...

if __name__ == "__main__":
   moduleA.foo()
   ...

And module A needs moduleB and moduleC to work, so it starts like this而模块A需要模块B和模块C才能工作,所以开始是这样的

from moduleB import *
from moduleC import *
...

If I run moduleA's functions from within lib, everything works fine.如果我从 lib 中运行 moduleA 的函数,一切正常。 But if I try to run file.py, I get the error ModuleNotFoundError: No module named 'moduleB'.但是如果我尝试运行 file.py,我会收到错误 ModuleNotFoundError: No module named 'moduleB'。 What am I doing wrong?我究竟做错了什么? Why can't the system recognize modules B and C?为什么系统无法识别模块 B 和 C? What do I have to do to maintain this neat project structure and get file.py to run?我必须做些什么来维护这个整洁的项目结构并让 file.py 运行?

Explanation解释

In Python, the import paths of children scripts must be relative to the location of the main script. Python中,子脚本的导入路径必须相对于主脚本的位置。

Solution解决方案

Instead of:代替:

from moduleB import *
from moduleC import *

Try writing:试着写:

from lib.moduleB import *
from lib.moduleC import *

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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