python protobuf无法反序列化消息 [英] python protobuf can't deserialize message

查看:67
本文介绍了python protobuf无法反序列化消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 python 中开始使用 protobuf 我遇到了一个奇怪的问题:

Getting started with protobuf in python I face a strange issue:

一个简单的消息原型定义是:

a simple message proto definition is:

syntax = "proto3";
package test;

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

通过 protoc -I 生成.--python_out=generated message.proto 并在 Python 中访问,如:

generated via protoc -I . --python_out=generated message.proto and accessed in Python like:

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

推荐答案

代替

a = m.ParseFromString(s_m)
a.foo

这样做

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

或者你可以这样做

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

区别在于 FromString 返回从字符串反序列化的新对象,而 ParseFromString 解析字符串并设置对象上的字段.

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.

这篇关于python protobuf无法反序列化消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆