5

When I try to generate files with the command

python -m grpc_tools.protoc -I./ --python_out=. --grpc_python_out=. service.proto

I get error.

Traceback:
test_client.py:11: in <module>
    from tests.remote.grpc_wrapper.service_pb2_grpc import TestServiceServicer, add_TestServiceServicer_to_server, \
service_pb2_grpc.py:4: in <module>
    import service_pb2 as service__pb2
E   ModuleNotFoundError: No module named 'service_pb2'

How can I fix it? I truing reinstall protobuf but it don’t help me.

pip uninstall protobuf
pip install -U protobuf

P.S. I use conda, I truing use

conda install protobuf

but it don’t help me too.

enter image description here

user45245
  • 845
  • 1
  • 8
  • 18
  • your error is here `service_pb2` no module . install it – sahasrara62 Dec 26 '18 at 16:31
  • @prashantrana, `service_pb2` is OP's filename. It's not a lib. @user45245, from which folder are you trying to run the python command, `python -m grpc_tools.protoc -I./ --python_out=. --grpc_python_out=. service.proto` – Soumendra Dec 26 '18 at 16:38
  • (venv) C:\Users\Valentin\PycharmProjects\protoactor-python\tests\remote\grpc_wrapper>python -m grpc_tools.protoc -I./ --python_out=. --grpc_python_out=. service.proto – user45245 Dec 26 '18 at 16:40
  • I have found a solution. Use "from . import" in _pb2_grpc.py for example from . import service_pb2 as service__pb2 – user45245 Dec 27 '18 at 09:07

1 Answers1

9

There's talk of specifying this at the point of generation in the .proto file in this issue. As far as I know you have two options currently:

1) Change your line 4 to have . in front (this signifies a relative import):

from . import service_pb2 as service__pb2

2) Change the __init__.py file in the "grpc_wrapper" folder to include:

import os
import sys
sys.path.insert(0, os.path.abspath(os.path.dirname(__file__)))
Ed Harrod
  • 3,423
  • 4
  • 32
  • 53
  • 1
    here's a shell command to replace it the package name - $target - with proper syntanx (e.g. in github action) `find $REPOPATH/$reponame/ -type f -name "*.py" -print0 | xargs -0 sed -i -e 's, import '"$target"'_pb2, from . import '"$target"'_pb2, g'` – joshp Dec 16 '21 at 18:37