简体   繁体   English

使用python替换protobuf文件中的行

[英]Replace lines in a protobuf file using python

I have an existing proto file that I would like to change. 我有一个要更改的现有原始文件。 What I would like to do is read the file in, change a value or two, and then write it back out to disk as a .proto file, to be read by another program. 我想做的是读入文件,更改一个或两个值,然后将其作为.proto文件写回到磁盘,以供其他程序读取。 According to this documentation , I should be able to write something like this: 根据本文档 ,我应该能够编写如下内容:

from google.protobuf import message

msg = message.Message()
msg.ParseFromString(infile.read())

... (make changes)

outfile.write(msg.SerializeToString())

But it just gives me a NotImplementedError . 但这只是给我一个NotImplementedError Where is the library I need to interface with protobuf text files? 我需要在哪里与protobuf文本文件接口的库? This seems to work for C++, why hasn't it been implemented for python? 似乎适用于C ++,为什么还没有为python实现呢? (No, the functions in google.protobuf.text_format aren't implemented either). (不,google.protobuf.text_format中的函数也未实现)。

You seem to be confusing several different concepts here. 您似乎在这里混淆了几个不同的概念。

message.Message is an abstract base class. message.Message是一个抽象基类。 You need to construct an instance of the specific derived class you're interested in. 您需要构造您感兴趣的特定派生类的实例。

.proto files contain type definitions, not message data. .proto文件包含类型定义,而不是消息数据。 You must compile your .proto file using protoc , the Protocol Compiler. 你必须编译.proto使用文件protoc ,该协议编译器。 It will generate Python code which you can then import into your program in order to construct the specific type you want. 它将生成Python代码,然后可以将其导入到程序中以构造所需的特定类型。 Please see the Protobuf tutorial for details. 有关详细信息,请参见Protobuf教程

Use ParseFromString() to parse binary protobuf data from a file, and use SerializeToString() to convert the message back into binary data. 使用ParseFromString()解析文件中的二进制 protobuf数据,并使用SerializeToString()将消息转换回二进制数据。 You should almost always use binary format for protobuf data. 您几乎应该始终将二进制格式用于protobuf数据。

The TextFormat class you reference implements an alternative encoding of protobufs that is human-readable. 您引用的TextFormat类实现了人类可读的protobuf的替代编码。 This format is not recommended for most use cases. 在大多数使用情况下, 建议使用此格式。 If you want a human-readable format, you may be better off with JSON, but it will always be much slower and less-compact than binary encodings. 如果您想要一种人类可读的格式,使用JSON可能会更好,但是与二进制编码相比,它总是更慢,更紧凑。 TextFormat is occasionally useful for debugging (printing out a message) and sometimes for writing message data as source code. TextFormat有时对于调试(打印消息)很有用,有时对于将消息数据写为源代码也很有用。 TextFormat is available in the Python library as the text_format module . TextFormat在Python库中作为text_format模块提供

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

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