Created
July 14, 2019 06:15
-
-
Save justinfx/c2b1458ea2ddab8faf635cacd140ad2d to your computer and use it in GitHub Desktop.
Dynamically reading a Protobuf FileDescriptorSet file into Python message classes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
""" | |
Read a serialized Protobuf FileDescriptorSet that was | |
generated from the protoc tool, and dynamically generate | |
the python classes for each message. | |
""" | |
import sys | |
from google.protobuf import descriptor_pb2 | |
from google.protobuf import reflection | |
from google.protobuf import symbol_database | |
def gen(desc_file, db=None): | |
if not db: | |
db = symbol_database.Default() | |
with open(desc_file, 'rb') as fh: | |
fds = descriptor_pb2.FileDescriptorSet.FromString(fh.read()) | |
generated = {} | |
for prot in fds.file: | |
fd = db.pool.Add(prot) | |
for name in fd.message_types_by_name: | |
mdesc = fd.message_types_by_name[name] | |
Klass = reflection.MakeClass(mdesc) | |
generated[(fd.package, name)] = db.RegisterMessage(Klass) | |
return generated | |
if __name__ == '__main__': | |
from pprint import pprint | |
generated = gen(sys.argv[1]) | |
pprint(generated) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment