Build Python Targets¶
py_library¶
Build a python library from source code
py_library(
name = 'protobuf_util',
srcs = [
'protobuf_util.py'
],
deps = [
':common', # Depends on other python library
]
)
When importing the python module in your code, you need to start writing from the workspace directory. This behavior can be changed through the base attribute, for example:
Change the root path of the module to the directory where the current BUILD file is located.
py_library also supports
- prebuilt=True Mainly used in the zip package.
Example:
srcs is the file name of the python package, there can only be one file, and it supports both whl and egg formats.
py_binary¶
Compile the py source code into an executable file.
Example:
When there are more than one srcs, you need to specify the entry file with the main attribute.
python_binary also support the base attribute.
Output files:
name.zip— a pure zip archive containing all Python sources and dependencies, identical on all platforms.name— the Unix/Linux/macOS shell wrapper that adds the zip toPYTHONPATHand invokespython3 -mwith the entry module.name.bat— the Windows batch wrapper that does the same.
Test targets follow the same output layout as binary targets.
Attributes:
- exclusions: list(str)
When packaging the file into the executable file, the pattern list of the path to be excluded,
note that the path is the path after packaging, which can be viewed through
unzip -l, example:
py_test¶
Compile and run the python test code.
py_test(
name = 'common_test',
srcs = [
'common_test.py'
],
deps = [
':common',
],
testdata = [...],
)
We usually use the unittest library for python unit testing.
Using Protobuf¶
The proto file needs to be described by proto_library, which is introduced in the deps of py_*. The corresponding python protobuf encoding and decoding code will be automatically generated during blade build.
The import path rule in the python code is to start from the workspace root, replace / with .,
and replace the .proto at the end of the file name with _pb2, for example: