本文介绍了将自定义模块导入 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

推荐答案

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

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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-29 18:25
查看更多