Search code examples
pythonprotocol-buffers

Reading protobuf Message file in Python


I have a pb file abc.pb file.

I need to read the file by retaining its format i.e. dont want to convert pb file to string and then again reconverting it.

Currently I m trying options with

    with open(data, "rb") as file_handle:
        data = file_handle.read()

But this converts that into bytes. How to read them as Message. Can someone please help?


Solution

  • Protobuf is a binary encoding and -- generally -- you'll use a schema (types) to decode messages.

    Protobuf types are described in proto files and compiled (using protoc) into langauge-specific stubs that can be used to encode|decode messages.

    See Protocol Buffer Basics: Python which includes an example reading a message.

    There are ways to decode binary files without a schema but it's more challenging.

    So:

    Either: See whether you can obtain the Python stubs for the pb file you're trying to decode

    Or: If you have proto files, use protoc (see example above) to generate the Python stubs

    Or: Use a tool like's Marc's (above) or some other library that will decode encoded arbitary messages for you.