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

如何从requirements.txt动态为Bazel的py_wheel传递requires属性

从requirements.txt自动生成py_wheel的requires依赖列表

可以通过Bazel的genrule配合简单脚本实现自动转换,避免重复维护依赖,具体步骤如下:

1. 编写依赖转换脚本

创建parse_requirements.py脚本,负责把requirements.txt内容转换成Bazel py_wheel所需的字符串列表格式:

#!/usr/bin/env python3
import sys

def main():
    with open(sys.argv[1], 'r') as f:
        lines = f.readlines()
    
    requires = []
    for line in lines:
        line = line.strip()
        # 跳过注释、空行
        if not line or line.startswith('#'):
            continue
        # 保留PEP 508格式的依赖声明,转成带引号的字符串
        requires.append(f'"{line}"')
    
    # 输出为Bazel可识别的列表格式
    print(f'REQUIRES = [{", ".join(requires)}]')

if __name__ == '__main__':
    main()

2. 用genrule生成依赖列表文件

在BUILD文件中添加genrule,调用脚本生成包含依赖列表的.bzl文件:

genrule(
    name = "generate_requires",
    srcs = ["requirements.txt"],
    outs = ["requires.bzl"],
    cmd = "$(location parse_requirements.py) $(SRCS) > $@",
    tools = ["parse_requirements.py"],
)

3. 在py_wheel中引用生成的依赖列表

在需要构建wheel的BUILD文件里,加载生成的requires.bzl并传入py_wheel的requires属性:

# 加载自动生成的依赖列表
load(":requires.bzl", "REQUIRES")

py_wheel(
    name = "my_package_wheel",
    distribution = "my-package",
    version = "0.1.0",
    srcs = glob(["src/**/*.py"]),
    # 直接使用生成的依赖列表
    requires = REQUIRES,
)

补充说明

  • 脚本会自动跳过requirements.txt中的注释和空行,保留符合PEP 508格式的依赖声明(包括带环境标记的行,比如requests==2.31.0 ; python_version >= "3.7")
  • pip_parse生成的是Bazel构建时的依赖目标,而py_wheel的requires需要的是wheel安装时的PEP 508依赖字符串,两者用途和格式完全不同,因此无法直接复用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 04:32:23