I emit the proto compilation into a generated_code/ directory(say communicator_pb2.py and communicator_pb2_grpc.py). Now, the grpc output imports the python code like so import communicator_pb2 as communicator__pb2; without having to modify the import path to import generated_code.communicator_pb2 as communicator__pb2 or append generated_code to sys.path, what is the most legal way to import if I were to import like:
import generate_code.commuinicator_pb2 as communicator_pb2
import generate_code.commuinicator_pb2_grpc as communicator_pb2_grpc
I've come up with an elegant solution (probably quite similar to what @Godric was telling in his answer). Suppose you have the following directory structure
service
├── main.py
└── generated_code/
├── __init__.py
├── communicator.proto
├── communicator_pb2.py
└── communicator_pb2_grpc.py
If you compile it the usual way, using grpc_tools (see here)
python -m grpc_tools.protoc --proto_path=service/generated_code --python_out=service/generated_code --grpc_python_out=service/generated_code
you would get the following import in generated_code/communicator_pb2_grpc.py
import communicator_pb2 as communicator__pb2
However, when you compile the files with
python -m grpc_tools.protoc --proto_path=. --python_out=. --grpc_python_out=. generated_code/communicator.proto
while sitting in service/ you obtain the desired result
import generated_code.communicator_pb2 as communicator_pb2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With