简体   繁体   中英

Access to google protobuf files in python (easy)

I read message from a protobuf file. The message contains time-series data, thus, I expected matrix-like structure, eg, processed_row[nData,nVar]

print(mySerializedData.processed_row)
>> [timestamp: 0.0
linear_acc_x: 0.288501300049
linear_acc_y: 0.573411297607
linear_acc_z: 0.161608612061
, timestamp: 0.0049
linear_acc_x: 0.428562097168
linear_acc_y: 0.685938775635
linear_acc_z: 0.221463653564
, timestamp: 0.01
linear_acc_x: 0.45968671875
linear_acc_y: 0.738611212158
linear_acc_z: 0.185550628662]

I can access to the individual datum like

print(mySerializedData.processed_row[0].timestamp)
>> 0.0
print(mySerializedData.processed_row[1].timestamp)
>> 0.0049

But what I'd like to obtain is like

print(mySerializedData.processed_row[:].timestamp)

But it shows the error AttributeError: 'list' object has no attribute 'timestamp'

print(type(mySerializedData.processed_row[0].timestamp))
>> <type 'float'>
print(type(mySerializedData.processed_row[0]))
>> <class 'PushCore_pb2.ProcessedDataRow'>

Is there way to get get timestamp double array with like [:]?

Thank you

You can create a list of the timestamp values using a list comprehension :

[element.timestamp for element in mySerializedData.processed_row]

Here's a generalized example. In example.proto :

package example;

message Element {
  required double timestamp = 1;
  required string data = 2;
}

message Container {
  repeated Element elements = 1;
}

Generate the corresponding Python output using:

protoc --python_out=. example.proto

Then, in Python:

>>> from example_pb2 import Container, Element
>>> 
>>> container = Container(
...   elements=[
...     Element(timestamp=.1, data='Some data.'),
...     Element(timestamp=.2, data='Some more data.'),
...   ]
... )
>>> 
>>> [element.timestamp for element in container.elements]
[0.1, 0.2]

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