简体   繁体   English

Protobuf,python3.6编译后导入报错

[英]Protobuf, import error after compilation in python3.6

Directory structure:目录结构:

Application/
   proto/
     payload.proto
     lab_account.proto
     public_trail.proto
   protocompiled/
     payload_pb2.py
     lab_account_pb2.py

Contents of the payload.proto payload.proto 的内容

syntax = "proto3";
import "lab_account.proto";
import "public_trail.proto";

if I compile my payload.proto file, with command .如果我使用命令编译我的 payload.proto 文件。

 Application⟫ protoc --proto_path=./proto --python_out=./protocompiled payload.proto

The compiled payload_pb2.py doest have the required imports.编译后的 payload_pb2.py 没有所需的导入。 It has wrong import statement like this.它有这样的错误导入语句。

 import lab_account_pb2 as lab__account__pb2
 import public_trail_pb2 as public__trail__pb2

instead of this;而不是这个;

 import protocompiled.lab_account_pb2 as lab__account__pb2
 import protocompiled.public_trail_pb2 as public__trail__pb2

Also referred, https://github.com/protocolbuffers/protobuf/issues/1491 but couldnt solve the issue.也提到, https://github.com/protocolbuffers/protobuf/issues/1491但无法解决问题。

There is an open issue 5374 in protobuf github regarding this problem. protobuf github 中有一个关于此问题的未解决问题 5374

Until it is resolved, I use the following workaround: after protoc run a sed script (works at least for GNU sed ) which will add relative imports.在解决之前,我使用以下解决方法:在protoc运行一个 sed 脚本(至少适用于 GNU sed )之后,它将添加相对导入。

protoc $PATH/*.proto --python_out=$PROTOC_OUTDIR
sed -i $PROTOC_OUTDIR/*_pb2.py -e 's/^import [^ ]*_pb2/from . \0/'

But this works only when all files are in the same directory.但这只有在所有文件都在同一目录中时才有效。 More complex script will be required to handle files spread over multiple directories.将需要更复杂的脚本来处理分布在多个目录中的文件。

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

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