在Jupyter notebook中使用特定虚拟环境中的python的kernel

    在虚拟环境tf中安装完tensorflow后,在虚拟环境tf打开的jupyter里发现只有一个kernel-python3,新建一个文件, import tensorflow as tf ,发现报错,没有tf这个模块。
    一开始还以为是tf的问题安装失败,后来才意识到是jupyter的问题。因为在虚拟环境tf中,虽然有jupyter(或者自己再安装pip install jupyter,他会提示说已存在),但这个jupyter还是原python环境中的jupyter。在虚拟环境tf中用命令 (tf) treamy ~ $ which jupyter 得/usr/local/bin/jupyter 再用 (tf) treamy ~ $ find ~/code/pydir/env -name "jupyter*" 发现虚拟环境中无jupyter故虚拟环境中的jupyter还是原python环境中的jupyter,kernel为python3,而我的原python3并没有安装tensorflow,所以报错了。
 
 
 

之前查网上按这个方法解决:(但无效)

(tf) treamy ~ $ ipython kernelspec install-self --user
[TerminalIPythonApp] WARNING | Subcommand `ipython kernelspec` is deprecated and will be removed in future versions.
[TerminalIPythonApp] WARNING | You likely want to use `jupyter kernelspec` in the future
[InstallNativeKernelSpec] WARNING | `jupyter kernelspec install-self` is DEPRECATED as of 4.0. You probably want `ipython kernel install` to install the IPython kernelspec.
[InstallNativeKernelSpec] Installed kernelspec python3 in /Users/treamy/Library/Jupyter/kernels/python3
(tf) treamy ~ $ mkdir -p ~/.ipython/kernels
(tf) treamy ~ $ mv /Users/treamy/Library/Jupyter/kernels/python3 ~/.ipython/kernels/tfkernel
打开kernel.json文件,然后将display_name 后面的内容修改为tfkernel
(tf) treamy ~ $ vim ~/.ipython/kernels/tfkernel/kernel.json
但这样并无效果,因为创建的kernel相当于只是原kernel的复制品即python3,从上面那个json文件就可以看出来。
 
 

解决方案:

(tf) treamy ~ $ python3 -m ipykernel install --user --name tf --display-name "Python3(tf)"
# Installed kernelspec tf in /Users/treamy/Library/Jupyter/kernels/tf
cd 到 /Users/treamy/Library/Jupyter/kernels/tf
里面含 kernel.json  logo-32x32.png  logo-64x64.png 
查看这个json文件: cat kernel.json 
{
"argv": [
"/Users/treamy/code/pydir/env/tf/bin/python3",
"-m",
"ipykernel_launcher",
"-f",
"{connection_file}"
],
"display_name": "Python3(tf)",
"language": "python"
}
 
然后也不用移动它,就这样就OK了。刷新jupyter后就可以看到Python3(tf)这个选项。

详细官方文档:

posted @ 2019-01-21 23:37  chen狗蛋儿  阅读(2451)  评论(0编辑  收藏  举报