gpt4 book ai didi

使用 Protocol Buffer 的 Python 项目,部署问题

转载 作者:太空狗 更新时间:2023-10-29 17:59:25 25 4
gpt4 key购买 nike

我有一个使用 setuptools 进行部署的 Python 项目,我主要关注 this guide关于项目结构。该项目使用 Google Protocol Buffers 来定义网络消息格式。我的主要问题是如何让 setup.py 在安装期间调用 protoc-compiler 以将定义构建到 _pb2.py 文件中。

this question建议只将生成的 _pb2.py 文件与项目一起分发。虽然这可能适用于非常相似的平台,但我发现了几种情况下它不起作用。例如,当我在使用 Anaconda Python 的 Mac 上进行开发并将生成的 _pb2.py 与项目的其余部分一起复制到运行 Raspbian 的 Raspberry Pi 时,总是会出现来自 _pb2.py 模块的导入错误。但是,如果我在 Pi 上重新编译 .proto 文件,该项目将按预期运行。因此,分发编译后的文件似乎不是一种选择。

有点想在这里寻找可行的最佳实践解决方案。可以假定目标平台上安装了协议(protocol)编译器。

编辑:

既然有人问失败的原因。在 Mac 上,protobuf 版本为 2.6.1。在 Pi 上是 2.4.1。显然,生成的 protoc 编译器输出使用的内部 API 已更改。输出基本上是:

  File "[...]network_manager.py", line 8, in <module>
import InstrumentControl.transports.serial_bridge_protocol_pb2 as protocol
File "[...]serial_bridge_protocol_pb2.py", line 9, in <module>
from google.protobuf import symbol_database as _symbol_database
ImportError: cannot import name symbol_database

最佳答案

好的,我解决了这个问题,不需要用户安装特定的旧版本或在我的开发机器之外的另一个平台上编译原型(prototype)文件。它的灵感来自 this setup.py script from protobuf itself .

首先,需要找到协议(protocol),这可以使用

# Find the Protocol Compiler.
if 'PROTOC' in os.environ and os.path.exists(os.environ['PROTOC']):
protoc = os.environ['PROTOC']
else:
protoc = find_executable("protoc")

此函数将编译一个 .proto 文件并将 _pb2.py 放在同一位置。然而,行为可以任意改变。

def generate_proto(source):
"""Invokes the Protocol Compiler to generate a _pb2.py from the given
.proto file. Does nothing if the output already exists and is newer than
the input."""

output = source.replace(".proto", "_pb2.py")

if (not os.path.exists(output) or
(os.path.exists(source) and
os.path.getmtime(source) > os.path.getmtime(output))):
print "Generating %s..." % output

if not os.path.exists(source):
sys.stderr.write("Can't find required file: %s\n" % source)
sys.exit(-1)

if protoc == None:
sys.stderr.write(
"Protocol buffers compiler 'protoc' not installed or not found.\n"
)
sys.exit(-1)

protoc_command = [ protoc, "-I.", "--python_out=.", source ]
if subprocess.call(protoc_command) != 0:
sys.exit(-1)

接下来,派生类 _build_py 和 _clean 以添加构建和清理 Protocol Buffer 。

# List of all .proto files
proto_src = ['file1.proto', 'path/to/file2.proto']

class build_py(_build_py):
def run(self):
for f in proto_src:
generate_proto(f)
_build_py.run(self)

class clean(_clean):
def run(self):
# Delete generated files in the code tree.
for (dirpath, dirnames, filenames) in os.walk("."):
for filename in filenames:
filepath = os.path.join(dirpath, filename)
if filepath.endswith("_pb2.py"):
os.remove(filepath)
# _clean is an old-style class, so super() doesn't work.
_clean.run(self)

最后是参数

cmdclass = { 'clean': clean, 'build_py': build_py }   

需要添加到对设置的调用中,一切都应该有效。仍然需要检查可能的怪癖,但到目前为止它在 Mac 和 Pi 上运行完美。

关于使用 Protocol Buffer 的 Python 项目,部署问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27843481/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com