frankr6591
frankr6591

Reputation: 1247

import fails on jupyter-notebook

NOTE: this is a duplicate of import from local directory on python2.

Let me say upfront, sorry as I've read thru the import rules for python, ipython and jupython and can't keep them straight anymore...

Environment:

ubuntu linux server with jupyterhub
jupyter home is $HOME/opt
$HOME/opt/mynotebooks                      # contains my .pynb notebooks
$HOME/opt/mynotebooks/py_lib               # contains .py files
$HOME/opt/mynotebooks/py_lib/app_config.py # myapp config/links to myapp
$HOME/opt/mynotebooks/py_lib/class1.py     # contains .py files
/opt/myapp/src/app                         # contains my app .py classes
/opt/myapp/src/app/appclass.py             # contains appclass

My notebook1.pynb contains the following start-up cell :

import os, sys
MY_NOTEBOOK = os.path.join(os.getenv('HOME'),'opt','mynotebooks')
# add my notebook to ipython path
os.chdir(MY_NOTEBOOK)
sys.path.append(MY_NOTEBOOK) 
import py_lib.app_config
print(os.getenv('MYAPP_STORE')

The above cell works ok.

Next, the load py_lib.class1 cell to do work...

from py_lib.class1 import myclass1

But the above gives error: "No module named class1".

If I move the app_config.py into my notebook dir it works use the following start-up cell...(NOTE import app_config changed without py_lib... I restart kernel and clear all output before re-running). The sys.path is the same when I do the py_lib.class1 import. Why can't it find it when app_config is 1 level down? Makes no sense?

import os, sys
MY_NOTEBOOK = os.path.join(os.getenv('HOME'),'opt','mynotebooks')
# add my notebook to ipython path
os.chdir(MY_NOTEBOOK)
sys.path.append(MY_NOTEBOOK) 
import app_config
print(os.getenv('MYAPP_STORE')

(BTW: this latter startup fails if I save notebook to py and run via python.)

$HOME/opt/mynotebooks/nb_lib/app_config.py

APP_SITE = os.path.join('/opt/myapp/src')
APP_STORE = os.path.join('/opt/myapp/store')
os.environ['APP_SITE'] = APP_SITE
os.environ['APP_STORE'] = APP_STORE
# Link to APP_SITE
os.chdir(APP_SITE)
sys.path.append(APP_SITE)  
APP_UPLOAD = os.path.join(APP_STORE,'upload')

Upvotes: 2

Views: 1805

Answers (1)

frankr6591
frankr6591

Reputation: 1247

I found the issue to be a duplicate of import from local directory.

Specifically, "Python 2.5 for Ubuntu 8.10 does not have the current directory (empty string) in sys.path for the interpreter."

Unfortunately, my app is still on py2 so I run the notebook on py2. I have put a sample of the AppNotebooks. So fix is to migrate to py3. Or for app, put config into a sub package (ie. py_lib).

Upvotes: 1

Related Questions