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

如何将带Jupyter单元格的.py文件直接转换为HTML?

直接将带Jupyter单元格的.py文件转为HTML的方案

以下是几种无需手动中转.ipynb的一步到位解决方案:

1. 使用jupytext + nbconvert命令行工具

这是最便捷的命令行方案,先安装依赖包:

pip install jupytext nbconvert

执行以下命令即可完成转换(如果不需要运行代码单元格,去掉--execute参数):

jupytext --to ipynb --execute your_script.py --output - | jupyter nbconvert --stdin --to html --output your_output.html

该命令通过jupytext将.py文件转为临时.ipynb格式(并执行代码),再通过管道直接传给nbconvert导出为HTML,全程无中间文件生成。

2. 编写Python脚本封装转换逻辑

如果需要自定义转换规则(比如指定HTML模板、选择性执行单元格),可以用脚本实现:

import jupytext
from nbconvert import HTMLExporter

# 替换为你的文件路径
input_path = "your_script.py"
output_path = "your_output.html"

# 读取带Jupyter单元格的.py文件
notebook = jupytext.read(input_path)

# 可选:执行代码单元格(保留运行结果)
# from nbclient import NotebookClient
# client = NotebookClient(notebook)
# client.execute()

# 导出HTML
exporter = HTMLExporter()
html_content, _ = exporter.from_notebook_node(notebook)

# 写入输出文件
with open(output_path, "w", encoding="utf-8") as f:
    f.write(html_content)

运行脚本即可直接完成转换,逻辑更灵活可控。

注意事项

  • 确保你的.py文件严格遵循VS Code的Jupyter单元格规范(用# %%标记单元格分隔),jupytext才能正确识别结构。
  • 若代码依赖特定第三方包,需在转换环境中提前安装,避免执行失败。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 20:32:40