如果您能提供更多详细信息可能会有所帮助:
- python 代码是如何运行的?它是作为一个动作运行的吗?
-
my_file 目标是什么?
- 你提到你有一些规则。这些 Starlark 规则是你写的吗?
但要直接回答:当使用bazel run 运行二进制文件时,它会在包含二进制文件所有依赖项的符号链接的“运行文件树”中执行。所以你的文件将被放在二进制文件的 runfiles 目录中。
my_program.py:
import os
from pathlib import Path
print("current working directory: " + os.getcwd())
p = Path('my_file.txt')
p.write_text('testing')
print("Testing done")
BUILD:
py_binary(
name = "my_program",
srcs = ["my_program.py"],
)
$ bazel run my_program
INFO: Analyzed target //:my_program (18 packages loaded, 90 targets configured).
INFO: Found 1 target...
Target //:my_program up-to-date:
bazel-bin/my_program
INFO: Elapsed time: 0.226s, Critical Path: 0.01s
INFO: 5 processes: 5 internal.
INFO: Build completed successfully, 5 total actions
INFO: Build completed successfully, 5 total actions
current working directory: /home/ahumesky/.cache/bazel/_bazel_ahumesky/5123c9882cdbb6c5e34f583431173549/execroot/__main__/bazel-out/k8-fastbuild/bin/my_program.runfiles/__main__
Testing done
$ ls /home/ahumesky/.cache/bazel/_bazel_ahumesky/5123c9882cdbb6c5e34f583431173549/execroot/__main__/bazel-out/k8-fastbuild/bin/my_program.runfiles/__main__
external my_file.txt my_program my_program.py
$ cat /home/ahumesky/.cache/bazel/_bazel_ahumesky/5123c9882cdbb6c5e34f583431173549/execroot/__main__/bazel-out/k8-fastbuild/bin/my_program.runfiles/__main__/my_file.txt
testing
如果可能,最好将输出文件路径作为参数传递给程序,以便文件位于某个已知位置:
import sys
from pathlib import Path
p = Path(sys.argv[1])
p.write_text('testing')
print("Testing done")
$ bazel run my_program -- /tmp/output.txt
INFO: Analyzed target //:my_program (0 packages loaded, 0 targets configured).
INFO: Found 1 target...
Target //:my_program up-to-date:
bazel-bin/my_program
INFO: Elapsed time: 0.040s, Critical Path: 0.00s
INFO: 1 process: 1 internal.
INFO: Build completed successfully, 1 total action
INFO: Build completed successfully, 1 total action
Testing done
$ cat /tmp/output.txt
testing
或者,如果你直接运行程序,那么文件将在当前工作目录中:
$ bazel build my_program
INFO: Analyzed target //:my_program (18 packages loaded, 90 targets configured).
INFO: Found 1 target...
Target //:my_program up-to-date:
bazel-bin/my_program
INFO: Elapsed time: 0.219s, Critical Path: 0.01s
INFO: 5 processes: 5 internal.
INFO: Build completed successfully, 5 total actions
$ bazel-bin/my_program
current working directory: /home/ahumesky/test
Testing done
$ cat my_file.txt
testing