我有两个带有 python 代码的 git 存储库。
https://github.com/SurferJeffAtGoogle/synthtool/tree/bazel包含两个构建目标:
~/gitrepos/synthtool$ bazel query ...
//tests:synthtool_test
//synthtool:synthtool
https://github.com/SurferJeffAtGoogle/nodejs-vision/tree/bazel包含一个构建目标:
~/gitrepos/nodejs-vision$ bazel query ...
//:synth
//tests:synthtool_test
和 //:synth
都依赖于 //synthtool:synthtool
。
我可以运行测试并且测试代码成功导入synthtool
:
~/gitrepos/synthtool$ bazel test ...
INFO: Analyzed 2 targets (4 packages loaded, 230 targets configured).
INFO: Found 1 target and 1 test target...
INFO: Elapsed time: 7.477s, Critical Path: 7.07s
INFO: 2 processes: 2 linux-sandbox.
INFO: Build completed successfully, 3 total actions
//tests:synthtool_test PASSED in 7.0s
Executed 1 out of 1 test: 1 test passes.
但是,当我尝试运行 //:synth
时,它无法导入 synthtool
:
~/gitrepos/nodejs-vision$ bazel run //:synth
Starting local Bazel server and connecting to it...
INFO: Analyzed target //:synth (17 packages loaded, 272 targets configured).
INFO: Found 1 target...
INFO: Deleting stale sandbox base /usr/local/google/home/rennie/.cache/bazel/_bazel_rennie/dadb642c5feb5ae86ab3
1dcb8a48c54a/sandbox
Target //:synth up-to-date:
bazel-bin/synth
INFO: Elapsed time: 2.555s, Critical Path: 0.03s
INFO: 0 processes.
INFO: Build completed successfully, 1 total action
INFO: Build completed successfully, 1 total action
Traceback (most recent call last):
File "/usr/local/google/home/rennie/.cache/bazel/_bazel_rennie/dadb642c5feb5ae86ab31dcb8a48c54a/execroot/nodejs_vision/bazel-out/k8-fastbuild/bin/synth.runfiles/nodejs_vision/synth.py", line 18, in <module>
import synthtool.gcp as gcp
ModuleNotFoundError: No module named 'synthtool.gcp'
rennie@rennie:~/gitrepos/nodejs-vision$
两个目标都有完全相同的代码行:
import synthtool.gcp as gcp
测试成功,但//:synth 失败。
我看到正确的文件被获取并最终出现在 blaze 输出目录中,但 Synth.py 无法导入它们:
~/gitrepos/nodejs-vision$ find -L bazel-* -name gcp
bazel-bin/synth.runfiles/nodejs_vision/external/synthtool/synthtool/gcp
bazel-bin/synth.runfiles/synthtool/synthtool/gcp
bazel-nodejs-vision/external/synthtool/synthtool/gcp
bazel-nodejs-vision/bazel-out/k8-fastbuild/bin/synth.runfiles/nodejs_vision/external/synthtool/synthtool/gcp
bazel-nodejs-vision/bazel-out/k8-fastbuild/bin/synth.runfiles/synthtool/synthtool/gcp
bazel-out/k8-fastbuild/bin/synth.runfiles/nodejs_vision/external/synthtool/synthtool/gcp
bazel-out/k8-fastbuild/bin/synth.runfiles/synthtool/synthtool/gcp
这是为什么呢?我该如何修复它?
最佳答案
这看起来像是存储库名称 (@synthtool
) 隐藏包名称 (//synthtool
) 的实例。失败目标的运行文件树如下所示:
<runfiles>/synthtool/synthtool/foo.py
^ ^ ^ ^
root | | |
repo root | |
package |
modules
Python 规则将每个存储库根以及运行文件根本身添加到 PYTHONPATH
中。 (例如,参见 #7067 。)这意味着上面的第一个和第二个路径片段都在您的 PYTHONPATH
上。您希望导入合成工具相对于存储库根进行解析,以便它获取包,但它却相对于运行文件根进行解析,因此它尝试导入存储库根。
您应该能够通过重命名包和/或存储库来缓解这种情况。
关于Python 无法从 bazel git_repository() 依赖项导入包,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60085724/