python 多个proto文件import引用时出现ModuleNotFoundError错误

问题描述

my_proto文件夹里有两个proto文件,book.proto想要引用person.proto文件中的Person,如下
book.proto

syntax = "proto2";

import "person.proto"; // 导入person.proto文件

message Book {
	optional string name = 1;
	optional float price = 2;
	optional Person author = 3;
}

person.proto

syntax = "proto2";

message Person {
	optional string name = 1;
	optional float height = 2;
	optional int32 age = 3;
	optional SEX sex = 4 [ default = MALE ];
	repeated Phone phone = 5;

	message Phone {
		optionale string number = 1; 
		optional Type type = 2;
	}
	
	enum Type {
		HOME = 0;
		MOBILE = 1;
	}

	enum SEX {
		MALE = 0;
		FEMALE = 1;
	}
}

使用protoc编译protoc文件后,my_proto文件夹中的文件为:person.proto, book.proto, person_pb.py, book_pb.py
person_pb.py文件中出现以下引用

import person_pb2 as person__pb2

构建my_test.py进行测试

import string
from my_proto import person_pb2, book_pb2

book = book_pb2.Book()
book.name = "python"
book.price = 56.7
person = book.person

person.name = "test"
person.sex = 0
person.height = 175.3
person.age = 26

for i in range(2)
	tel = person.phone.add()
	tel.number = "".join(random.choice(string.digits) for k in range(11))
	tel.type = random.choice([0, 1])

serizalized_book = book.SerizalizeToString()
print(f"serizalized book {serizalized_book}")

new_book = book_pb.Book()
new_book.ParseFromString(serizalized_book)
print(f"deserizalized book {new_book}")

运行时报错:import person_pb2 as person__pb2
ModuleNotFoundError: No module named ‘person_pb2’

解决方案

ModuleNotFoundError错误通常都是由于引用路径的位置不正确导致的
方法一:

# 修改book_pb.py文件
# import person_pb.py as person__pb.py
from . import person_pb.py as person__pb.py

方法二:

# 在my_proto文件夹中增加__init__.py文件
import sys
import os

sys.path.append(os.path.dirname(__file__))

参考文章:https://qa.1r1g.com/sf/ask/3775421401/

你可能感兴趣的:(测开,python,proto,protobuf)