[英]Python ModuleNotFoundError for my main package
This is a follow up question for a question I asked not long ago .这是我不久前问的一个问题的后续问题。 The answer is correct and works great, but when I tried to apply it to the main package it didn't work.
答案是正确的并且效果很好,但是当我尝试将它应用到主包时它不起作用。
Lets say I have the following files structure:假设我有以下文件结构:
a/
->b/
->c/
-> __init__.py
-> script1.py
-> script2.py
->d/
-> __init__.py
-> script3.py
(The __init__
files are just like in the answer I linked above). (
__init__
文件就像我上面链接的答案一样)。
And in script3.py
I import script1.py
like so: from bc import script1
.在
script3.py
我像这样导入script1.py
: from bc import script1
。
It works when I run it in Pycharm, but when I clone the repository in Colab (all this code is in a GitHub repository) I get the error: ModuleNotFoundError: No module named 'b'
当我在 Pycharm 中运行它时它可以工作,但是当我在 Colab 中克隆存储库(所有这些代码都在 GitHub 存储库中)时,我收到错误:
ModuleNotFoundError: No module named 'b'
Which makes sense because my package is not in the sys.path
variable.这是有道理的,因为我的包不在
sys.path
变量中。 And adding the folder a
to the sys.path
manually, after I cloned the repository, helps but it is not a real solution because I can't always do it (eg in unit-tests).在我克隆存储库后,手动将文件夹
a
添加到sys.path
帮助,但这不是一个真正的解决方案,因为我不能总是这样做(例如在单元测试中)。
So my question is, how can I fix it¿ Adding the __init__
file to folder b
didn't help.所以我的问题是,我该如何修复它?将
__init__
文件添加到文件夹b
没有帮助。
Notes:笔记:
a
is the project's folder, so it is not part of the path.a
是项目的文件夹,因此它不是路径的一部分。script3
like so from abd import script3
.script3
像现在这样from abd import script3
。 In this case I must specify folder a
because, again, b
is not in sys.path
.a
因为同样, b
不在sys.path
。You can backwardly add folder b
to your path and then import only from c
folder, like this:您可以向后添加文件夹
b
到您的路径,然后仅从c
文件夹导入,如下所示:
from os.path import realpath, dirname
import sys
sys.path.append(dirname(dirname(realpath(__file__))))
from c import script1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.