animal imported Traceback (most recent call last): File "__init__.py", line 3, in <module> from .cat import Cat ImportError: attempted relative import with no known parent package
在子目录中直接运行文件
有时需要在子目录中执行方便的脚本,但是这时就会遇到报错
此时可以通过修改sys.path来自定义搜索范围
首先尝试修改animal/__init__.py中内容为
1 2 3 4 5 6 7
import sys from pathlib import Path package_root = Path(__file__).absolute().parent.parent print(f"animal imported, add {package_root} to sys.path") sys.path.insert(0, str(package_root)) from animal.cat import Cat from animal.dog import Dog
在/root/project/animal下执行python __init__.py
此时输出为
1 2 3 4
animal imported, add /root/project/python_pkg_test to sys.path animal imported, add /root/project/python_pkg_test to sys.path Cat imported Dog imported