如何在 Windows 上为 Python 使用协议缓冲区?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21196648/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 22:16:13  来源:igfitidea点击:

How can I use protocol buffers for Python on windows?

pythonprotocol-buffersprotoc

提问by user2399973

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.pyfrom my myProto.protofile, but when I get the following error when I run my Python program:

我一直在尝试在我的 Python 程序中使用协议缓冲区,但无法让它工作。我正在运行 Windows 8 机器并尝试过 Python 2.7.6 和 Python 3.3。我下载了 Python 的二进制协议缓冲区编译器并用它myProto_pb2.py从我的myProto.proto文件中生成,但是当我运行我的 Python 程序时出现以下错误:

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

在“import myProto_pb2”行中,使用协议缓冲区版本 2.5 中的 Python 2.7.6 时出现以下错误:

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?

如何在 Windows 上从 Python 正确安装和运行协议缓冲区?

回答by abarnert

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

如何在 Windows 上从 Python 正确安装和运行协议缓冲区?

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 mightwork, 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 importsomething else… exactly as you're seeing.

与任何其他软件包一样,如果您希望安装它,则必须实际安装它。如果您只是尝试使用位于源目录中的包运行,它可能会起作用,但大多数包不会以这种方式运行;您往往会得到诸如顶级 package 之类的东西import,然后当它尝试import其他东西时会失败几行……正如您所看到的。

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 pythondirectory are complete instructions for installing it. Basically:

我相信一个可安装的包来自 GoogleCode 的主下载包。至少它适用于源程序包,如果不是 win32 程序包。而且内侧python目录是安装它的完整说明。基本上:

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 pipinstalled:

但是,如果 win32 预构建包没有提供,或者您不再拥有它,或者您只是更喜欢从 PyPI 安装,它也可以在那里获得。所以,假设你已经pip安装

pip install protobuf