0

My folder structure:

grpc/
    server.py
    client.py
    ...    
    src/
        __init__.py
        image_pb2.py
        image_pb2_grpc.py 
        ...

server.py

import image_pb2_grpc
import image_pb2

...

image_pb_grpc.py

import image_pb2
...

In summary, server depends on both image_pb2 and image_pb2_grpc, while image_pb2_grpc also depends on image_pb2.

Now, if I move my server.py inside the src folder, the code surely runs fine, as everything is in the path.

The problem is server.py should be outside the src folder.

Now, I can still solve the problem by changing server.py and image_pb2_grpc.py with:

server.py

from src import image_pb2_grpc
from src import image_pb2

...

image_pb_grpc.py

from src import image_pb2
...

The issue with this approach is, I need to change image_pb_grpc.py manually, as they are generated code from grpc, and they are generated using a bash script, so it is not possible to change them manually.

How can I organize my project so that I can run server outside src, while not changing image_pb2 or image_pb2_grpc?

Zabir Al Nazi
  • 10,298
  • 4
  • 33
  • 60
  • I am not sure, but try `from .src import ...` in `server.py` and `from . import image_pb2` in `image_pb_grpc.py`. Also add a empty `__init__.py` to the `src` folder. – user_na Jun 24 '21 at 20:26
  • @user_na as I told in my question, I can not change image_pb2 file as it's auto-generated. – Zabir Al Nazi Jun 24 '21 at 20:42

2 Answers2

0

I would suggest to add to your src/__init__.py following code:

import image_pb2_grpc
import image_pb2

Then your server.py will be able to import those both files simply by:

from src import image_pb2_grpc, image_pb2`

I haven't tried it but it should work.

Maciej M
  • 786
  • 6
  • 17
0

The correct way of running your script is:

$ cd grpc
$ python -m server # this is the one you want to run

Use the relative imports in server.py.

If this does not work I am afraid you need to hack sys.path - but this should be avoided at all cost

EDIT:

In server once you import the image_pb2 as in from .src import image_pb2 do

sys.modules['image_pb2'] = sys.modules['src.image_pb2']

then import image_pb2_grpc. Do not add any imports in __init__.py

Mr_and_Mrs_D
  • 32,208
  • 39
  • 178
  • 361