Setting a default sys.path for a Notebook

ぃ、小莉子 提交于 2019-12-05 03:05:41
Nick T

To avoid "hidden configurations" (i.e. things that aren't in source control/machine-specific) and to maintain a notebook/code separation like you describe, I do something like the below:

code/
    mymodule.py
    mypackage/
        __init__.py

notebooks/
    mynb.ipynb
    mynb2.ipynb
    paths.py   <--- below

In paths.py:

import sys
import pathlib
sys.path.insert(0, str(pathlib.Path(__file__).parents[1] / 'code'))
# sys.path[0] = str(pathlib.Path(__file__).parents[1] / 'code')

Then in mynb*.ipynb I can happily do:

import paths
import mymodule, mypackage

, etc.

The latter form effectively replaces the import path from the empty-string (current directory) to the "code" directory, which is perhaps a bit cleaner. This makes imports insensitive to using stuff like os.chdir().

I wrote simple bash script which updates the path and launches Jupyter:

#!/usr/bin/env bash

echo "Saving PYTHONPATH"
ORIGINAL_PYTHONPATH=$PYTHONPATH
echo "Prepending package to PYTHONPATH"
export PYTHONPATH="$PWD/:$ORIGINAL_PYTHONPATH"
echo "Starting Jupyter"
jupyter notebook
echo "Reverting to the original PYTHONPATH"
export PYTHONPATH=$ORIGINAL_PYTHONPATH

After some research I realized changing PYTHONPATH in .bash_profile should do the trick.

Here are the two lines that I added to my .bash_profile

PYTHONPATH="<path where DeriveFinalResultSet.py exists>:$PYTHONPATH"
export PYTHONPATH

To verify, I did the following after opening a fresh IPython Notebook.

import sys
print(sys.path)
['', '**<path where DeriveFinalResultSet.py exists>**', '<some path>Google Drive/Project/AnimalPhotoBias/Notebooks', '<some path>anaconda/lib/python35.zip', '<some path>anaconda/lib/python3.5', '<some path>anaconda/lib/python3.5/plat-darwin', '<some path>anaconda/lib/python3.5/lib-dynload', '<some path>anaconda/lib/python3.5/site-packages/Sphinx-1.3.5-py3.5.egg', '<some path>anaconda/lib/python3.5/site-packages/setuptools-20.3-py3.5.egg', '<some path>anaconda/lib/python3.5/site-packages', '<some path>anaconda/lib/python3.5/site-packages/aeosa', '<some path>anaconda/lib/python3.5/site-packages/IPython/extensions', '<some path>.ipython']
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!