Roy Styles
Roy Styles

Reputation: 31

importing a protobuf dependency from a separate directory in python

I have two protobuf messages located in separate directories. One message is nested in the other. Basically, something like this:

import "msg1.proto";

message Message2 {
    optional Message1 message1 = 1;
}

Where the files are as follows:

dir
+---dir1
|       msg1.proto
|
\---dir2
    |   msg2.proto

The auto-generated file msg2_pb.py contains the line import msg1_pb. The problem is that msg1_pb.py and msg2_pb.py are located in different directories, thus the import fails.

Is there some flag I can add so that msg1_pb and msg2_pb will compile in such a way that they'll be more aware of the directory structure?

Currently, when compiling msg2, my command-line looks like this:

protoc.exe --proto_path=dir1 --python_out=out msg2.proto

Upvotes: 3

Views: 2518

Answers (1)

rkaramc
rkaramc

Reputation: 51

Roy,

You may have found the solution already! Anyway, here goes...

I have used two methods to resolve this, either should work for you:

  1. Add the folder containing the generated protobuf classes to sys.path

    sys.path.append('/.../dir/out')
    
  2. Edit the generated protobuf classes to use absolute paths for import

    # msg2_pb.py
    from out import msg1_pb
    

I prefer the 2nd approach myself (avoids messing with sys.path; protobuf classes are re-generated rarely if ever).

Upvotes: 4

Related Questions