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 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c