我们如何将Python生成的protobuf代码用于python代码?

时间:2015-04-01 11:37:34

标签: python protocol-buffers

我在Python 3.4中安装了protobuf,并将编译后的代码pb_x_pb2.py推送到python34文件夹中。当我输入import pb_x_pb2.py时,它会显示以下错误。

>>> import pb_interface_pb2
Traceback (most recent call last):
  File "<pyshell#21>", line 1, in <module>
    import pb_interface_pb2
  File "C:\Python34\pb_interface_pb2.py", line 5, in <module>
    from google.protobuf import reflection
  File "C:\Python34\lib\site-packages\google\protobuf\reflection.py", line 68, in <module>
    from google.protobuf.internal import python_message
  File "C:\Python34\lib\site-packages\google\protobuf\internal\python_message.py", line 848
    except struct.error, e:
                       ^
SyntaxError: invalid syntax

1 个答案:

答案 0 :(得分:2)

Protobuf并不真正支持python 3.x.对于导入的库,请尝试pip install protobuf-py3,即包的python 3端口。您还可以从生成的文件上的2to3.py文件夹中运行Pythonxx\Tools\Scripts脚本。

另一种选择是下载最新版本的源代码,并自行编译。我相信最新版本大多兼容2.x和3.x