sys.path different in Jupyter and Python - how to import own modules in Jupyter?

后端 未结 5 1731
一向
一向 2020-11-30 01:29

In Jupyter my own little module is not loaded but in python/bpython is everything is fine. When typing

import sys
print(sys.path)

the path

5条回答
  •  没有蜡笔的小新
    2020-11-30 02:17

    Suppose your project has the following structure and you want to do imports in the notebook.ipynb:

    /app
      /mypackage
        mymodule.py
      /notebooks
        notebook.ipynb
    

    If you are running Jupyter inside a docker container without any virtualenv it might be useful to create Jupyter (ipython) config in your project folder:

    /app
      /profile_default
        ipython_config.py
    

    Content of ipython_config.py:

    c.InteractiveShellApp.exec_lines = [
        'import sys; sys.path.append("/app")'
    ]
    

    Open the notebook and check it out:

    print(sys.path)
    

    ['', '/usr/local/lib/python36.zip', '/usr/local/lib/python3.6', '/usr/local/lib/python3.6/lib-dynload', '/usr/local/lib/python3.6/site-packages', '/usr/local/lib/python3.6/site-packages/IPython/extensions', '/root/.ipython', '/app']

    Now you can do imports in your notebook without any sys.path appending in the cells:

    from mypackage.mymodule import myfunc
    

提交回复
热议问题