[英]Bazel: Make genrule outputs available to another rule
我需要某个genrule
的输出在另一个规则旁边可用。 (即py_binary
)。
假设我们有以下文件:
# root/gen/BUILD:
genrule(
name = "gen",
outs = ["a.txt", "a2.txt"],
cmd = "cd $(RULEDIR) && echo salam > a.txt && echo hello > a2.txt",
)
# root/BUILD:
py_binary(
name = "use",
srcs = ["use.py"],
data = ["gen:a.txt", "gen:a2.txt"],
)
# use.py:
f = open("a.txt", "r")
f2 = open("a2.txt", "r")
print(f.read())
print(f2.read())
乍看上去:
project
├── root
│ ├── BUILD
│ ├── gen
│ │ └── BUILD << This can generate required 'a.txt' and 'a2.txt'
| | files.
│ └── use.py << This script needs to access a.txt file as './a.txt',
| but with 'bazel run root:use' it should access files
| like 'root/gen/a.txt'.
└── WORKSPACE
当我运行bazel run :use
,找不到文件:
FileNotFoundError: [Errno 2] No such file or directory: 'a.txt'
它需要在附近具有a.txt
和a2.txt
文件,但它们位于bazel-bin/gen
目录中。
您可以在genrule
设置output_to_bindir ,以便将输出文件写入bazel-bin
目录而不是bazel-genfiles
目录,然后使用工作空间中的相对路径在use.py
引用它们,例如:
# root/gen/BUILD
genrule(
name = "gen",
...
output_to_bindir = True,
)
# use.py:
f = open("root/gen/a.txt", "r")
f2 = open("root/gen/a2.txt", "r")
print(f.read())
print(f2.read())
当通过bazel run
时,这应该允许应用程序加载文件。
如果您无法修改py_binary中的代码,则可以编写一个genrule来创建到另一个文件的链接,例如:
genrule(
name = "link_a.txt",
srcs = ["//gen/a.txt"]
outs = ["a.txt"],
cmd = "ln $< $@"
)
genrule(
name = "link_a2.txt",
srcs = ["//gen/a2.txt"]
outs = ["a2.txt"],
cmd = "ln $< $@"
)
( $<
是“只有一个输入文件的路径的快捷方式”,类似地, $@
是“只有一个输入文件的路径的快捷方式”)
如果需要,也可以将类型规则包装在可重用的宏中,或者在Starlark中执行更奇特的操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.