Jupyter Notebook 的安装和使用

Jupyter Notebook 是一款优秀的 Python 数据分析工具。Anaconda 内部就封装了这个工具,使用十分方便。这里介绍如何手动安装和配置 Jupyter Notebook。
官方网站:https://jupyter.org/
官方文档:https://jupyter-notebook.readthedocs.io/en/stable/
官方 GitHub 仓库:https://github.com/jupyter/notebook
Jupyter Notebook 安装和运行
直接使用 pip 即可安装:
pip install notebook
安装好以后就可以启动 Jupyter Notebook 了:
jupyter notebook
远程使用 Jupyter Notebook
其实使用上面两个步骤,就可以在本地使用 Jupyter Notebook 了。但是如果 Jupyter 的服务运行在其他服务器或虚拟机中,是无法从另一台电脑访问到的。若要远程使用 Jupyter Notebook,还需要一点额外的配置。
Jupyter Notebook 在不同系统中默认的配置文件位置如下:
- Windows:
C:\Users\USERNAME\.jupyter\jupyter_notebook_config.py
- OS X:
/Users/USERNAME/.jupyter/jupyter_notebook_config.py
- Linux:
/home/USERNAME/.jupyter/jupyter_notebook_config.py
如果还未创建配置文件,可使用如下命令初始化配置文件:
jupyter notebook --generate-config
在配置文件中设置允许访问 Jupyter Notebook 的 IP 和 Jupyter 服务的端口,并禁用自动开启浏览器:
c.NotebookApp.ip = '*' # * 代表运行所有 IP
c.NotebookApp.port = 9999
c.NotebookApp.open_browser = False
此时,根据提示,就可以通过浏览器访问 Jupyter Notebook 服务了:

修改 Jupyter Notebook 密码
使用 token 登陆毕竟还是不方便,这时我们可以通过给 Jupyter Notebook 设置密码,通过密码访问 Jupyter 服务。
有两种方式可以修改 Jupyter Notebook 的密码。
第一种方式比较简便,在终端中使用命令即可:
$ jupyter notebook password
Enter password: ****
Verify password: ****
[NotebookPasswordApp] Wrote hashed password to /Users/you/.jupyter/jupyter_notebook_config.json
第二种方式比较繁琐,需要首先使用 Jupyter 的哈希工具获取密码的哈希值:
In [1]: from notebook.auth import passwd
In [2]: passwd()
Enter password:
Verify password:
Out[2]: 'sha1:67c9e60bb8b6:9ffede0825894254b2e042ea597d771089e11aed'
然后将密码写入到 Jupyter Notebook 的配置文件中:
c.NotebookApp.password = u'sha1:67c9e60bb8b6:9ffede0825894254b2e042ea597d771089e11aed'
再次启动 Jupyter Notebook,浏览器访问时就会提示我们输入密码了:

supervisor 配置
为了让 Jupyter 服务能一直在后台运行,可以使用 supervisor 进行管理。supervisor 的配置参数如下(注意替换相应的路径):
[program:jupyter]
directory=/work/directory
command=/absolute/path/to/jupyter notebook
stdout_logfile=/absolute/path/to/logs/jupyter.log