【问题标题】:How to avoid nested imports when compiling proto files from a java project into python modules将java项目中的proto文件编译成python模块时如何避免嵌套导入
【发布时间】:2020-11-17 06:48:01
【问题描述】:

例如在java项目中

myapp
└── src
    └── main
        └── proto
            └── com
                └── abc
                    └── myapp
                        └── api
                            ├── common.proto
                            └── myapp.proto
$ cat myapp/src/main/proto/com/abc/myapp/api/common.proto
syntax = "proto3";

package com.abc.myapp.api;

message Metadata {

  string key = 1;
}
$ cat myapp/src/main/proto/com/abc/myapp/api/myapp.proto
syntax = "proto3";

import "com/abc/myapp/api/common.proto";

package com.abc.myapp.api;

message Request {
    string name = 1;

    Metadata metada = 2;
}

将 protos 编译成 python 模块时

$ protoc -I myapp/src/main/proto --python_out=tmp  com/abc/myapp/api/common.proto 
$ protoc -I myapp/src/main/proto --python_out=tmp  com/abc/myapp/api/myapp.proto

输出结构是这样的

tmp
└── com
    └── abc
        └── myapp
            └── api
                ├── common_pb2.py
                └── myapp_pb2.py

而在myapp_pb2.py里面,import是非常嵌套和like的

from com.abc.myapp.api import common_pb2 as com_dot_abc_dot_myapp_dot_api_dot_common__pb2

有没有推荐的做法来使编译的 pb2 文件结构平坦?例如

tmp
├── common_pb2.py
└── myapp_pb2.py

并且myapp_pb2.py 具有类似的导入

from . import common_pb2 as ...

而不是

from com.abc.myapp.api import common_pb2 com.abc.myapp.api ...

【问题讨论】:

标签: java python protocol-buffers proto


【解决方案1】:

您可以使用您的 protobufs 在目录中创建一个 init 文件,然后添加以下代码:

# pb/__init__.py
import sys
from pathlib import Path
sys.path.append(str(Path(__file__).parent))

这应该允许您以您想要的方式导入文件。

请注意,您所要求的不是当前可用的功能,我提出的解决方案只是众多正在使用的解决方案之一。

对于许多 protobuf 的 python 用户来说,这是一个已知的刺激源,请参阅:https://github.com/protocolbuffers/protobuf/pull/7470 和 https://github.com/protocolbuffers/protobuf/issues/1491

【讨论】:

  • from com.abc.myapp.api import common_pb2 com.abc.myapp. 将如何工作?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-03
  • 1970-01-01
相关资源
最近更新 更多