Reputation: 532
I am using Pycharm to develop a python package and would like to use Jupyter notebooks to interact with the modules.
My project structure is as follows :
project/notebooks/my_notebook.ipynb
project/module/__init__.py
project/module/core.py
project/tests/...
I run my_notebook.ipynb
in the browser but cannot figure out how to import the content of the python module. Anything like from module import foo
does not work out of the box. I came accross this blog post which involves installing the source code as an editable Pip package but I am wondering if there is another way to make it work that does not involves installing the package ?
Upvotes: 3
Views: 5653
Reputation: 2150
In my opinion is bad practice to hardcode a specific path into the notebook code. Instead I would add the root project folder to PYTHONPATH when starting up your Jupyter notebook server, either directly from the project folder like so
env PYTHONPATH=`pwd` jupyter notebook
or if you are starting it up from somewhere else, like so
env PYTHONPATH=/Users/foo/bar/project/ jupyter notebook
Upvotes: 0
Reputation: 1641
You just need to get that directory into your path inside the notebook:
eg:
import sys
# make sure to use position 1
sys.path.insert(1, "/Users/foo/bar/project/")
from module.core import foo
It's important to use position 1 as using position 0 may break sys.path: docs
Also note you should make sure you are using the same virtualenv (or conda env) for your notebook that your pycharm project is using, or else you might have unanticipated conflicts
Upvotes: 3