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

Bazel中跨外部仓库运行时访问数据文件的路径如何获取?

正确访问方式分两种,推荐优先用第一种兼容性更强的方案:

方案1:使用Bazel官方Runfiles工具(推荐)

该方案不需要硬拼接路径,自动兼容--nolegacy_external_runfiles等参数配置,也适配bazel run、bazel test、直接部署二进制等不同运行场景:

  1. 先修改foo/BUILD.bazel,引入runfiles依赖:
py_binary(
    name = "foo",
    srcs = ["foo.py"],
    data = [
        "local-data.txt",
        "@data//:data"
    ],
    # 新增runfiles依赖
    deps = ["@bazel_tools//tools/python/runfiles:runfiles"],
)
  1. 修改foo.py代码,通过runfiles定位文件路径:
import os
from bazel_tools.tools.python.runfiles import runfiles

def dump_file(file_path):
    print(file_path + ":")
    with open(file_path) as file:
        print(file.read())

def main():
    r = runfiles.Create()
    data_files = [
        'local-data.txt',
        # 路径格式为「外部仓库名/文件在外部仓库内的相对路径」
        r.Rlocation("data/external-data.txt")
    ]
    for file in data_files:
        dump_file(file)
    print("cwd: " + os.getcwd())
if __name__ == "__main__":
    main()

方案2:硬拼接相对路径(仅适配你当前的参数配置)

你使用了--nolegacy_external_runfiles参数时,外部依赖的文件会存放在runfiles根目录的external/路径下,你当前运行时的cwd是foo.runfiles/__main__,只需向上跳转一级就能到达runfiles根目录,所以可以直接写相对路径:

'../external/data/external-data.txt'

或者更稳妥的写法:

os.path.join(os.path.dirname(os.getcwd()), "external/data/external-data.txt")

注意:你之前找到的很长的相对路径是软链接指向的物理文件地址,不需要直接使用,访问runfiles目录下的软链接路径即可正常读取文件。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 02:15:03