2009-12-01 26 views
4

在使用我們的protobuf類生成的Python代碼,我們得到這個錯誤:爲什麼在使用Google Protocol Buffers時看到「無法導入name descriptor_pb2」錯誤?

cannot import name descriptor_pb2 

++生成的代碼等價的C工作得很好,所以這樣看來,有一個與我們的實際原定義沒有問題。

import sys 
sys.path.append('..\path\to\generated') 
sys.path.append('..\contrib\protobuf\python') 

from foobar_pb2 import FooBar 

是否正確追加系統的路徑:

這個錯誤,當我試圖導入我們班,像這樣發生?

我在protobuf\python\google\protobuf目錄中檢查了descriptor_pb2.py,但只發現descriptor.py - 我們使用的是最新版本,所以我假設我們沒有任何文件丟失。

有誰知道解決方案是什麼?

回答

6

我相信你已經產生descriptor_pb2.pyprotoc自己:

protoc descriptor.proto --python_out=gen/ 

是生成的Python類的文件夾。

之後,下面的作品就好了:

sys.path.append('../gen') 
from descriptor_pb2 import FileDescriptorSet 

../gen/descriptor_pb2.py必須存在。

+1

儘管生成descriptor_pb2.py文件後,我得到一個錯誤,說這個descriptor_pb2是指它在導入自我任何想法如何解決它 – 2013-07-11 07:21:29

2

請確保按照自述文件中的指示安裝protobuf運行時庫。您不能直接從包中直接使用源代碼,因爲descriptor_pb2.py需要由protoc(protobuf編譯器)生成,作爲安裝過程的一部分。

5

在我的情況下,沒有找到descriptor_pb2發生,因爲protobuf沒有正確安裝。 在protobuf的的蟒蛇子目錄,一定要運行

python setup.py build 
python setup.py test 
python setup.py install (as root) 
+0

謝謝!有用!! – KayKay 2014-01-23 09:08:38

+0

你也可以在'python setup.py build'步驟之後停下來,並指向build/lib目錄。 – teeks99 2018-01-05 15:20:47

0

蟒蛇的setup.py建立

這一步是必須的,因爲它產生了一些源文件。

Generating google/protobuf/descriptor_pb2.py... Generating google/protobuf/compiler/plugin_pb2.py... Generating google/protobuf/unittest_pb2.py... Generating google/protobuf/unittest_custom_options_pb2.py... Generating google/protobuf/unittest_import_pb2.py... Generating google/protobuf/unittest_import_public_pb2.py... Generating google/protobuf/unittest_mset_pb2.py... Generating google/protobuf/unittest_no_generic_services_pb2.py... Generating google/protobuf/internal/descriptor_pool_test1_pb2.py... Generating google/protobuf/internal/descriptor_pool_test2_pb2.py... Generating google/protobuf/internal/test_bad_identifiers_pb2.py... Generating google/protobuf/internal/missing_enum_values_pb2.py... Generating google/protobuf/internal/more_extensions_pb2.py... Generating google/protobuf/internal/more_extensions_dynamic_pb2.py... Generating google/protobuf/internal/more_messages_pb2.py... Generating google/protobuf/internal/factory_test1_pb2.py... Generating google/protobuf/internal/factory_test2_pb2.py... Generating google/protobuf/pyext/python_pb2.py... bla...

恰恰是 'descriptor_pb2.py'

1

我使用Python 2.7在Windows 10

就我而言,我已經下載protoc-3.0.0-β-2-win32的從https://github.com/google/protobuf/releases並將二進制protoc文件複製到src文件夾。

之後,我運行命令python setup.py build並且生成了descriptor_pb2。

相關問題