2015-04-01 78 views
2

我已经在Python 3.4中安装了protobuf,并且我将已编译的代码pb_x_pb2.py推送到python34文件夹中。当我输入import pb_x_pb2.py时,它显示以下错误。我们如何在Python代码中使用Python生成的protobuf代码?

>>> 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 
+0

你为Python 3编译过吗?语法看起来像Python 2. – 2015-04-01 11:40:56

+0

哦!这意味着我只能使用Python 2.7? – raghu 2015-04-01 11:44:56

+0

Protobuffer应该在3.x下支持。但是,如果您为Python 2.x编译,结果将仅在2.x下运行。你是如何将Protobuffer文件编译为Python的? – 2015-04-01 11:46:26

回答

2

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

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

+0

我已经尝试在python2.7版本本身,但仍面临同样的问题。我使用'pip安装protobuf'安装protobuf。但是当我在空闲时输入“protobuf”时,它会显示导入错误,表示没有可用的模块。要使用该编译的Python protobuf代码,我相信应该导入protobuf。你能否清楚地告诉步骤使用protobuf代码,因为Iam new在这里我无法关注你。 – raghu 2015-04-01 13:38:07

+0

听起来好像您没有使用与您安装的位置相同的安装中的空闲位置。你有多个版本的Python安装? – horns 2015-04-01 14:36:15