Python 项目使用协议缓冲区,部署问题

Python project using protocol buffers, Deployment issues

我有一个使用 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 文件,该项目将按预期运行。因此,分发编译后的文件似乎不是一种选择。

有点想在这里寻找可行的最佳实践解决方案。可以假设目标平台上安装了protoc-compiler。

编辑:

既然有人问失败的原因。在 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

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

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

来完成
# 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 以添加构建和清理协议缓冲区。

# 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 上完美运行。

另一种解决方案是将 protobuf 库与您的应用捆绑在一起,而不是使用目标机器上安装的版本。这样你就知道生成的代码没有版本不匹配。

我刚刚启动 protobuf-setuptools 包以使用此代码中最合理的部分。它仍然需要改进,所以欢迎任何反馈!

查看:https://pypi.python.org/pypi/protobuf-setuptools