dongzhan2029 2019-01-01 00:23
浏览 327
已采纳

无法打开应该在基本路径中的文件

I have a Go project (bazel-remote) that tries to read a yaml file passed in the command line, when built with bazel. This yaml file sits in the same location from where I run the bazel run command.

But it fails to run because os.Open fails with no such file or directory.

I printed the basePath using os.Getwd, because someone suggested that my basePath might be set wrong. But my basePath is set to a location in my /private/var/tmp/ where the bazel objects are created and stored:

/private/var/tmp/bazel/312feba8ddcde6737ae7dd7ef9bc2a5a/execroot/main/bazel-out/darwin-fastbuild/bin/darwin_amd64_static_pure_stripped/bazel-remote.runfiles/main'

How do I set my basePath correctly? Why is my basePath set to where it is?

  • 写回答

1条回答 默认 最新

  • drq9991 2019-01-02 17:54
    关注

    Binaries started with bazel run are executed in an internal Bazel directory. They'll have access to "runfiles", which are files mentioned in the data attribute of the binary rule or its dependencies. For example, if you have a rule like the one below, you'll be able to read foo.txt, but not bar.txt or other files:

    load("@io_bazel_rules_go//go:def.bzl", "go_binary")
    
    go_binary(
        name = "hello",
        srcs = ["hello.go"],
        data = ["foo.txt"],
    )
    

    Note that the working directory of the binary corresponds to the repository root directory, not the directory where the binary is defined. You can debug with os.Getwd and filepath.Walk.

    You mentioned you wanted to access a yaml file passed in on the command line though. Presumably, you want to be able to access any file the user passes in, not just files mentioned in the data attribute. For this case, take a look at the BUILD_WORKING_DIRECTORY environment variable (bazel run sets this). That gives the path to the directory where bazel run was invoked. Also, BUILD_WORKSPACE_DIRECTORY is the path to the workspace root directory.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何实现H5在QQ平台上的二次分享卡片效果?
  • ¥15 python爬取bilibili校园招聘网站
  • ¥30 求解达问题(有红包)
  • ¥15 请解包一个pak文件
  • ¥15 不同系统编译兼容问题
  • ¥100 三相直流充电模块对数字电源芯片在物理上它必须具备哪些功能和性能?
  • ¥30 数字电源对DSP芯片的具体要求
  • ¥20 antv g6 折线边如何变为钝角
  • ¥30 如何在Matlab或Python中 设置饼图的高度
  • ¥15 nginx中的CORS策略应该如何配置