Python Jupyter Notebook 中的相对导入

Python Relative Import in Jupyter Notebook

假设我有以下结构:

 dir_1
 ├── functions.py
 └── dir_2
     └── code.ipynb

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

from ..functions import some_function

我收到错误:

attempted relative import with no known parent package

我检查了一堆类似的帖子,但还没有弄清楚...我是 运行 来自 conda env 的 jupyter notebook,我的 python 版本是 3.7.6.

您可以使用sys.path.append('/path/to/application/app/folder')然后尝试导入

在你的笔记本中做:

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

jupyter 笔记本从 sys.path 中的当前工作目录开始。 见 sys.path

... the directory containing the script that was used to invoke the Python interpreter.

如果你的实用函数在父目录中,你可以这样做:

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

给定这样的结构:

 dir_1
 ├── functions
 │   └──__init__.py  # contains some_function
 └── dir_2
     └── code.ipynb

我们只是将相对路径插入 sys.path:

import sys

if ".." not in sys.path:
    sys.path.insert(0, "..")
from functions import some_function