首页 文章

Jupyter和Python中的sys.path不同 - 如何在Jupyter中导入自己的模块?

提问于
浏览
34

在Jupyter我没有加载我自己的小模块但是在python / bpython中一切都很好 . 打字时

import sys
print(sys.path)

我的模块的路径不会在Jupyter中显示,但在python / bpython中它仍然存在 .

我在用:

.bashrc中的

  • PYTHONPATH包含我的模块,

  • jupyter和bpython在virtualenv中 .

最相似的问题是Cannot import modules in jupyter notebook; wrong sys.path

如何配置Jupyter自动加载我的模块?

3 回答

  • 12

    Jupyter基于ipython,一个永久的解决方案可能是改变ipython配置选项 .

    创建配置文件

    $ ipython profile create
    $ ipython locate
    /Users/username/.ipython
    

    编辑配置文件

    $ cd /Users/username/.ipython
    $ vi profile_default/ipython_config.py
    

    以下行允许您将模块路径添加到sys.path

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

    在jupyter启动时,将执行上一行

    在这里您可以找到有关ipython config https://www.lucypark.kr/blog/2013/02/10/when-python-imports-and-ipython-does-not/的更多详细信息

  • 26

    以下是我在jupyter笔记本中的项目,

    import sys
    sys.path.append("../") # go to parent dir
    from customFunctions import *
    

    然后,为了影响 customFunctions.py 的变化,

    %load_ext autoreload
    %autoreload 2
    
  • 4

    Jupyter有自己的PATH变量JUPYTER_PATH .

    将此行添加到 .bashrc 文件对我有用:

    export JUPYTER_PATH=<directory_for_your_module>:$JUPYTER_PATH
    

相关问题