Sea*_*123 5 python protocol-buffers python-3.x
我libprotoc 3.2.0在 Python 包中使用Python 3。如果我尝试将 Protobuff Python 文件(用 extensions 表示_pb2.py)放入他们自己的文件夹中,使用这些.proto文件,protobufs然后尝试将它们导入一个 python 文件,如下所示:
# assuming outputs from a.proto and b.proto, where b depends on a
import protobufs.a
import protobufs.b
Run Code Online (Sandbox Code Playgroud)
我收到b无法找到的导入错误a。如果我将_pb2.py文件输出到我的包的根目录中,我就没有这个问题。这在this issue中详细说明,但我不确定我是否遇到完全相同的问题。是否可以避免_pb2.py在我的包的根目录输出文件?
我实际上拥有的是两个相互引用的 protobuff,如下.proto文件中所示:
syntax = "proto3";
import "common.proto";
Run Code Online (Sandbox Code Playgroud)
在 Python 文件中,这被转换为:
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: persons.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf.internal import enum_type_wrapper
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
from google.protobuf import descriptor_pb2
# @@protoc_insertion_point(imports)
_sym_db = _symbol_database.Default()
import common_pb2 as common__pb2
Run Code Online (Sandbox Code Playgroud)
但是因为该文件protobufs位于 Python 包中调用的文件夹中,所以最后一行应该是import protobufs.common_pb2 as common__pb2and not import common_pb2 as common__pb2,但libprotoc不知道如何考虑该文件夹。
解决方案实际上非常简单。只需使用:
import "protobufs/common.proto";
Run Code Online (Sandbox Code Playgroud)
这应该会导致您的_pb2.py文件包含导入from protobufs import common_pb2 as protobufs_dot_common__pb2而不是当前导入。
当然,您需要相应地更新编译器的命令行。类似的东西:
protoc.exe protobufs\persons.proto --proto_path=. --python_out=.
Run Code Online (Sandbox Code Playgroud)