Python 3中的相对导入不起作用 [英] Relative import in Python 3 is not working
问题描述
我有以下目录:
mydirectory
├── __init__.py
├── file1.py
└── file2.py
我在file1.py中定义了一个函数f.
I have a function f defined in file1.py.
如果在file2.py中,我愿意
If, in file2.py, I do
from .file1 import f
我收到以下错误:
SystemError:父模块"未加载,无法执行相对 导入
SystemError: Parent module '' not loaded, cannot perform relative import
为什么?以及如何使其工作?
Why? And how to make it work?
推荐答案
由于file1
和file2
位于同一目录中,因此您甚至不必具有__init__.py
文件.如果您要扩大规模,那么就把它留在那里.
since file1
and file2
are in the same directory, you don't even need to have an __init__.py
file. If you're going to be scaling up, then leave it there.
要在同一目录的文件中导入某些内容,只需这样做
To import something in a file in the same directory, just do like this
from file1 import f
即,您不需要执行相对路径.file1
,因为它们位于同一目录中.
i.e., you don't need to do the relative path .file1
because they are in the same directory.
如果将要运行整个应用程序的主要功能,脚本或任何其他工具位于另一个目录中,那么您将必须使所有内容都与正在执行的位置有关.
If your main function, script, or whatever, that will be running the whole application is in another directory, then you will have to make everything relative to wherever that is being executed.
这篇关于Python 3中的相对导入不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!