Stealing pages from the server...

Iimport Own Modules in Jupyter


Introduction

Importing the module path in Jupyter notebook could be a real pain in the ass at times. In this article, I’ll aim to explain how I establish a default system path for notebooks in order to avoid hidden configurations and make it easier to maintain a notebook or code.

Magic Tricks

The code structure in my folder (suppose it’s at C drive) would be like the following:

folder-name/
	package/
	    __init__.py
	    code.py
	notebooks/
	    notebook.ipynb

First, create a configuration file:

ipython profile create

Edit the configuration file (in my case, the file located at C:/Users/yangwang/.ipython/profile_default/ipython_config.py):

c = get_config()
c.InteractiveShellApp.exec_lines = [
    'import sys; sys.path.append(r"C:\\folder-name")'
]

Now whenever you open the notebook inside the notebooks folder, you are able to do from package import code stuff. To verify, you can also do the following after opening a fresh notebook:

import sys
print(sys.path)

References

  1. https://www.lucypark.kr/blog/2013/02/10/when-python-imports-and-ipython-does-not/
  2. https://stackoverflow.com/a/50305652

Author: Yang Wang
Reprint policy: All articles in this blog are used except for special statements CC BY 4.0 reprint polocy. If reproduced, please indicate source Yang Wang !
  TOC