N M*_*N M 6 protocol-buffers python-3.x
我有一个为 python 2 编译的谷歌协议缓冲区,我正在尝试将它移植到 python 3。不幸的是,我在任何地方都找不到我用来生成编译的协议缓冲区的 proto 文件。如何恢复 proto 文件,以便我可以为 python 3 编译一个新文件。我不知道使用了哪些 proto 版本,我所拥有的只是要在 python 2.6 上运行的 .py 文件。
您必须编写代码(例如使用 Python)来遍历消息描述符树。原则上,它们应该包含原始原型文件的完整信息(代码注释除外)。您仍然拥有的生成的 Python 模块应该允许您将原始文件的文件描述符序列化为文件描述符原始消息,然后可以将其提供给将其表达为原始代码的代码。
作为指导,您应该研究 protoc 的各种代码生成器,它们实际上执行相同的操作:它们将文件描述符作为 protobuf 消息读取,分析它并生成代码。
这里基本介绍了如何用Python编写Protobuf插件
https://www.expobrain.net/2015/09/13/create-a-plugin-for-google-protocol-buffer/
这是 protoc 插件的官方列表
https://github.com/google/protobuf/blob/master/docs/third_party.md
这是一个用 Python 编写的用于生成 LUA 代码的协议插件。
https://github.com/sean-lin/protoc-gen-lua/blob/master/plugin/protoc-gen-lua
我们看一下主要代码块
def main():
plugin_require_bin = sys.stdin.read()
code_gen_req = plugin_pb2.CodeGeneratorRequest()
code_gen_req.ParseFromString(plugin_require_bin)
env = Env()
for proto_file in code_gen_req.proto_file:
code_gen_file(proto_file, env,
proto_file.name in code_gen_req.file_to_generate)
code_generated = plugin_pb2.CodeGeneratorResponse()
for k in _files:
file_desc = code_generated.file.add()
file_desc.name = k
file_desc.content = _files[k]
sys.stdout.write(code_generated.SerializeToString())
Run Code Online (Sandbox Code Playgroud)
该循环for proto_file in code_gen_req.proto_file:实际上循环遍历 protoc 要求代码生成器插件生成 LUA 代码的文件描述符对象。所以现在你可以这样做:
# This should get you the file descriptor for your proto file
file_descr = your_package_pb2.sometype.GetDescriptor().file
# serialized version of file descriptor
filedescr_msg = file_descr.serialized_pb
# required by lua codegen
env = Env()
# create LUA code -> modify it to create proto code
code_gen_file(filedescr, env, "your_package.proto")
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2057 次 |
| 最近记录: |