python-3.x - 如何将已编译的 Protocol Buffer 转换回 .proto 文件?

标签 python-3.x protocol-buffers

我有一个为 python 2 编译的 google Protocol Buffer ,我正在尝试将它移植到 python 3。不幸的是,我在任何地方都找不到用于生成已编译 Protocol Buffer 的 proto 文件。如何恢复 proto 文件以便为 python 3 编译一个新文件。我不知道使用了哪些 proto 版本,我所拥有的只是要在 python 2.6 上运行的 .py 文件。

最佳答案

您将不得不编写代码(例如在 Python 中)来遍历您的消息描述符树。原则上,它们应该包含原始 proto 文件的全部信息,但代码注释除外。并且您仍然拥有的生成的 Python 模块应该允许您将 proto 文件的文件描述符序列化为文件描述符 proto 消息,然后可以将其馈送到将其表示为 proto 代码的代码。

作为指南,您应该查看 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 代码的 protoc 插件。

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())

循环 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")

关于python-3.x - 如何将已编译的 Protocol Buffer 转换回 .proto 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47669184/

相关文章:

python-3.x - 运行时错误 : module compiled against API version 0xe but this version of numpy is 0xd when importing sentence-transformers

python - 读取 csv 标题空白和不区分大小写

python-3.x - 使用 Python 从网站请求中获取完整的 html

Python 创建一个设定大小的 numpy 数组

flutter - 我们应该以什么方式将带有 oneof 的原始消息映射到带有干净代码的数据类

protobuf-net 保留 future 领域

c++ - 在 mac os 上执行程序时 libprotobuf 检查失败

Android protobuf-lite toString 不工作

python - 大多数 pythonic3 dezip(?) 实现

request - 根据我的请求设置日期值时,Google Protocol Buffers : c. toArray 不是一个函数