Created
January 7, 2019 22:11
-
-
Save rgov/91cf2162cf4b73405c703901c2e41b42 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
''' | |
I was playing around with dynamically compiling and loading protobuf files. This kind of works, | |
so I wanted to save it for later. | |
I guess what I would want it to do is create a container object representing the message and enum | |
descriptors that allows you to access them as normal attributes. | |
Alternatively you can have protoc output a .py file and then fuss around with importlib to load it. | |
''' | |
import os | |
import subprocess | |
import tempfile | |
from google.protobuf.descriptor import MakeDescriptor | |
from google.protobuf.descriptor_pb2 import FileDescriptorSet | |
from google.protobuf.reflection import MakeClass | |
def compile_proto(proto): | |
with tempfile.NamedTemporaryFile(mode='w') as infile: | |
with tempfile.NamedTemporaryFile(mode='rb') as outfile: | |
infile.write(proto) | |
infile.flush() | |
subprocess.check_call(['protoc', '-o', outfile.name, | |
'--proto_path', os.path.dirname(infile.name), infile.name]) | |
return outfile.read() | |
proto = compile_proto(''' | |
syntax = "proto2"; | |
message Foo { } | |
''') | |
fds = FileDescriptorSet.FromString(proto) | |
file_descriptor = fds.file | |
msg_descriptor = MakeDescriptor(file_descriptor[0].message_type[0]) | |
msg_class = MakeClass(msg_descriptor) | |
msg = msg_class() | |
print(msg) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment