README.md
1# bazel-runfiles library
2
3This is a Bazel Runfiles lookup library for Bazel-built Python binaries and tests.
4
5Learn about runfiles: read [Runfiles guide](https://bazel.build/extending/rules#runfiles)
6or watch [Fabian's BazelCon talk](https://www.youtube.com/watch?v=5NbgUMH1OGo).
7
8## Importing
9
10The Runfiles API is available from two sources, a direct Bazel target, and a [pypi](https://pypi.org/) package.
11
12## Pure Bazel imports
13
141. Depend on this runfiles library from your build rule, like you would other third-party libraries:
15
16 ```python
17 py_binary(
18 name = "my_binary",
19 # ...
20 deps = ["@rules_python//python/runfiles"],
21 )
22 ```
23
242. Import the runfiles library:
25
26 ```python
27 from python.runfiles import Runfiles
28 ```
29
30## Pypi imports
31
321. Add the 'bazel-runfiles' dependency along with other third-party dependencies, for example in your `requirements.txt` file.
33
342. Depend on this runfiles library from your build rule, like you would other third-party libraries:
35 ```python
36 load("@pip_deps//:requirements.bzl", "requirement")
37
38 py_binary(
39 name = "my_binary",
40 ...
41 deps = [requirement("bazel-runfiles")],
42 )
43 ```
44
453. Import the runfiles library:
46 ```python
47 from runfiles import Runfiles
48 ```
49
50## Typical Usage
51
52Create a `Runfiles` object and use `Rlocation` to look up runfile paths:
53
54```python
55r = Runfiles.Create()
56# ...
57with open(r.Rlocation("my_workspace/path/to/my/data.txt"), "r") as f:
58 contents = f.readlines()
59 # ...
60```
61
62The code above creates a manifest- or directory-based implementation based on the environment variables in `os.environ`. See `Runfiles.Create()` for more info.
63
64If you want to explicitly create a manifest- or directory-based
65implementation, you can do so as follows:
66
67```python
68r1 = Runfiles.CreateManifestBased("path/to/foo.runfiles_manifest")
69
70r2 = Runfiles.CreateDirectoryBased("path/to/foo.runfiles/")
71```
72
73If you want to start subprocesses, and the subprocess can't automatically
74find the correct runfiles directory, you can explicitly set the right
75environment variables for them:
76
77```python
78import subprocess
79from python.runfiles import Runfiles
80
81r = Runfiles.Create()
82env = {}
83# ...
84env.update(r.EnvVars())
85p = subprocess.run(
86 [r.Rlocation("path/to/binary")],
87 env=env,
88 # ...
89)
90```
91