问题
今天在运行一个之前写的python程序时,报错如下:
Traceback (most recent call last):
File "transfer-newclient.py", line 18, in <module>
import didi_protocol_clientsdk_pb2
File "./pb/didi_protocol_clientsdk_pb2.py", line 5, in <module>
from google.protobuf import descriptor as _descriptor
File "/usr/lib/python2.7/site-packages/google/protobuf/descriptor.py", line 117
class DescriptorBase(metaclass=DescriptorMetaclass):
SyntaxError: invalid syntax
分析
因为能确认该代码之前是能运行成功的,因此排除是代码的问题。同时怀疑是依赖的包版本发生了变化(在公共服务器上,有root权限的人都能随意改动)。根据错误提示,去看了python protobuf包的版本号,使用以下命令
pip show [package] // 展示当前安装package的信息,包含版本号
pip show protobuf
You are using pip version 7.1.0, however version 22.3.1 is available.
You should consider upgrading via the 'pip install --upgrade pip' command.
---
Metadata-Version: 2.1
Name: protobuf
Version: 4.21.6
Summary: Protocol Buffers
Home-page: https://developers.google.com/protocol-buffers/
Author: None
Author-email: None
License: BSD-3-Clause
Location: /usr/lib/python2.7/site-packages
Requires:
好嘛,使用的版本是4.21,明显高于代码中使用到的版本号。
因此首先卸载该包,同时安装符合预期的版本
pip uninstall [package] // 卸载package
pip install [package]== // 查看包有哪些适用版本
pip install -v [package]==[version] // 安装指定版本的包
最后确认一下protobuf包版本是否降级成功
pip show protobuf
You are using pip version 7.1.0, however version 22.3.1 is available.
You should consider upgrading via the 'pip install --upgrade pip' command.
---
Metadata-Version: 1.0
Name: protobuf
Version: 2.5.0
Summary: Protocol Buffers
Home-page: http://code.google.com/p/protobuf/
Author: protobuf@googlegroups.com
Author-email: protobuf@googlegroups.com
License: New BSD License
Location: /usr/lib/python2.7/site-packages
Requires: setuptools
问题解决