How can I use protocol buffers for Python on windo

2019-02-06 21:30发布

问题:

I have been trying to use protocol buffers in my Python program, but cannot get it to work. I'm running a Windows 8 machine and have tried Python 2.7.6 and Python 3.3. I downloaded the binary protocol buffer compiler for Python and used it to generate myProto_pb2.py from my myProto.proto file, but when I get the following error when I run my Python program:

from the "import myProto_pb2" line, I get the following error when using Python 2.7.6 from protocol buffers version 2.5:

from google.protobuf import descriptor as _descriptor
  ImportError: No module named google.protobuf

How can I correctly install and run protocol buffers from Python on Windows?

回答1:

How can I correctly install and run protocol buffers from Python on Windows?

Like any other package, you have to actually install it if you want it to be installed. If you just try to run with the package sitting in your source directory, it might work, but most packages don't work that way; you tend to get things like the top-level package importing and then failing a few lines down when it tries to import something else… exactly as you're seeing.

I believe an installable package comes in the main download package from GoogleCode. At least it does for the source packages, if not the win32 package. And inside the python directory are complete instructions for installing it. Basically:

C:\path\to\protobuf-2.5.0> cd python
C:\path\to\protobuf-2.5.0\python> python setup.py build
C:\path\to\protobuf-2.5.0\python> python setup.py test
C:\path\to\protobuf-2.5.0\python> python setup.py install

But if that doesn't come with the win32 pre-built package, or you don't have it lying around anymore, or you just prefer to install off PyPI, it's also available there. So, assuming you've got pip installed:

pip install protobuf