[英]ImportError: attempted relative import with no known parent package :(
I'm attempting to import a script from my Items file but I keeps on getting an error我正在尝试从我的 Items 文件中导入脚本,但我不断收到错误消息
from .Items.Quest1_items import *
gives给
from .Items.Quest1_items import *
ImportError: attempted relative import with no known parent package
Process finished with exit code 1
Here my project tree, I'm running the script from the main.py file这是我的项目树,我正在从 main.py 文件运行脚本
Quest1/
|
|- main.py
|
|- Items/
| |- __init__.py
| |- Quest1_items.py
Remove the dot from the beginning.从头开始删除点。 Relative paths with respect to
main.py
are found automatically.自动找到相对于
main.py
的相对路径。
from Items.Quest1_items import *
You can only perform relative import (ie., starting with a dot), inside a package that you import.您只能在您导入的 package 内执行相对导入(即,以点开头)。 For instance, imagine the situation:
例如,想象一下这种情况:
project/
├ main.py
├ mylib/
├ __init__.py
│ ├ module1.py
│ └ module2.py
in main.py
, you would have import mylib
or from mylib import *
, but inside module1.py
, you could have from. import module2
在
main.py
中,您将拥有import mylib
或from mylib import *
,但在module1.py
中,您可以拥有from. import module2
from. import module2
, because here the .
from. import module2
,因为这里的.
stands for mylib
(which is a python package, because you imported it within main.py
).代表
mylib
(这是一个 python package,因为您在main.py
中导入了它)。
So, the solution is simply remove the dot, it's not useful in your situation.因此,解决方案只是删除点,它在您的情况下没有用。
To put it simply: if you use relative import, you can run the file you want to run with 'python -m your_module_path' on the two layers above the outermost file used by your code.简单地说:如果你使用相对导入,你可以在你的代码使用的最外层文件上方的两层上运行你想要运行的文件,使用'python -m your_module_path'。
Like the following, if you want to run run.py
, you need to go to two layers above it, then run python -m dir1.dir2.run
(without .py
).如下所示,如果要运行
run.py
,则需要 go 到它上面的两层,然后运行python -m dir1.dir2.run
(不带.py
)。
.../dir1/dir2/
-test
-test1.py
from .test2 import *
-test2.py
-run.py
from .test.test1 import *
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.