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

如何让setup.py中的SDK检查代码仅在pip install时执行?

解决方案

可以通过两种方式实现仅在pip install时执行SDK检查,避免构建包时触发:

方法一:通过命令行参数判断场景

检查sys.argv中的执行命令,排除构建相关的命令(如build、sdist、bdist_wheel),仅在执行安装命令时运行检查代码:

import sys
from setuptools import setup

# 定义需要跳过检查的构建类命令
SKIP_COMMANDS = {"build", "sdist", "bdist_wheel", "bdist_egg"}

# 仅当当前命令不在排除列表中时执行检查
if not any(cmd in sys.argv for cmd in SKIP_COMMANDS):
    try:
        import pyzed.sl
    except ImportError:
        print("ERROR: You must manually install the ZED Python SDK first.")
        sys.exit(1)

    zed_version = [int(p) for p in pyzed.sl.Camera.get_sdk_version().split(".")]
    if zed_version < [4, 0, 8]:
        print("ERROR: ZED SDK 4.0.8 or higher is required, you must update the ZED SDK first.")
        sys.exit(1)

setup(...)

这种方式简单直接,适合大多数常规场景,若有自定义构建命令,只需补充到SKIP_COMMANDS集合中即可。

方法二:重写Install命令钩子

利用setuptools的命令扩展机制,仅在执行install命令前触发检查,更精准地控制执行时机:

import sys
from setuptools import setup
from setuptools.command.install import install

class CustomInstall(install):
    def run(self):
        # 先执行SDK检查逻辑
        try:
            import pyzed.sl
        except ImportError:
            print("ERROR: You must manually install the ZED Python SDK first.")
            sys.exit(1)

        zed_version = [int(p) for p in pyzed.sl.Camera.get_sdk_version().split(".")]
        if zed_version < [4, 0, 8]:
            print("ERROR: ZED SDK 4.0.8 or higher is required, you must update the ZED SDK first.")
            sys.exit(1)
        
        # 执行原生的安装流程
        super().run()

setup(
    ...,
    cmdclass={'install': CustomInstall}
)

这种方式完全遵循setuptools的扩展规范,只有在执行install命令时才会触发检查,不会受其他构建命令影响,可靠性更高。

补充说明

如果你的包需要支持wheel安装(pip install从wheel包安装时,setup.py不会被执行),若仍需在安装时检查SDK,可考虑在包的__init__.py中加入检查逻辑,但这样会在每次导入包时触发检查。如果仅需在安装阶段检查,上述两种方法已能满足源码安装和从本地源码构建后安装的场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 00:33:31