[英]ImportError with absolute and relative imports
Having trouble importing with a very simple file structure.使用非常简单的文件结构导入时遇到问题。
My file structure looks like this:我的文件结构如下所示:
project/
...
project.py
helper.py
__init__.py
...
Within project.py is the class I am trying to import in helper在 project.py 中是 class 我试图在助手中导入
#project.py
class MyAPIOne():
...
class MyAPITwo():
...
#helper.py
import MyAPIOne
if __name__ == "__main__":
api = MyApiOne()
...
When running with python3 helper.py
:使用
python3 helper.py
运行时:
If I keep the absolute import import MyAPIOne
I recieve ModuleNotFoundError: No module named 'MyAPIOne'
如果我保留绝对导入
import MyAPIOne
我收到ModuleNotFoundError: No module named 'MyAPIOne'
If I change it to a relative import from. import MyAPIOne
如果我将其更改为相对导入
from. import MyAPIOne
from. import MyAPIOne
I receive ImportError: cannot import name 'MyAPIOne'
from. import MyAPIOne
我收到ImportError: cannot import name 'MyAPIOne'
I have also experimented with appended to sys.path
various directories, with no luck.我还尝试将各种目录附加到
sys.path
中,但没有成功。
If you are running this script from the project
folder, you can alter your import the following way: from project import MyAPIOne
.如果您从
project
文件夹运行此脚本,则可以通过以下方式更改导入: from project import MyAPIOne
。 Also, you can add this folder to your PYTHONPATH
env variable.此外,您可以将此文件夹添加到
PYTHONPATH
环境变量中。
Upd: to add some folder to PYTHONPATH you can ran更新:要向 PYTHONPATH 添加一些文件夹,您可以运行
export PYTHONPATH="${PYTHONPATH}:/my/other/path"
main file can import all the files, but main file can't be imported by other files.主文件可以导入所有文件,但主文件不能被其他文件导入。
once file mentioned with __name__ = "__main__" , then it becomes main file.一旦用__name__ = "__main__"提到文件,它就会成为主文件。 so helper.py is acts as main file.
所以 helper.py 作为主文件。 it can't be imported.
它不能被导入。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.