简体   繁体   中英

Import pycharm project into jupyter notebook

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 ?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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