Jupyter Notebook 中的 Python 相对导入

CHR*_*HRD 13 python relative-import anaconda jupyter-notebook

假设我有以下结构:

\n\n
 dir_1\n \xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 functions.py\n \xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 dir_2\n     \xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 code.ipynb\n
Run Code Online (Sandbox Code Playgroud)\n\n

在,,code.ipynb我只是想访问里面的一个函数functions.py并尝试了这个:

\n\n
from ..functions import some_function\n
Run Code Online (Sandbox Code Playgroud)\n\n

我收到错误:

\n\n
attempted relative import with no known parent package\n
Run Code Online (Sandbox Code Playgroud)\n\n

我已经检查了一堆类似的帖子,但还没有弄清楚这一点...我正在从 a 运行 jupyter 笔记本,conda env我的 python 版本是3.7.6.

\n

Mr_*_*s_D 9

在你的笔记本中执行以下操作:

import os, sys
dir2 = os.path.abspath('')
dir1 = os.path.dirname(dir2)
if not dir1 in sys.path: sys.path.append(dir1)
from functions import some_function
Run Code Online (Sandbox Code Playgroud)


gma*_*n3g 5

jupyter 笔记本从 sys.path 中的当前工作目录开始。请参阅系统路径

...包含用于调用 Python 解释器的脚本的目录。

如果您的实用程序函数位于父目录中,您可以执行以下操作:

import os, sys
parent_dir = os.path.abspath('..')
# the parent_dir could already be there if the kernel was not restarted,
# and we run this cell again
if parent_dir not in sys.path:
    sys.path.append(parent_dir)
from functions import some_function
Run Code Online (Sandbox Code Playgroud)