简体   繁体   English

在 Jupyter Notebook 中导入本地模块

[英]Import local modules in Jupyter notebook

I would like to outsource some general functions useful for multiple notebooks in a module (also for testing purposes).我想外包一些对模块中多个笔记本有用的通用功能(也用于测试目的)。 The current directory structure looks like the following当前目录结构如下所示

jupyter/
├─ notebooks/
│  ├─ 01 Notebook 1.ipynb
│  ├─ ...
├─ src/
│  ├─ module_a/
│  │  ├─ __init__.py
│  │  ├─ func_a.py
│  ├─ module_b/...
├─ tests/...
├─ data/...
├─ .../

In func_a.py , there is a simple function def print_a(): print('a')func_a.py ,有一个简单的函数def print_a(): print('a')

However, when I would like to import and use module_a in 01 Notebook 1.ipynb by using (what I think makes sense)但是,当我想通过使用(我认为有道理)在01 Notebook 1.ipynb导入和使用module_a

from .. src.module_a import print_a

I got an ImportError: attempted relative import with no known parent package .我得到了一个ImportError: attempted relative import with no known parent package What am I doing wrong?我究竟做错了什么? I am using Python 3.9.我正在使用 Python 3.9。

I would try to append the src directory to the system path like so:我会尝试将 src 目录附加到系统路径,如下所示:

import sys
sys.path.append("/path/to/your/src")

from src.module_a import a

please note that you can use the relative path from your notebook root and not absolute path like in the example above, so the following:请注意,您可以使用笔记本根目录中的相对路径,而不是上面示例中的绝对路径,因此如下所示:

sys.path.append("src")

should work too也应该工作

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM