【工作向】protobuf编译生成pb.cc和pb.py文件

序言

  • 首先通过protoc --version查看protoc版本,避免pb文件生成方和使用方版本不一致

1. 生成pb.cc

  • 生成命令

    shell 复制代码
    protoc -I=${proto_file_dir} --cpp_out=${pb_file_dir} *.proto

    参数: -I表示 proto 文件的路径; --cpp_out 表示输出路径; 最后一个参数表示需要被编译为 pb.h 和 pb.cc 文件的 proto 文件, *.proto 表示 -I 路径下的所有 proto 文件

2. 生成pb.py

  • 生成命令

    shell 复制代码
    protoc -I=. --python_out=. person.proto	# 单个proto文件生成pb2.py文件
    protoc -I=. --python_out=. *.proto		# 所有proto文件生成pb2.py文件
  • proto包含:如果重新拷贝了所有.proto文件到同一目录下生成pb.py文件,请记得修改proto依赖路径,修改前后如下图


3. 导入pb2.py文件使用

  • 同级目录

    shell 复制代码
    import dir.test_pb2 as test__pb2
    或
    from dir import test_pb2 as test__pb2
  • 上级目录 :方法1,使用sys.path.append()

    shell 复制代码
    import sys
    sys.path.append('/path/to/another/directory')
    import another_module

    说明:sys.path是Python的搜索路径列表,它包含了模块搜索路径。我们可以向sys.path列表中添加另一个目录,使得Python可以在该目录中寻找模块文件

  • 上级目录 :方法2,使用相对路径

    shell 复制代码
    from ..another_directory import another_module

    说明:...表示上一级目录

  • 上级目录 :方法3,使用importlib

    shell 复制代码
    import importlib
    scenario_pb2 = importlib.import_module(".scenario_pb2", "protos")
    scenario_pb2 = importlib.import_module("protos.scenario_pb2")

【参考文章】

[1]. importlib用法

[2]. 如何从其他目录导入py文件, 推荐

[3]. linux下配置protobuf并编译生成pb.py文件

[4]. 从用protoc生成的pb2.py中反向工程.proto文件

created by shuaixio, 2024.03.06

相关推荐
GDAL5 天前
GeoPB: A Protobuf Solution for Efficient Geospatial Data Handling
javascript·protobuf·geopb
盒马盒马9 天前
Protobuf:基本概念与使用流程
google·protobuf
小冰子X1 个月前
ProtoBuf 详解
c++·protobuf
小欧欧11 个月前
关于Protobuf在使用中的一些注意点
protobuf
看到我请叫我滚去学习Orz2 个月前
【Protobuf】Protobuf 语法介绍
c++·protobuf
czl3892 个月前
gRPC golang开发实践
golang·grpc·protobuf
AskHarries2 个月前
Spring Boot集成protobuf快速入门Demo
java·spring boot·后端·protobuf
技术大白2 个月前
使用fastdds替换原有协议为protobuf
c++·protobuf·fastdds
时丶光2 个月前
解决protobuf.js 使用默认值的属性丢失问题
javascript·protobuf
[奋斗不止]2 个月前
Xml,Json,Protobuffer等序列化的区别。如何选型
xml·json·protobuf