关于virtualenv:虚拟环境中的Jupyter Notebook没有看到虚拟环境包

Jupyter Notebook in virtual environment doesn't see the virtual env packages

我正在尝试在虚拟环境中使用Jupyter Notebook。
我创建了一个新的virtualenv virtualenv ker12
+激活+安装特定版本的keras或任何其他库。

同样如在IPython笔记本中使用virtualenv中提到的那样:

pip install ipykernel

python -m ipykernel install --user --name=my-virtualenv-name

当我运行笔记本并写
! which jupyter输出正确

/Users/myname/virtualenv/ker12/bin/python

但是当我尝试导入库时,例如import keras则会出错。

ImportError: No module named keras

但是当我写pip freeze | grep Keras时从另一边
输出是:

Keras==1.2.0

更新1:

这个问题与Keras无关,它与任何其他库(例如pandas)一起出现

如果我打印os.path,则输出如下:

<'module 'posixpath' from /usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/posixpath.pyc>

从"命令行python"开始,os.path看起来是正确的

<'module 'posixpath' from '/Users/my_name/virtualenv/ker12/lib/python2.7/posixpath.pyc'>

更新2:

如果我从终端打印sys.path并且jupyter输出也不同:

从终端

/Users/myname/virtualenv/ker12/lib/python27.zip
/Users/myname/virtualenv/ker12/lib/python2.7
/Users/myname/virtualenv/ker12/lib/python2.7/plat-darwin
/Users/myname/virtualenv/ker12/lib/python2.7/plat-mac
/Users/myname/virtualenv/ker12/lib/python2.7/plat-mac/lib-scriptpackages
/Users/myname/virtualenv/ker12/lib/python2.7/lib-tk
/Users/myname/virtualenv/ker12/lib/python2.7/lib-old
/Users/myname/virtualenv/ker12/lib/python2.7/lib-dynload
/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7
/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-darwin
/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk
/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac /usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac/lib-scriptpackages
/Users/myname/virtualenv/ker12/lib/python2.7/site-packages

来自JUPYTER

/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python27.zip
/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7
/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-darwin
/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac /usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac/lib-scriptpackages
/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk
/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-old
/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload
/usr/local/lib/python2.7/site-packages
/usr/local/lib/python2.7/site-packages/IPython/extensions
/Users/myname/.ipython `


解决方案是使用以下命令打开jupyter notebook:

~/virtualenv/my_venv_name/bin/jupyter-notebook


您不应该安装ipykernel - 而是应该在虚拟环境中进行完整的Jupyter安装(pip install jupyter)。 此外,请确保不使用--system-site-packages选项创建虚拟环境。

另见这个答案。