【发布时间】:2018-04-03 20:18:46
【问题描述】:
当我拿一个简单的hello.proto 文件时
syntax = "proto3";
package helloworld;
//import "timestamp.proto";
service Greeter {
rpc SayHello (HelloRequest) returns (HelloReply) {}
}
message HelloRequest {
string name = 1;
//google.protobuf.Timestamp smth = 2;
}
message HelloReply {
string message = 1;
}
并且(在virtualenv -p python3 py内)使用
python -m grpc_tools.protoc -I. --python_out=. --grpc_python_out=. ./hello.proto
我得到了两个不错的文件:hello_pb2.py 和 hello_pb2_grpc.py
还有一个简单的两行playground.py:
import hello_pb2
import hello_pb2_grpc
与python playground.py 配合得很好
一切都会改变,当尝试使用众所周知的 protobuf 类型、时间戳和取消注释第 3 行和第 9 行时。
我在站点包中看到的最接近的对应文件timestamp.proto:
$ find -name timestamp\*
./lib/python3.5/site-packages/grpc_tools/_proto/google/protobuf/timestamp.proto
./lib/python3.5/site-packages/google/protobuf/timestamp_pb2.py
./lib/python3.5/site-packages/google/protobuf/__pycache__/timestamp_pb2.cpython-35.pyc
所以我使用了一些不同的代码生成命令:
python -m grpc_tools.protoc -I. \
-I./lib/python3.5/site-packages/grpc_tools/_proto/google/protobuf \
--python_out=. --grpc_python_out=. ./hello.proto
但python playground.py 现在会导致错误:
Traceback (most recent call last):
File "playground.py", line 1, in <module>
import hello_pb2
File "/py/hello_pb2.py", line 16, in <module>
import timestamp_pb2 as timestamp__pb2
ImportError: No module named 'timestamp_pb2
那是因为hello_pb2.py 现在有一行:
import timestamp_pb2 as timestamp__pb2
我尝试了一些不同的 playground.py:
import sys
sys.path.append('./lib/python3.5/site-packages/google/protobuf')
import hello_pb2
import hello_pb2_grpc
但这会导致不同的错误:
$ python playground.py
Traceback (most recent call last):
File "playground.py", line 3, in <module>
import hello_pb2
File "/py/hello_pb2.py", line 25, in <module>
dependencies=[timestamp__pb2.DESCRIPTOR,])
File "/py/lib/python3.5/site-packages/google/protobuf/descriptor.py", line 829, in __new__
return _message.default_pool.AddSerializedFile(serialized_pb)
TypeError: Couldn't build proto file into descriptor pool!
Invalid proto descriptor for file "hello.proto":
hello.proto: Import "timestamp.proto" has not been loaded.
helloworld.HelloRequest.smth: "google.protobuf.Timestamp" seems to be defined in "google/protobuf/timestamp.proto", which is not imported by "hello.proto". To use it here, please add the necessary import.
所以,我没有想法。如何在python中使用这个众所周知的类型(3)?
详细信息:ubuntu:xenial、python 3.5.2、virtualenv 15.2.0、
env:virtualenv -p python3 py && cd py && source bin/activate && pip install grpcio grpcio_tools(这会安装 protobuf-3.5.2、grpcio-1.10.0、grpcio_tools-1.10.0)
【问题讨论】:
-
我怀疑这更像是一个 Protocol Buffers Python 问题而不是一个 gRPC Python 问题(从你的命令行中取出
--grpc_python_out=.,我敢打赌你的问题仍然存在)但我会接受一个镜头:你为什么认为你需要“import timestamp.proto;”在您的.proto文件中?你能只取消第 9 行的注释并看到一切正常吗? -
当我单独取消注释第 9 行时,我在生成期间得到
hello.proto:9:3: "google.protobuf.Timestamp" is not defined.。 (但谢谢)
标签: python python-3.x protocol-buffers grpc