You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Quarto运行Python代码遇nbformat缺失错误,求解决方案

解决Quarto运行Python代码时ModuleNotFoundError: No module named 'nbformat'问题

问题描述

在Quarto文档中运行Python代码时,反复出现ModuleNotFoundError: No module named 'nbformat'错误,但终端执行quarto check jupyter显示环境正常,尝试安装Jupyter后仍未解决。相关代码、报错及环境信息如下:

可复现Quarto代码:

---
title: "matplotlib demo"
format:
  html:
    code-fold: true
jupyter: python3
---

For a demonstration of a line plot on a polar axis, see @fig-polar.

```{python}
#| label: fig-polar
#| fig-cap: "A line plot on a polar axis"

import numpy as np
import matplotlib.pyplot as plt

r = np.arange(0, 2, 0.01)
theta = 2 * np.pi * r
fig, ax = plt.subplots(
  subplot_kw = {'projection': 'polar'} 
)
ax.plot(theta, r)
ax.set_rticks([0.5, 1, 1.5, 2])
ax.grid(True)
plt.show()
**报错信息**:

Starting python3 kernel...Traceback (most recent call last):
File "/Applications/RStudio.app/Contents/Resources/app/quarto/share/jupyter/jupyter.py", line 21, in
from notebook import notebook_execute, RestartKernel
File "/Applications/RStudio.app/Contents/Resources/app/quarto/share/jupyter/notebook.py", line 16, in
import nbformat
ModuleNotFoundError: No module named 'nbformat'

**环境检查结果**:

[✓] Checking Python 3 installation....OK
Version: 3.7.11 (Conda)
Path: /Users/quinten/Library/r-miniconda/envs/r-reticulate/bin/python
Jupyter: 4.12.0
Kernels: julia-1.8, python3

[✓] Checking Jupyter engine render....OK

### 解决方案

#### 1. 确认Quarto实际调用的Python环境
先检查Quarto默认使用的Python路径是否与预期一致:
```bash
quarto config get tools.python

如果输出不是/Users/quinten/Library/r-miniconda/envs/r-reticulate/bin/python,手动指定环境:

  • 临时方案:在Quarto文档的YAML头部添加python字段:
    ---
    title: "matplotlib demo"
    format:
      html:
        code-fold: true
    jupyter: python3
    python: /Users/quinten/Library/r-miniconda/envs/r-reticulate/bin/python
    ---
    
  • 全局方案:在终端执行命令设置全局默认Python:
    quarto config set tools.python /Users/quinten/Library/r-miniconda/envs/r-reticulate/bin/python
    

2. 给目标环境安装nbformat

激活r-reticulate conda环境,安装nbformat:

conda activate r-reticulate
pip install nbformat
# 或用conda安装:conda install nbformat -c conda-forge

3. 排查RStudio集成的环境冲突

如果在RStudio中运行Quarto,可能存在环境不一致问题:

  • 在RStudio控制台执行,强制使用r-reticulate环境:
    reticulate::use_condaenv("r-reticulate", required = TRUE)
    
  • 重启RStudio后重新渲染文档
  • 也可直接在终端渲染文档,排除RStudio干扰:
    quarto render your-document.qmd
    

4. 重置Jupyter Kernel(可选)

若上述步骤无效,检查并重置Jupyter Kernel:

  1. 查看当前Kernel列表:
    jupyter kernelspec list
    
  2. 若python3 Kernel未指向r-reticulate环境,重新安装Kernel:
    conda activate r-reticulate
    python -m ipykernel install --user --name python3 --display-name "Python (r-reticulate)"
    

内容的提问来源于stack exchange,提问作者Quinten

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 01:00:54