<h2>注意事项</h2>
<p>我错误地安装了<code>protobuf3</code>-我以为它是<code>protobuf3</code>Python包,但它是一个非官方的python3protobuf2包</strong>,而不是相反。在你开始之前把它取下来。在</p>
<h2>解决方案</h2>
<p>经过一番反复试验,以下解决方案奏效了。如果你有更好的/官方的,请随时发布。在</p>
<h2>先决条件:Protobuf3</h2>
<ul>
<li>删除<code>protobuf2</code>(我使用了<code>brew uninstall</code>)。确保<code>protoc</code>不出现在路径中。在</li>
<li>安装<a href="https://github.com/google/protobuf/releases/tag/v3.0.0" rel="nofollow">^{<cd1>}</a>二进制文件。还没有自制软件包,所以我使用了OSX二进制文件<code>protoc-3.0.0-osx-x86_64.zip</code>。<code>make</code>脚本也是一个选项。
<ul>
<li>将<code>bin</code>目录的内容复制到<code>/usr/local/bin</code></li>
<li>将<code>include</code>的内容复制到<code>/usr/local/include</code></li>
</ul></li>
<li>确保protobuf3已安装-<code>protoc version</code>应该显示<code>libprotoc 3.0.0</code>。在</li>
</ul>
<h2>Python安装</h2>
<ul>
<li>创建虚拟环境</li>
<li>将<a href="https://github.com/google/protobuf" rel="nofollow">master branch of ^{<cd15>}</a>下载到<code>/tmp</code></li>
<li>激活虚拟环境</li>
<li><code>cd protobuf-master/python && setup.py install</code></li>
</ul>
<h2>代码</h2>
<p>相关函数是<code>google.protobuf.json_format module</code>中的<code>MessageToJson</code>:</p>
<pre><code>from google.protobuf import json_format
o = SomeProtobufClass()
print json_format.MessageToJson(o)
{
...
}
</code></pre>