使用 Jupyter notebook 在 python 中进行相对导入

Relative Import in python with Jupyter notebook

我在 python 中遇到一些导入问题。不太明白为什么会报错

我正在使用目录笔记本中的 jupyter 笔记本。我需要导入位于 source/prepare_data.py

中的函数 prepare_data

对于导入,我尝试使用 from ..source.prepare_data import prepare_data

这里 https://docs.python.org/3/reference/import.html(第 5.7 段)和 python 向我显示错误 "attempted relative import beyond top-level package"。

packages

您无法从当前工作目录的父目录导入。解决这个问题的简单方法是从根路径开始工作。

您可以在 this answer 中找到更多信息。

您可以将脚本的路径添加到您的系统路径中:

sys.path.append('../source/')
from prepare_data import prepare_data

请注意,这是一个漂亮的 quick-and-dirty hack。如果您正在考虑打包代码,来自@albeksdurf 的链接答案有一些更好的选择。