我不明白谷歌 Python protobuf 文档中关于软件包的最后一句的第一部分:
The
.proto
file starts with a package declaration, which helps to prevent naming conflicts between different projects. In Python, packages are normally determined by directory structure, so the package you define in your.proto
file will have no effect on the generated code. However, you should still declare one to avoid name collisions in the Protocol Buffers name space as well as in non-Python languages.
在 Python 中(可能因此在确实使用命名空间的语言中)“您在
.proto
文件中定义的包对生成的代码没有影响”实际上是错误的,因为生成的 ..._pb2.py
文件包含具有包字段的描述符。DESCRIPTOR = _descriptor.FileDescriptor(
name='example.proto',
package='example',
syntax='proto3',
...
)
我查过了,你不能
import example
生成代码后进入一个普通的python文件。即声明 package example;
在您的 .proto
文件,然后 protoc
编译它不会自动使您的包可用于在您的环境中的 python 文件中导入(您仍然必须使用 import ..._pb2
来访问这些类)。任何人都可以解释如何在
.proto
中声明包文件在 Python 和 C# 中都使用,作为明确使用命名空间的语言的一个例子?
最佳答案
引用文档本身:
In Python, the package directive is ignored, since Python modules are organized according to their location in the file system.
那么包声明到底有什么用呢?
我相信两件事:
Foo
在 package bar
下定义和 package baz
两个都;然后使用 bar.Foo
和 baz.Foo
任何需要的地方。Foo
在上面的例子中,一个名为 Foo
的消息类型将在 bar
的命名空间中声明和 baz
.您使用 Python 应用程序创建的 proto 文件可以以几乎相同的方式为您的 C# 应用程序编译。需要注意的是,Protobuf 是用于序列化和反序列化数据的语言不可知机制。话虽如此,我个人并没有发现在我的 Python 应用程序的 protobuf 消息中使用包说明符。
引用:https://developers.google.com/protocol-buffers/docs/proto
关于c# - protobuf 包是如何使用的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54434747/