2015-11-06 147 views

回答

4

如果您使用的是protobuf包,則print函數/語句會爲您提供一個可讀的消息表示,因爲__str__方法:-)。

+0

事實上,這個工程。但是,對於我特定的消息描述,對於某些特定的消息內容,消息被打印爲空字符串,但我認爲這是來自庫的錯誤。 –

1

回答時,print__str__可以工作,但除了調試字符串之外,我不會使用它們。

如果你正在寫一些用戶可以看到的東西,最好使用google.protobuf.text_format模塊,它有更多的控件(例如轉義或不轉義UTF8字符串)以及將文本格式解析爲protobufs的函數。

2

下面是一個讀寫示例人性化的使用protobuf 2.0的文本文件python。從文本文件

f = open('a.txt', 'r') 
address_book = addressbook_pb2.AddressBook() # replace with your own message 
text_format.Parse(f.read(), address_book) 
f.close() 

from google.protobuf import text_format 

讀取到一個文本文件

f = open('b.txt', 'w') 
f.write(text_format.MessageToString(address_book)) 
f.close() 

C++相當於是:

bool ReadProtoFromTextFile(const std::string filename, google::protobuf::Message* proto) 
{ 
    int fd = _open(filename.c_str(), O_RDONLY); 
    if (fd == -1) 
     return false; 

    google::protobuf::io::FileInputStream* input = new google::protobuf::io::FileInputStream(fd); 
    bool success = google::protobuf::TextFormat::Parse(input, proto); 

    delete input; 
    _close(fd); 
    return success; 
} 

bool WriteProtoToTextFile(const google::protobuf::Message& proto, const std::string filename) 
{ 
    int fd = _open(filename.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0644); 
    if (fd == -1) 
     return false; 

    google::protobuf::io::FileOutputStream* output = new google::protobuf::io::FileOutputStream(fd); 
    bool success = google::protobuf::TextFormat::Print(proto, output); 

    delete output; 
    _close(fd); 
    return success; 
}