Python进阶(4) Jupyter Notebook

本文详细介绍JupyterNotebook的远程访问配置、实用技巧、常见问题解决方案及推荐扩展包,帮助用户提升工作效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


0. 前言

  • 安装:pip install jupyter

1. 远程访问

1.1. 方法一

  • 第一步:生成配置文件 jupyter notebook --generate-config
  • 第二步:进入python命令行,生成密码。
>>> from notebook.auth import passwd
>>> passwd()
Enter password:
Verify password:
'sha1:xxxxxxxxxx'
  • 第三步:修改默认配置文件vim ~/.jupyter/jupyter_notebook_config.py
c.NotebookApp.ip='*' # 就是设置所有ip皆可访问
c.NotebookApp.password = u'sha:xxxx...' # 即上一部生成的值
c.NotebookApp.open_browser = False # 禁止自动打开浏览器
c.NotebookApp.port = 8888 #随便指定一个端口
  • 第四步:启动jupyter jupyter notebook

1.2. 方法二

  • 第一步:新建配置文件 config.json
{
  "NotebookApp": {
    "ip": "0.0.0.0",
    "port": 8888,
    "open_browser": false,
    "token": ""
  }
}
  • 第二步:运行命令 jupyter notebook --config /path/to/config.json >> /dev/null &

2. 小技巧

2.1. 重载模块

import imp
imp.reload(module_name)

2.2. 执行命令行命令

  • 在语句最开始添加一个感叹号,如!ls

2.3. 设置主题

  • Github
  • 安装:pip install jupyterthemes
  • 基本使用:
jt -l  # 查看可用主题列表
jt -r  # 选择默认主题
jt -t themename  # 选择主题

2.4. 添加ikernel

  • 安装 ipykernel 或 jupyter,即pip install ipykernelpip install jupyter
  • 添加 kernel 命令:python -m ipykernel install --name mykernel_name
  • 注意:有可能会因为权限不足安装失败,这时需要执行 sudo /path/to/my/python -m ipykernel install --name mykernel_name

2.5. 计时

  • 在一个cell最开始添加 %%time,会计算当前cell的运行时间。
  • 对某一行添加 %time,则会计算当前行的运行时间。
  • 对某一行添加 %timeit,则会多次运行本行(说是默认跑100000次,但我是的时候跑了1loop,7runs),计算平均时间与方差。

3. 碰到的问题

3.1. 创建文件时 Permission Denied

  • 问题描述:nohup jupyter notebook 是不能正常运行的。
  • 解决:将需要常见文件的文件夹配置权限,即 chmod 777 /path/to/target/dir

3.2. Win10中偶尔出现的Matplotlib问题

  • 问题描述:
    • 当使用 plt.imshow(img) 等展示图片时不会显示图片。
    • 报错:UserWarning: Matplotlib is currently using agg, which is a non-GUI backend, so cannot show the figure.
  • 解决:在import完之后添加 %matplotlib notebook

3.3. 在 jupyter 中展示视频

  • 问题描述:
    • Jupyter 中展示图片一般使用 matplotlib 的 plt.imshow 即可。
    • 但如何在jupyter中展示视频(连续展示多张图片)?
  • 解决:使用 IPython 解决
    • PS: 如果视频是由多张图片组成,可以直接通过 display(Image(data=img_path)) 来实现。
from IPython.display import clear_output, display, Image
import cv2
import time

cap = cv2.VideoCapture("/path/to/xx.mp4")

while True:
    ret, frame = cap.read()
    if not ret:
        break
    clear_output()
    _, img = cv2.imencode('.png', frame)
    display(Image(data=img))
    time.sleep(0.1)

4. 进阶扩展包

  • 安装:
pip install jupyter_contrib_nbextensions
jupyter contrib nbextension install—user
pip install jupyter_nbextensions_configurator
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值