将自定义模块导入Jupyter Notebook [英] Importing custom module into jupyter notebook

查看:1016
本文介绍了将自定义模块导入Jupyter Notebook的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是的,我知道这是一个经常性的问题,但我仍然找不到令人信服的答案.我什至在 https://chrisyeh96.github.io上阅读/2017/08/08/definitive-guide-python-imports.html ,但找不到解决方法:

Yes, I know this is a recurrent question but I still couldn't find a convincing answer. I even read at https://chrisyeh96.github.io/2017/08/08/definitive-guide-python-imports.html but could not find out how to solve the problem:

我正在运行包含jupyter(ipython)笔记本的python 3.6项目.我希望笔记本导入自定义的本地helpers.py程序包,以后可能会在其他来源中使用该程序包.

I'm running python 3.6 project that includes jupyter (ipython) notebooks. I want the notebook to import a custom local helpers.py package that I will probably use also later in other sources.

项目结构类似于:

my_project/
│
├── my_project/
│   ├── notebooks/
│       └── a_notebook.ipynb
│   ├── __init__.py     # suppose to make package `my_project` importable
│   └── helpers.py
│
├── tests/
│   └── helpers_tests.py
│
├── .gitignore
├── LICENSE
├── README.md
├── requirements.txt
└── setup.py

在笔记本中导入helpers时出现错误:

When importing helpers in the notebook I get the error:

----> 4 import helpers

ModuleNotFoundError: No module named 'helpers'

我也尝试了from my_project import helpers,但遇到了相同的错误ModuleNotFoundError: No module named 'my_project'

I also tried from my_project import helpers and I get the same error ModuleNotFoundError: No module named 'my_project'

我最终(并暂时)使用了通常的技巧:

I finally (and temporarily) used the usual trick:

import sys
sys.path.append('..')
import helpers

但是它看起来很糟糕,我仍在寻找更好的解决方案

But it looks awful and I'm still looking for a better solution

推荐答案

一个人可以告诉python通过sys.path在哪里寻找模块.我有一个这样的项目结构:

One can tell python where to look for modules via sys.path. I have a project structure like this:

project/
    │
    ├── src/
    │    └── my_module/
    │        ├── __init__.py       
    │        └── helpers.py
    ├── notebooks/
    │   └── a_notebook.ipynb
    ...

我能够像这样加载模块:

I was able to load the module like so:

import sys
sys.path.append('../src/')

from my_module import helpers

一个人应该可以从任何地方加载该模块.

One should be able load the module from wherever they have it.

这篇关于将自定义模块导入Jupyter Notebook的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆