使用环境
- python: 2.7.16
- protoc: libprotoc 3.15.6
- pip: 20.3.4
- pip show protobuf: 3.15.8
环境安装说明
Python 2+ 自己安装
pip 安装
-
https://bootstrap.pypa.io/pip/2.7/get-pip.py -o get-pip.py
(该包适用于 python 2+, python 3+ 请使用
curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py
) -
sudo python get-pip.py
-
验证 pip
-
pip --version
pip 20.3.4 from /Library/Python/2.7/site-packages/pip (python 2.7)
-
使用 pip 安装 protobuf
-
pip install --upgrade protobuf
-
验证
-
pip show protobuf
Name: protobuf
Version: 3.15.8
Summary: Protocol Buffers
Home-page: developers.google.com/protocol-bu…
Author: None
Author-email: None
License: 3-Clause BSD License
Location: /Users/admin/Library/Python/2.7/lib/python/site-packages
Requires: six
Required-by:
-
安装 protoc 命令
-
brew install protobu
-
验证
-
protoc --version
libprotoc 3.15.6
-
注意
- 这里要确保的是pip安装的protobuf版本号要高于protoc的版本号
将 proto 文件转化成 json 文件
-
克隆 git仓库
-
准备一个 proto 文件, 假定其路径为 /Users/admin/pb/proto/test.proto
-
生产 proto 的 python 类
protoc --proto_path=src/ --python_out=build/gen src/test.proto
- --proto_path指定了src/test.proto所在的源目录(因为这里proto可以import互相包含,所以需包含可能import的基proto的源目录)
- --python_out指定了生成目录
- src/test.proto需要根据proto生成的文件
-
执行命令
protoc --proto_path=/Users/admin/pb/proto/ --python_out=/Users/admin/pb/build/ /Users/admin/pb/proto/test.proto 复制代码
将生成
/Users/admin/pb/build/test_pb2.py
-
生产json文件
-
将下列代码中的
import test_pb2 as pb_test
中的 test_pb2 修改成你生成的proto 的 python 类, 也就是 /Users/admin/pb/build/test_pb2.py;#! /usr/bin/env python import os, sys # set import path to app root sys.path.insert(0, os.path.dirname(os.path.dirname(__file__))) import protobuf_json_writer from pprint import pprint import test_pb2 as pb_test # print protobuf_json_writer._msg2json(pb_test.TestMessage.DESCRIPTOR) print protobuf_json_writer.proto2json(pb_test) 复制代码
-
运行
python test_writer.py
-
可以看见输出的 json
-
近期评论