Bazel中py_test依赖含等号文件名时zipper.exe报错求助
在Bazel 7.5.0中,将包含特殊字符=的文件(如equal=.txt或equal = .txt)作为py_test的data依赖传入时,执行构建会触发zipper.exe报错提示文件不存在,但文件实际存在。将=替换为+则可正常运行。根据Bazel文档,目标名称允许包含等号,需明确问题原因及无需修改文件名的解决方案。
最小复现示例
BUILD文件
py_test( name = "bazel_char_test", srcs = ["bazel_char_test.py"], data = ["equal.txt"]+["equal = .txt"], )
错误信息
ERROR: C:/path/BUILD:31:8: Building Python zip: //project_path:bazel_char_test failed: (Exit -1): zipper.exe failed: error executing PythonZipper command (from target //project_path:bazel_char_test) external\bazel_tools\tools\zip\zipper\zipper.exe cC bazel-out/x64_windows-fastbuild/bin/project_path/bazel_char_test.zip ... (remaining 1 argument skipped)
File .txt=project_path/equal = .txt does not seem to exist.Target //project_path:bazel_char_test failed to build
这是因为Bazel的zipper.exe工具在处理文件名中的=时,会错误地将其解析为zip条目重命名的分隔符(格式为目标文件名=源文件名)。当文件名包含=时,工具会把=前的部分当作目标zip内的文件名,=后的部分当作源文件路径,导致路径解析混乱,最终找不到实际文件。
可以通过以下两种方式规避这个问题:
使用
data的字典格式指定映射:在data中用字典明确指定源文件和zip内的目标文件名,避免zipper误解析=:py_test( name = "bazel_char_test", srcs = ["bazel_char_test.py"], data = { "equal.txt": "equal.txt", "equal = .txt": "equal = .txt" # 明确映射,避免分隔符误解析 }, )通过
py_runtime禁用zip打包:如果不需要将测试代码打包为zip,可以配置py_runtime并设置zip属性为False,让Bazel直接使用文件目录而非zip包,绕开zipper的处理逻辑:- 在项目根目录创建
python_runtime.bzl文件:def _python_runtime_impl(ctx): return [platform_common.ToolchainInfo( python_interpreter_path = ctx.attr.python_interpreter_path, zip = False, )] python_runtime = rule( implementation = _python_runtime_impl, attrs = { "python_interpreter_path": attr.string(mandatory = True), }, ) - 在
WORKSPACE或BUILD中注册该工具链:load("//:python_runtime.bzl", "python_runtime") python_runtime( name = "python_no_zip", python_interpreter_path = "python", # 替换为你的Python解释器路径 ) toolchain( name = "python_toolchain", toolchain = ":python_no_zip", toolchain_type = "@bazel_tools//tools/python:toolchain_type", ) - 构建时指定使用该工具链:
bazel test //project_path:bazel_char_test --python_toolchain=//:python_toolchain
- 在项目根目录创建
内容的提问来源于stack exchange,提问作者Gelsengamer

