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

如何在pyproject.toml中实现setup.py的post_install注册Jupyter Widget逻辑

用pyproject.toml实现Jupyter Widget注册的post_install逻辑

问题背景

之前通过setup.py自定义develop、install、egg_info命令类,在安装/开发模式下执行_post_install函数完成Jupyter Widget注册,现在想迁移到pyproject.toml体系。

实现方案

目前pyproject.toml作为纯配置文件无法直接定义自定义命令类(涉及可执行Python逻辑),因此需要结合精简的setup.py保留原有逻辑,同时将项目元数据、构建依赖等配置移到pyproject.toml中。

步骤1:配置pyproject.toml

在项目根目录创建/修改pyproject.toml,声明构建依赖和项目元数据:

[build-system]
requires = ["setuptools>=61.0"]
build-backend = "setuptools.build_meta"

[project]
name = "你的Widget包名"
version = "0.1.0"
authors = [
  { name="你的名字", email="你的邮箱" }
]
description = "Jupyter Widget 示例包"
# 按需添加更多元数据(如依赖、分类等)

步骤2:保留精简的setup.py

创建/修改setup.py,仅保留自定义命令类和_post_install逻辑:

from setuptools import setup
from setuptools.command.develop import develop as _develop
from setuptools.command.install import install as _install
from setuptools.command.egg_info import egg_info as _egg_info

def _post_install():
    # 这里写入你的Jupyter Widget注册逻辑,示例:
    # import subprocess
    # subprocess.run(["jupyter", "nbextension", "install", "--sys-prefix", "你的Widget模块"])
    # subprocess.run(["jupyter", "nbextension", "enable", "--sys-prefix", "你的Widget模块"])
    print("执行Jupyter Widget注册逻辑...")

class develop(_develop):
    def run(self):
        self.execute(_post_install, (), msg="Running post-install...")
        super().run()

class install(_install):
    def run(self):
        self.execute(_post_install, (), msg="Running post-install...")
        super().run()

class egg_info(_egg_info):
    def run(self):
        self.execute(_post_install, (), msg="Running post-install...")
        super().run()

setup(
    cmdclass={
        "develop": develop,
        "install": install,
        "egg_info": egg_info,
    }
)

替代方案:使用Jupyter官方打包工具

如果是Jupyter Widget开发,更推荐使用jupyter-packaging工具,它已集成Widget注册的相关逻辑,可直接在pyproject.toml中配置,无需手动写post_install:

[build-system]
requires = ["jupyter-packaging>=0.12.0", "setuptools>=61.0"]
build-backend = "jupyter_packaging.build_api"

[project]
name = "你的Widget包名"
version = "0.1.0"

[tool.jupyter-packaging]
extension = "你的Widget模块名"
widgets = true

说明

  • pyproject.toml负责声明构建环境、项目元数据等静态配置;
  • 自定义命令类和执行逻辑仍需放在setup.py中,因为涉及Python代码执行,无法通过纯配置文件实现;
  • 若使用jupyter-packaging,可完全省略手动的post_install逻辑,更符合Jupyter生态的打包规范。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 11:17:17