如何在Bazel的py_wheel规则中读取requirements.txt作为依赖参数
Bazel py_wheel自动读取requirements.txt依赖的实现方法
有两种成熟的实现方案:
方法1:配合rules_python的pip_parse流程使用(推荐)
无需额外自定义逻辑,直接复用rules_python自带的依赖解析能力即可:
- 首先在WORKSPACE文件中完成pip依赖加载配置:
load("@rules_python//python:pip.bzl", "pip_parse") pip_parse( name = "pip_deps", requirements = "//:requirements.txt", # 替换为你自己的requirements.txt路径 ) load("@pip_deps//:requirements.bzl", "install_deps", "all_requirements") install_deps()
- 到声明py_wheel的BUILD文件中,直接导入解析好的依赖列表使用:
load("@pip_deps//:requirements.bzl", "all_requirements") load("@rules_python//python:packaging.bzl", "py_wheel") py_wheel( name = "dummy", distribution = "dummy", python_tag = "py3", version = "latest", entry_points={"console_scripts": ["dummy = dummy.app:main"]}, requires = all_requirements, deps = [":dummy-dependencies"], )
如果需要过滤不需要打包进依赖的条目,可以自行加过滤逻辑:
def get_filtered_reqs(): # 示例:过滤掉所有内部私有依赖 return [req for req in all_requirements if not req.startswith("internal-")] py_wheel( # 其余配置不变 requires = get_filtered_reqs(), )
方法2:自定义Starlark函数直接读取requirements.txt
如果你不需要用到pip_parse的依赖安装能力,只想单纯解析requirements.txt的内容,可以自己实现简单的解析函数:
- 新建
parse_requirements.bzl文件,写入以下内容:
def parse_requirements(req_file): reqs = [] content = read(req_file) for line in content.splitlines(): line = line.strip() # 跳过空行、注释行 if not line or line.startswith("#"): continue # 处理行尾注释 if "#" in line: line = line.split("#")[0].strip() reqs.append(line) return reqs
- 在BUILD文件中导入函数使用即可,注意要把requirements.txt声明为构建依赖,避免修改后不触发重新构建。
注意事项
- 若使用Bzlmod(Bazel 6+ 模块系统),只需将对应导入逻辑适配为模块语法即可,核心逻辑不变,依然是从pip解析生成的
requirements.bzl中获取all_requirements列表。 - requirements.txt中带环境标记的依赖(例如
pywin32; sys_platform == "win32")可以直接被py_wheel的requires参数原生支持,不需要额外处理。
内容的提问来源于stack exchange,提问作者randomperson
相关产品推荐
相关产品推荐

