当前位置:   article > 正文

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

protoc import not found

问题描述

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;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

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;
	}
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24

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

import person_pb2 as person__pb2
  • 1

构建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}")
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24

运行时报错: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
  • 1
  • 2
  • 3

方法二:

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

sys.path.append(os.path.dirname(__file__))
  • 1
  • 2
  • 3
  • 4
  • 5
'
运行

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

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/码创造者/article/detail/794539
推荐阅读
相关标签
  

闽ICP备14008679号