[英]What is the correct way to import this class?
I have the following repository structure:我有以下存储库结构:
directoryA
- moduleA.py (it contains MyClass class)
directoryB
- moduleB.py
In moduleB.py I need to import MyClass, I use the following command:在 moduleB.py 中我需要导入 MyClass,我使用以下命令:
from directoryA.moduleA import MyClass
When I run the main() function in moduleB.py I have the following error:当我在 moduleB.py 中运行 main() function 时,出现以下错误:
ModuleNotFoundError: No module named 'directoryA' ModuleNotFoundError:没有名为“directoryA”的模块
I run the moduleB.py from directoryB in the following way:我以下列方式从 directoryB 运行 moduleB.py:
py moduleB.py
How could I fix this problem?我该如何解决这个问题?
The best you can do to organizing your scripts would be using a file called main.py
in the main folder, which must be in the same directory as directoryA
and directoryB
.组织脚本的最佳方法是在主文件夹中使用名为main.py
的文件,该文件必须与directoryA
和directoryB
位于同一目录中。
In main.py
, just import the files from child directories:在main.py
中,只需从子目录导入文件:
from directoryA.moduleA import MyClass
import directoryB.moduleB
# Do whatever you want, but sometimes, just don't go too overboard.
The thing is moduleB.py searches for directoryA inside directoryB, which is the working directory.事情是 moduleB.py 在 directoryB 中搜索 directoryA,这是工作目录。 You can try using two dots to go up one hierarchy level:您可以尝试使用两个点将 go 向上一级:
from ..directoryA.moduleA import MyClass
or you can also try to append the path of the file for the import statement或者你也可以尝试append文件的路径为import语句
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.