python中的relative import使用起来却有不少问题。
比如下面这样一个结构
crawler |_src_ | |_spiders_ | |_test.py | |_local_settings.py
test.py中想import local_settings这个模块,那在test.py中加上
import ...local_settings
运行 python test.py。 结果就是报了标题的错误。
查阅了一些资料,原因如下:
在python文档https://docs.python.org/3.9/tutorial/modules.html#intra-package-references中有段话:
Note that relative imports are based on the name of the current module. Since the name of the main module is always "main", modules intended for use as the main module of a Python application must always use absolute imports.
还有在PEP 328(https://peps.python.org/pep-0328/#relative-imports-and-name)有:
Relative imports use a module's name attribute to determine that module's position in the package hierarchy. 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.
也就是说由于test.py中的__name__
attribute没有设置,__name__
== __main__
,所以把test.py当成了顶层,这时reletive import就没法使用了。
解决方法有一:
sys.path.append("../..") from local_setting import *
二:
不是直接运行test.py这个script,而是当作module来运行
python -m crawler.src.spiders.test
三:
在子目录中的py文件中使用relative import,而不是从顶层目录中的py中使用relieve import
具体的分析过程参照:
https://stackoverflow.com/questions/30669474/beyond-top-level-package-error-in-relative-import
https://stackoverflow.com/questions/14132789/relative-imports-for-the-billionth-time/14132912#14132912
https://stackoverflow.com/questions/16981921/relative-imports-in-python-3
https://stackoverflow.com/questions/68960171/python-error-importerror-attempted-relative-import-with-no-known-parent-package
https://napuzba.com/a/import-error-relative-no-parent/