简体   繁体   English

python protobuf无法反序列化消息

[英]python protobuf can't deserialize message

Getting started with protobuf in python I face a strange issue: 在Python中使用protobuf入门,我遇到一个奇怪的问题:

a simple message proto definition is: 一个简单的消息原型定义是:

syntax = "proto3";
package test;

message Message {
  string message = 1;
  string sender = 2;
}

generated via protoc -I . --python_out=generated message.proto 通过protoc -I . --python_out=generated message.proto生成protoc -I . --python_out=generated message.proto protoc -I . --python_out=generated message.proto and accessed in Python like: protoc -I . --python_out=generated message.proto并在Python中进行访问,例如:

from generated.message_pb2 import Message

Then I can construct a message 然后我可以构造一条消息

m = Message()
m.sender = 'foo'
m.message = 'bar'

print(str(m))

but de-serializing will not return a result 但反序列化不会返回结果

s_m = m.SerializeToString()
print(s_m) # prints fine
a = m.ParseFromString(s_m)
a.foo #fails with error - no attributes deserialized

Instead of 代替

a = m.ParseFromString(s_m)
a.foo

do this 做这个

a = m.FromString(s_m)
print a.sender

alternatively you can do this 或者,您可以这样做

m2 = Message()
m2.ParseFromString(s_m)
print m2.sender

The difference is that FromString returns a new object deserialized from the string whereas ParseFromString parses the string and sets the fields on the object. 区别在于FromString返回从字符串反序列化的新对象,而ParseFromString解析字符串并设置对象上的字段。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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