简体   繁体   中英

How to extract field value from protobuf/python object

Using proto3 syntax I am using the protobuf protocol to generate messages and I am programmatically parsing them via python3. Is there some API or method to extract the value in specific fields and manipulate them/do further calculations?

Take the following message as an example.

message File {
         bytes  data =1;
} 

If I want to get the size of the bytestring and run len(msg.file.data) I get the error message object of type 'File' has no len() which is valid because the object File has no such method built-in, so how do I extract the bytes as bytes only independent from the object?

message FileTransfer {
  File file = 1;
}

This defines a new message called FileTransfer that has a single field called file of type File. You could then use the FileTransfer message to send a file over a.network connection or to store a file in a database.

To get the length of the bytes field in the File message, you can use the len() function as follows:

file_message = File() file_message.data = b'Hello, world!'

length = len(file_message.data)

print(length) # prints "12"

The len() function returns the number of bytes in the bytes field. In this case, it would return 12, since the bytes field contains the string b'Hello, world,'. which has a length of 12 bytes.

You can also access the individual bytes in the bytes field using indexing. For example:

first_byte = file_message.data[0]

second_byte = file_message.data[1]

print(first_byte) # prints "72" print(second_byte) # prints "101"

This would print the ASCII codes for the first and second bytes of the bytes field, which are the ASCII codes for the letters 'H' and 'e' respectively.

You can also slice the bytes field to get a sub-sequence of bytes. For example:`subsequence = file_message.data[1:4]

print(subsequence) # prints "b'ell'"`

This would return a bytes object containing the bytes b'ell', which are the second, third, and fourth bytes of the original bytes field.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM