英文:
module import of same folder says not found when called from outside folder
问题
以下是翻译后的内容:
文件布局如下
.
├── modules/
│ ├── module1.py
│ └── module2.py
└── main.py
module2.py:
print('hello world')
module1.py:
import module2
运行 module1.py
时,输出如下
"hello world"
main.py:
from modules import module1
运行 main.py
时,输出如下:
Traceback (most recent call last):
File "C:\Users\demar\Desktop\A\main.py", line 1, in <module>
from modules import module1
File "C:\Users\demar\Desktop\A\modules\module1.py", line 1, in <module>
import module2
ModuleNotFoundError: No module named 'module2'
英文:
The file layout looks like this
.
├── modules/
│ ├── module1.py
│ └── module2.py
└── main.py
module2.py:
print('hello world')
module1.py:
import module2
when running module1.py
the output looks like this
"hello world"
main.py:
from modules import module1
when running main.py
the output looks like this:
Traceback (most recent call last):
File "C:\Users\demar\Desktop\A\main.py", line 1, in <module>
from modules import module1
File "C:\Users\demar\Desktop\A\modules\module1.py", line 1, in <module>
import module2
ModuleNotFoundError: No module named 'module2'
答案1
得分: 1
当你在main.py
所在的目录中时,Python会自动将此目录添加到sys.path
(这是Python查找模块和包的地方)。
因此,modules
(命名空间)包和main.py
对Python是可识别的。这就是为什么运行from modules import module1
部分时没有出现错误的原因,因为它们的目录位于sys.path
中。
错误出现在尝试执行module1
时,它看到了import module2
行。现在它不认识module2
。
如何修复?
-
你可以将
module2.py
的目录,即modules/
,添加到sys.path
中,或者通过PYTHONPATH
环境变量来实现。 -
你可以更改
module1.py
,像这样导入它:
from modules import module2
英文:
When you are in the directory of main.py
, Python automatically adds this directory to the sys.path
(this is where it looks for modules and packages).
So modules
(namespace) package and main.py
are recognizable for Python. That's why you didn't get any error running the from modules import module1
part. Again because their directory is in the sys.path
Error comes from when it tries to execute module1
, it sees import module2
line. Now it doesn't recognize module2
.
How to fix?
-
You could either add the directory of
module2.py
which ismodules/
to thesys.path
or viaPYTHONPATH
environment variable. -
You could change
module1.py
and import it like this:
from modules import module2
答案2
得分: 0
正确的 module1.py 代码:
from modules import module2
仅因为你从父文件夹运行 main.py。
英文:
Correct code for module1.py:
from modules import module2
just because you run main.py from parent folder
答案3
得分: 0
以下是您要翻译的内容:
在module1中,我发现如果我只是这样写:
try:
import module2
except Exception:
from . import module2
它可以从主程序正常工作,也可以从module1正常工作。
英文:
I found that if I just write
try:
import module2
except Exception:
from . import module2
in module1
it works from main and works from module1
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论