当我获取一个简单的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)中使用
^{pr2}$
我有两个不错的文件:hello_pb2.py和{}
简单的两条线操场.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
import hello_pb2
File "/py/hello_pb2.py", line 16, in
import timestamp_pb2 as timestamp__pb2
ImportError: No module named 'timestamp_pb2
这是因为hello_pb2.py现在有一行:import timestamp_pb2 as timestamp__pb2
我尝试了一点不同操场.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
import hello_pb2
File "/py/hello_pb2.py", line 25, in
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)