运行juptyer笔记本时如何修复导入错误?

问题描述:

我有一个python jupyter笔记本,我试图在命令行上执行。下面是一个命令:运行juptyer笔记本时如何修复导入错误?

jupyter nbconvert --to notebook --execute --ExecutePreprocessor.timeout=60 --output out_file test.ipynb 

这里是这款笔记本(test.ipynb

{"cells":[{"metadata":{"deletable":true,"editable":true},"cell_type":"markdown","source":["# Morphology analysis with neurom\n","\n","You can find the full documentation of neurom on http://neurom.readthedocs.io/en/latest/index.html ."]},{"metadata":{"collapsed":false,"deletable":true,"editable":true,"trusted":false},"cell_type":"code","source":["%matplotlib inline\n","from copy import deepcopy\n","\n","from IPython.display import display, HTML\n","import urllib, zipfile, os\n","\n","try:\n"," import neurom\n"," from neurom import viewer, stats\n","except ImportError:\n"," !pip2 install neurom\n"," import neurom\n"," from neurom import viewer, stats"],"execution_count":null,"outputs":[]}],"metadata":{"kernelspec":{"name":"python2","display_name":"Python 2","language":"python"},"language_info":{"version":"2.7.6","mimetype":"text/x-python","file_extension":".py","codemirror_mode":{"version":2,"name":"ipython"},"nbconvert_exporter":"python","name":"python","pygments_lexer":"ipython2"}},"nbformat":4,"nbformat_minor":2} 

对应于下面的代码的测试版本:

get_ipython().magic(u'matplotlib inline') 
from copy import deepcopy 

from IPython.display import display, HTML 
import urllib, zipfile, os 

try: 
    import neurom 
    from neurom import viewer, stats 
except ImportError: 
    get_ipython().system(u'pip2 install neurom') 
    import neurom 
    from neurom import viewer, stats 

运行这段代码与上面的命令,我得到以下错误

ImportError: No module named neurom 

尽管此模块安装在当前设置中。那么,python为什么不拿起这个模块呢?

问题似乎是笔记本的执行不使用当前环境(例如virtualenv),您必须将其“添加”到jupyter笔记本。

因此首先要使用此命令

jupyter notebook --generate-config 

产生通常是一个文件~/.jupyter/jupyter_notebook_config.py生成标准配置。在该文件中,您必须添加以下部分

c.InteractiveShellApp.exec_lines=[ 
    'import sys; sys.path.append("path-to-add")' 
] 

向您的执行添加路径。

参见线程here