这个问题在这里已经有了答案:
Attempted relative import with no known parent package
(3 个回答)
Relative imports in Python 3
(24 个回答)
8 个月前关闭。
我有以下目录结构:
py_test
├── __init__.py
├── dir1
│ ├── __init__.py
│ └── script1.py
└── dir2
├── __init__.py
└── script2.py
在
script2
我想“import ..\script1
”。我在
script2
中尝试过的内容:from ..dir1 import script1
ImportError: attempted relative import with no known parent package`
import sys, os
path2add = os.path.normpath(os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir, 'dir1')))
if (not (path2add in sys.path)) :
sys.path.append(path2add)
如果我想使用选项 1,使其工作的最简单(即文件最少)的文件/目录结构是什么?
我知道 this ,但我想知道是否可以避免创建该目录结构,并且仍然使用 type-1
import
.我目前正在使用 this workaround , 它使用类型 2
import
.有关的:
How to import a Python class that is in a directory above?
Import a module from a directory (package) one level up
Getting "ImportError: attempted relative import with no known parent package" when running from Python Interpreter
Using importlib to dynamically import module(s) containing relative imports
How to import variables in a different python file
最佳答案
如评论中所述,尝试将模块导入目录将不起作用如果 script2.py
是你的切入点。
如 this link you included 中所述:
If the module's
__name__
does not contain any package information (e.g., it is set to__main__
), then relative imports are resolved as if the module were a top-level module, regardless of where the module is actually located on the file system.
该模块的
__name__
设置为 __main__
如果它是入口点,或者是你传递给解释器的入口点,比如 python script2.py
.这样运行的任何 python 模块都不再具有从更高目录导入文件所需的信息。
因此,您有两种选择:
选项 1:继续使用
sys.path.append
的解决方法这将按照您的意愿工作,但它相当麻烦。
选项 2:将您的入口点放在顶层
假设你的包有多个脚本需要运行,你可以创建一个新文件来导入
script1
和 script2
然后根据命令行参数调用您想要的功能。然后你就可以保持你当前的目录结构并且让你的相对导入工作得很好,而不需要对 sys.path
进行任何摆弄。 .
关于python - 另一个 ImportError : attempted relative import with no known parent package,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59489786/