安装前提:Python 环境
Jupyter Notebook 需要 Python 3.8+。推荐使用虚拟环境隔离项目依赖:
# 检查 Python 版本(需要 3.8+) $ python3 --version Python 3.12.2 # 创建虚拟环境 $ python3 -m venv myenv # 激活虚拟环境 $ source myenv/bin/activate # macOS / Linux $ myenv\Scripts\activate # Windows
方法一:pip 安装(推荐)
最简单的安装方式:
# 安装 classic Jupyter Notebook $ pip install notebook # 或者安装功能更强大的 JupyterLab(现代推荐) $ pip install jupyterlab # 验证安装 $ jupyter --version Selected Jupyter core packages... IPython : 9.5.0 ipykernel : 7.2.0 jupyter_client : 8.8.0 notebook : 7.3.x
TIP
notebook 是经典版(本教程主要介绍),jupyterlab 是下一代界面,两者可以同时安装。启动时分别用 jupyter notebook 和 jupyter lab。
方法二:conda 安装
如果你使用 Anaconda 或 Miniconda 管理 Python 环境,Jupyter 已经内置:
# Anaconda 发行版已预装 Jupyter,直接启动即可 $ conda list jupyter # 用 conda 安装/更新 $ conda install -c conda-forge notebook jupyterlab # 创建独立环境 $ conda create -n ds_env python=3.12 notebook pandas matplotlib $ conda activate ds_env
安装常用科学计算包
数据科学工作通常需要以下套件:
$ pip install numpy pandas matplotlib seaborn scikit-learn
| 包名 | 用途 |
|---|---|
numpy | 数值计算、多维数组 |
pandas | 数据框(DataFrame)、数据清洗 |
matplotlib | 2D 图表绘制 |
seaborn | 统计图表(基于 matplotlib) |
scikit-learn | 机器学习算法库 |
scipy | 科学计算(积分、优化、统计) |
ipywidgets | 交互式控件 |
启动 Jupyter Notebook
# 在当前目录启动 $ jupyter notebook # 指定工作目录 $ jupyter notebook --notebook-dir=/Users/mi/projects # 指定端口(默认 8888) $ jupyter notebook --port=8889 # 不自动打开浏览器 $ jupyter notebook --no-browser
启动后,终端会输出类似:
To access the notebook, open this file in a browser:
file:///Users/mi/.local/share/jupyter/runtime/nbserver-xxx.html
Or copy and paste one of these URLs:
http://localhost:8888/?token=abc123def456...
浏览器会自动打开 http://localhost:8888/tree,显示 Jupyter 主页。
首次访问:Token 认证
Jupyter 默认开启 Token 认证,防止未授权访问。第一次打开时需要输入 Token:
- 从终端输出的 URL 中复制 Token(
?token=...后面的字符串) - 或在终端运行
jupyter notebook list查看当前 Token - 也可以在 "Password or token" 输入框粘贴
WARNING
不要在公共网络上设置空 Token(
--NotebookApp.token=''),这会让任何能访问该端口的人都可以执行代码。仅在本机开发时可以关闭认证。
配置文件
使用配置文件持久化设置,避免每次都要敲参数:
# 生成配置文件 $ jupyter notebook --generate-config Writing default config to: /Users/mi/.jupyter/jupyter_notebook_config.py # 编辑配置文件,修改以下选项:
# ~/.jupyter/jupyter_notebook_config.py # 设置默认工作目录 c.NotebookApp.notebook_dir = '/Users/mi/notebooks' # 设置端口 c.NotebookApp.port = 8888 # 关闭自动打开浏览器 c.NotebookApp.open_browser = False # 设置密码(哈希值,用 jupyter notebook password 生成) c.NotebookApp.password = 'argon2:...'
停止 Jupyter
在终端按 Ctrl+C,会提示:
Shutdown this notebook server (y/[n])? y
输入 y 确认停止。也可以在 Jupyter 主页的 File 菜单中选择 "Shut Down"。
国内加速安装
如果 pip 下载速度慢,可使用国内镜像:
# 使用清华镜像 $ pip install notebook -i https://pypi.tuna.tsinghua.edu.cn/simple # 或者设置为默认镜像 $ pip config set global.index-url https://pypi.tuna.tsinghua.edu.cn/simple
本章小结
pip install notebook是最简单的安装方式jupyter notebook在当前目录启动服务- 配置文件在
~/.jupyter/jupyter_notebook_config.py - 默认端口 8888,地址
http://localhost:8888/tree